<template>
  <div class="productInfoEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="productInfoEdit-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="productInfoEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        </template>
      </a-page-header>
      <a-form-model
        id="productInfoEdit-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol">
        <a-card :bordered="false" class="productInfoEdit-cont">
          <a-row>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="产品名称" prop="name">
                <a-input v-model.trim="form.name" id="productInfoEdit-name" :maxLength="100" allowClear placeholder="请输入产品名称(最多100个字符)" />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="产品编码" prop="code">
                <a-input
                  id="productInfoEdit-code"
                  :maxLength="100"
                  :disabled="form.state&&form.state!='WAIT'"
                  v-model.trim="form.code"
                  placeholder="请输入产品编码(最多100个字符)"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="原厂编码" prop="origCode">
                <a-input
                  id="productInfoEdit-origCode"
                  :maxLength="200"
                  v-model.trim="form.origCode"
                  placeholder="请输入(最多200个字符，多个编码用逗号隔开)"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="其他编码" prop="otherCode">
                <a-input
                  id="productInfoEdit-otherCode"
                  :maxLength="60"
                  v-model.trim="form.otherCode"
                  placeholder="请输入(最多60个字符，多个编码用逗号隔开)"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="产品品牌" prop="productBrandSn">
                <a-select
                  id="productInfoEdit-productBrand"
                  placeholder="请选择产品品牌"
                  allowClear
                  v-model="form.productBrandSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in productBrandList" :key="item.brandSn" :value="item.brandSn" :disabled="item.enabledFlag==0">{{ item.brandName }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="产品分类" prop="productType">
                <a-cascader
                  :disabled="form.state&&form.state!='WAIT'"
                  expand-trigger="hover"
                  @change="changeProductType"
                  :options="productTypeList"
                  :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                  id="productInfoEdit-productType"
                  placeholder="请选择产品分类"
                  allowClear
                  v-model="form.productType" />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="单位" prop="unit">
                <v-select
                  code="PRODUCT_UNIT"
                  id="productInfoEdit-unit"
                  v-model="form.unit"
                  allowClear
                  placeholder="请选择单位"
                ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="包装数" prop="packQty" :label-col="{span:4}" :wrapper-col="{span:16}">
                <a-input-number
                  id="productInfoEdit-packQty"
                  v-model="form.packQty"
                  :precision="0"
                  :min="1"
                  :max="99999999"
                  placeholder="请输入"
                />
                <span style="margin: 0 5px;">/</span>
                <v-select
                  code="PRODUCT_PACK_UNIT"
                  id="productInfoEdit-packQtyUnit"
                  v-model="form.packQtyUnit"
                  allowClear
                  style="width: 100px;"
                  placeholder="单位"
                ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="箭冠产品" prop="arrowFalg">
                <v-select
                  code="ARROW_FALG"
                  id="productInfoEdit-arrowFalg"
                  v-model="form.arrowFalg"
                  allowClear
                  placeholder="请选择"
                ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="条形码" prop="qrCode">
                <a-input
                  id="productInfoEdit-qrCode"
                  :maxLength="50"
                  v-model.trim="form.qrCode"
                  placeholder="请输入条形码(最多50个字符)"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="出库仓库" prop="outWarehouseSn">
                <chooseWarehouse ref="outWarehouse" id="productInfoEdit-outWarehouse" isPermission v-model="form.outWarehouseSn"></chooseWarehouse>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="退货仓库" prop="returnWarehouseSn">
                <chooseWarehouse ref="returnWarehouse" id="productInfoEdit-returnWarehouse" isPermission v-model="form.returnWarehouseSn"></chooseWarehouse>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
              <a-form-model-item label="产品图片" help="说明：图片比例1:1，尺寸大于300*300px，首张为主图，最多5张。" :label-col="{span:3}" :wrapper-col="{span:18}">
                <Upload
                  class="upload"
                  id="productInfoEdit-productMsg"
                  v-model="form.productMsg"
                  ref="productMsg"
                  @change="changeImage"
                  :maxNums="5"
                  listType="picture-card" ></Upload>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="产品尺寸" prop="size">
                <a-input
                  v-model.trim="form.size"
                  id="productInfoEdit-size"
                  :maxLength="50"
                  allowClear
                  placeholder="请输入产品尺寸(最多50个字符)" />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="产品重量(g)" prop="weight">
                <a-input-number
                  style="width:80%;"
                  :precision="0"
                  id="productInfoEdit-weight"
                  v-model="form.weight"
                  :min="1"
                  :max="999999"
                  placeholder="请输入产品重量，注意单位为g（正整数）"/>
                <span v-if="form.weight">（{{ form.weight/1000 }}kg）</span>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="颜色" prop="color">
                <a-input
                  v-model.trim="form.color"
                  id="productInfoEdit-color"
                  :maxLength="50"
                  allowClear
                  placeholder="请输入颜色(最多50个字符)" />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="产品内盒尺寸" prop="boxSize">
                <a-input
                  v-model.trim="form.boxSize"
                  id="productInfoEdit-boxSize"
                  :maxLength="50"
                  allowClear
                  placeholder="请输入产品内盒尺寸(最多50个字符)" />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="产品说明" prop="description" :label-col="{span:2}" :wrapper-col="{span:20}">
                <editor id="productInfoEdit-description" ref="editor" class="productInfoEdit-description" @on-change="editorDescriptionChange" :cache="false"></editor>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="其他说明" prop="otherDesc" :label-col="{span:2}" :wrapper-col="{span:20}">
                <editor id="productInfoEdit-otherDesc" ref="otherDesc" class="productInfoEdit-otherDesc" @on-change="editorOtherChange" :cache="false"></editor>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        class="button-primary"
        :disabled="spinning"
        id="productInfoEdit-submit-btn"
        size="large"
        @click="handleSubmit"
        style="padding: 0 60px;">保存</a-button>
    </div>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { VSelect, Upload } from '@/components'
import Editor from '@/components/WEeditor'
import chooseWarehouse from '@/views/common/chooseWarehouse'
// 接口
import { productSave, productSnDetail } from '@/api/product'
import { productTypeQueryAll } from '@/api/productType'
import { productBrandQuery } from '@/api/productBrand'
export default {
  name: 'ProductInfoEdit',
  mixins: [commonMixin],
  components: { VSelect, Upload, Editor, chooseWarehouse },
  data () {
    return {
      spinning: false,
      formItemLayout: {
        labelCol: { span: 4 }, // label 标签布局
        wrapperCol: { span: 16 }// 输入控件布局
      },
      form: {
        name: '', // 产品名称
        code: '', //  产品编码
        origCode: '', //  原厂编码
        otherCode: '', // 其他编码
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        productType: [], //  产品分类
        unit: undefined, //  单位
        packQty: '', // 包装数
        packQtyUnit: undefined, // 包装数单位
        arrowFalg: undefined, // 是否箭冠产品
        qrCode: '', // 条形码
        productMsg: '', //  产品图片
        size: '', // 产品尺寸
        weight: undefined, // 产品重量
        color: undefined, // 颜色
        boxSize: '', // 内核尺寸
        description: '', // 产品说明
        otherDesc: '', // 其他说明
        outWarehouseSn: undefined, // 出库仓库
        returnWarehouseSn: undefined// 退货仓库
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'change' }
          // { validator: validateSpecialCharacter, trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入产品编码', trigger: 'change' }
          // { validator: validateSpecialCharacter, trigger: 'change' }
        ],
        origCode: [
          // { validator: validateSpecialCharacter, trigger: 'change' }
        ],
        productBrandSn: [
          { required: true, message: '请选择产品品牌', trigger: 'change' }
        ],
        productType: [
          { required: true, message: '请选择产品分类', trigger: 'change' }
        ],
        unit: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        packQty: [
          { required: true, message: '请输入包装数', trigger: 'change' }
        ],
        arrowFalg: [
          { required: true, message: '请选择是否为箭冠产品', trigger: 'change' }
        ],
        outWarehouseSn: [
          { required: true, message: '请选择出库仓库', trigger: 'change' }
        ],
        returnWarehouseSn: [
          { required: true, message: '请选择退货仓库', trigger: 'change' }
        ],
        qrCode: [
          { required: false, message: '请输入条形码', trigger: 'change' },
          { validator: this.validateQrCode }
        ]
      },
      productBrandList: [], //  品牌下拉数据
      productTypeList: [] //  分类下拉数据
    }
  },
  methods: {
    //  获取编辑回显数据
    getDetail () {
      productSnDetail({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.form = Object.assign(this.form, data)
          // 产品分类回显赋值
          this.form.productType = [ this.form.productTypeSn1, this.form.productTypeSn2, this.form.productTypeSn3 ]
          // 产品图片回显
          if (res.data.productPicList && res.data.productPicList.length > 0) {
            let str = ''
            res.data.productPicList.map(item => {
              if (item.imageUrl) {
                str += item.imageUrl + ','
              }
            })
            str = str.substr(0, str.length - 1)
            this.$refs.productMsg.setFileList(str)
            this.form.productMsg = str
          } else {
            this.$refs.productMsg.setFileList('')
            this.form.productMsg = ''
          }
          // 产品说明回显
          this.$refs.editor.setHtml(res.data.description)
          this.$refs.otherDesc.setHtml(res.data.otherDesc)
        } else {
          this.$refs.ruleForm.resetFields()
        }
      })
    },
    // 提交
    handleSubmit (e) {
      // 防止表单重复提交
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          // 判断产品分类是否选择到第三级
          if (!form.productTypeSn3) {
            this.$message.warning('产品分类未选到第三级，请修改后再提交！')
            return false
          }
          form.id = _this.$route.params.id ? _this.$route.params.id : undefined
          // 产品图片
          form.productPicList = []
          if (form.productMsg) {
            const arr = form.productMsg.split(',')
            arr.map(item => {
              form.productPicList.push({ imageUrl: item })
            })
          }
          delete form.productMsg
          delete form.productType
          delete form.updateDate
          _this.spinning = true
          productSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.handleBack()
                _this.spinning = false
              }, 1000)
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 返回
    handleBack () {
      this.$router.push({ name: 'productInfoList', query: { closeLastOldTab: true } })
    },
    // 产品图片上传
    changeImage (file) {
      this.form.productMsg = file
    },
    // 验证 条形码 规则
    validateQrCode (rule, value, callback) {
      const reg = /^[0-9a-zA-Z]+$/
      if (value && !reg.test(value)) {
        callback('条形码由大小写英文字母和数字组成')
      } else {
        callback()
      }
    },
    // 产品说明 文本编辑器
    editorDescriptionChange (html, text) {
      this.form.description = html
    },
    //  其他说明 文本编辑器
    editorOtherChange (html, text) {
      this.form.otherDesc = html
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.form.productTypeSn1 = val[0] ? val[0] : ''
      this.form.productTypeSn2 = val[1] ? val[1] : ''
      this.form.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  产品品牌  列表
    getProductBrand () {
      productBrandQuery({}).then(res => {
        if (res.status == 200) {
          this.productBrandList = res.data
        } else {
          this.productBrandList = []
        }
      })
    },
    //  产品分类  列表
    getProductType () {
      productTypeQueryAll({}).then(res => {
        if (res.status == 200) {
          if (res.data && res.data.length > 0) {
            //  递归处理disabled禁用
            this.recursionFun(res.data, false)
            this.productTypeList = res.data
          } else {
            this.productTypeList = []
          }
        } else {
          this.productTypeList = []
        }
      })
    },
    //  递归函数
    recursionFun (data, state) {
      if (data) {
        data.map((item, index) => {
          // enabledFlag为0表示禁用，父级禁用则子级也为禁用
          if ((item.enabledFlag && item.enabledFlag == 0) || state) {
            item.disabled = true
          } else {
            item.disabled = false
          }
          if (item.children && item.children.length == 0) {
            delete item.children
          } else {
            this.recursionFun(item.children, item.disabled)
          }
        })
      }
    },
    // 根据输入项进行筛选
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 初始化数据
    pageInit () {
      this.$refs.productMsg.setFileList('')
      this.$refs.editor.setHtml('')
      this.$refs.otherDesc.setHtml('')
      this.$refs.ruleForm.resetFields()
      this.form.packQtyUnit = undefined
      this.getProductBrand()
      this.getProductType()
      if (this.$route.params.id) { //  编辑页
        this.getDetail()
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .productInfoEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .productInfoEdit-cont{
      margin-bottom: 10px;
    }
    .upload{
      width: 100%!important;
    }
    //  文本编辑器  工具栏样式换行
    .productInfoEdit-editor{
      .w-e-toolbar{
        flex-wrap: wrap;
        z-index: 0;
      }
    }
    .affix{
      .ant-affix{
        z-index: 101;
      }
    }
  }
</style>
