<template>
  <el-dialog
    class="creator"
    title="转移任务"
    width="70%"
    :visible="showCreator"
    @close="close"
  >
    <div class="creator__body">
      <el-form
        inline
        ref="form"
        label-position="top"
        :model="formData"
        :rules="rules"
        :disabled="mode === 'detail'"
      >
          <template v-for="member in creatorGroup">
            <el-collapse :key="member.prefix + 'main'" v-model="activeNames" class="member">
              <el-collapse-item :name="member.prefix + 1" :title="`转移${member.prefixText}信息`"
                                class="creator__info creator__info--base">
                <!--共用查询框-->
                <template v-for="item in publicQueries">
                  <el-form-item
                    :key="`${member.prefix}${item.valueField}`"
                    :label="`${member.prefixText}${item.label}`"
                    :prop="`${member.prefix}${item.valueField}`"
                  >
                    <PublicQuery
                      single
                      :disabled="item.disabled === member.prefix || item.disabled === true"
                      :title="`${member.prefixText}${item.label}`"
                      :baseUrl="baseUrl"
                      :cfgKey="member.prefix === 'fm' ? item.exceptionCfgKey || item.cfgKey : item.cfgKey"
                      :valueField.sync="formData[`${member.prefix}${item.valueField}`]"
                      :textField.sync="item.textField === undefined ? false : formData[`${member.prefix}${item.textField}`]"
                      :before="item.before && (() => item.before(member.prefix))"
                      @change="selected => {item.onChange && item.onChange(member.prefix, selected)}"
                    ></PublicQuery>
                  </el-form-item>
                </template>

                <!--输入框-->
                <template v-for="item in inputs">
                  <el-form-item
                    :key="`${member.prefix}${item.prop}`"
                    :label="`${member[item.preTextConfig || 'prefixText']}${item.label}`"
                    :prop="`${member.prefix}${item.prop}`"
                  >
                    <el-input
                      v-model="formData[`${member.prefix}${item.prop}`]"
                      :disabled="item.disabled === member.prefix || item.disabled === true"
                      @input.native="val => { item.onInput && item.onInput(member.prefix) }"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-collapse-item>
            </el-collapse>
          </template>
          <template v-for="member in creatorGroup">
            <el-collapse :key="member.prefix + 'lot'" v-model="activeNames" class="member">
              <el-collapse-item :title="`${member.prefixText}批次属性`" :name="member.prefix + 2"
                                class="creator__info creator__info--senior">
                <LotAttrs
                  disabled
                  :prefix="member.prefix === 'fm' ? member.prefix : member.prefix2"
                  :formData="formData"
                  :queryParams="member.lotAttrsParams"
                  @getLotConfig="lotConfig => getLotConfig(lotConfig, member.prefix)"
                ></LotAttrs>
              </el-collapse-item>
            </el-collapse>
          </template>

      </el-form>
    </div>
    <div class="creator__foot" v-if="mode !== 'detail'">
      <el-button v-auth="50300030206" :disabled="mode !== 'create' && detailData.status !== '00'" type="primary" @click="save">保存</el-button>
      <el-button v-auth="50300030207" :disabled="mode !== 'create' && detailData.status !== '00'" type="primary" @click="saveAndCreate">保存并新增</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 补位
function fix (target, length = 2) {
  const diffLen = length - String(target).length
  if (diffLen > 0) {
    const fixed0 = new Array(diffLen).fill('0')
    return `${fixed0.join('')}${String(target)}`
  }
  return String(target)
}
export default {
  props: ['showCreator', 'mainFormData', 'mode', 'detailData'],
  watch: {
    detailData: {
      immediate: true,
      handler (val) {
        if (this.mode !== 'create') {
          this.creatorGroup[0].lotAttrsParams = {
            ownerCode: val.fmOwner,
            skuCode: val.fmSku,
            lotNum: val.fmLot
          }
          this.creatorGroup[1].lotAttrsParams = {
            ownerCode: val.toOwner,
            skuCode: val.toSku,
            lotNum: val.toLot
          }
          // this.$set(this, 'formData', { ...this.formData, ...val })
          this.formData = { ...this.formData, ...val }
        } else {
          this.formData = {
            ownerCode: this.mainFormData.fmOwner,
            tfNo: this.mainFormData.tfNo,
            isSerial: 'N',
          }
        }
      }
    },
  },
  created () {
  },
  mounted () {
  },

  data () {
    return {
      activeNames: ['fm1', 'fm2', 'to1', 'to2'],
      // 组, 目前分 源和目标 两组
      creatorGroup: [
        { prefix: 'fm', prefixText: '源', prefixText2: '转出', lotAttrsParams: {} }, // 源的批次属性写死不传参
        { prefix: 'to', prefix2: '', prefixText: '目标', prefixText2: '转入', lotAttrsParams: {} }, // 目标的批次属性放入formData
      ],
      // 共用查询框
      publicQueries: [
        { label: '货主', valueField: 'Owner', textField: 'EbcuNameCn', cfgKey: 'invWmsCustomer', disabled: 'fm', onChange: this.ownerChange },
        {
          label: '商品',
          valueField: 'Sku',
          textField: 'SkuName',
          cfgKey: 'invWmsSku',
          before: this.skuBefore,
          onChange: this.skuChange,
          exceptionCfgKey: 'invWmsInvLotLoc1'
        },
        { label: '库位', valueField: 'Loc', textField: 'Loc', cfgKey: 'invWmsLoc', disabled: 'fm', rowData: {} },
        {
          label: '包装规格',
          valueField: 'CdpaFormat',
          textField: 'Pack',
          cfgKey: 'invWmsPackage',
          disabled: true,
          rowData: {}
        },
        { label: '包装单位', valueField: 'Uom', textField: 'CdprDesc', cfgKey: 'invWmsUom', before: this.cdprBefore },
      ],
      // 输入框
      inputs: [
        { label: '跟踪号', prop: 'Id', disabled: 'fm' },
        { label: '批次', prop: 'Lot', disabled: true },
        // { label: '包装规格', prop: 'CdpaFormat', disabled: true },
        // preTextConfigs允许使用非默认的prefix, 这里几个输入框使用的是 '转出/转入' 作为前缀
        { label: '数', prop: 'QtyUom', preTextConfig: 'prefixText2', onInput: this.qtyUomChange },
        { label: '数EA', prop: 'QtyEa', preTextConfig: 'prefixText2', disabled: true },
        { label: '重量', prop: 'Weight', preTextConfig: 'prefixText2' },
      ],
      // 时间框
      datePickers: [
        { label: '生产日期', prop: 'lotAtt01' },
        { label: '失效日期', prop: 'lotAtt02' },
        { label: '入库日期', prop: 'lotAtt03' },
      ],
      // 表单对象
      formData: {
        ownerCode: this.mainFormData.fmOwner,
        tfNo: this.mainFormData.tfNo,
        isSerial: 'N',
      },
      baseUrl: '/inv_web/invweb', // 多条件基础URL
      // 表单验证
      rules: {
        // formData写在 computed 就不能识别校验, 导致校验始终不通过
        fmQtyUom: [{ required: true, message: '必填', trigger: 'change' }], // 转出数
        toQtyUom: [{ required: true, message: '必填', trigger: 'change' }], // 转入数
        fmSku: [{ required: true, message: '必填', trigger: 'change' }], // 源商品
        toOwner: [{ required: true, message: '必填', trigger: 'change' }], // 目标货主
        toSku: [{ required: true, message: '必填', trigger: 'change' }], // 目标商品
        toLoc: [{ required: true, message: '必填', trigger: 'change' }], // 目标库位
        fmUom: [{ required: true, message: '必填', trigger: 'change' }], // 源包装单位
        toUom: [{ required: true, message: '必填', trigger: 'change' }], // 目标包装单位
      },
    }
  },
  methods: {
    // 重置, 若只使用form的resetField, 当表单为prop传过来详情时会重置为详情数据而不是置空
    reset () {
      this.$refs.form.resetFields() // 单纯是为了清空校验
      this.formData = {
        ownerCode: this.mainFormData.fmOwner,
        tfNo: this.mainFormData.tfNo,
        isSerial: 'N',
      }
    },
    // 保存
    save () {
      this.saveAndCreate('needClose')
    },
    // 关闭
    close () {
      this.$emit('close')
    },
    // 保存并新增
    saveAndCreate (needClose) {
      this.$refs.form.validate(valid => {
        if (valid) {
          const url = this.$API.inventory.tfOrder.saveTfDetail
          const param = { wmTfDetailEntityBean: JSON.stringify(this.formData) }
          this.$https.post(url, param)
            .then(data => {
              // this.$message.success('操作成功')
              this.$emit('createDone') // 通知父组件新增完毕, 刷新列表
              this.reset()
              needClose === 'needClose' && this.close() // 保存按钮需要关闭弹窗
            })
        }
      })
    },
    // 选择了商品, 设置其他信息
    skuChange (prefix, skuObj) {
      // 包装规格
      let index = 0
      if (prefix === 'fm') {
        // 使用 set 才能避免 当其他属性被动设置之后再去修改, 而 sync 的 update: 无法更新视图的 bug
        this.$set(this.formData, `${prefix}EbcuNameCn`, skuObj.ownerName)
        this.$set(this.formData, `${prefix}Loc`, skuObj.locCode)
        this.$set(this.formData, `${prefix}Id`, skuObj.traceId)
        // 包装规格
        this.$set(this.formData, `${prefix}Pack`, skuObj.packName)
        // 包装单位
        this.$set(this.formData, `${prefix}CdprDesc`, skuObj.cdprDesc)
        this.$set(this.formData, `${prefix}Uom`, skuObj.printUom)
        this.formData.toLoc = skuObj.locCode
        this.formData.toId = skuObj.traceId
        // 查询批次属性
        this.creatorGroup[0].lotAttrsParams = {
          ownerCode: this.formData.fmOwner,
          skuCode: this.formData.fmSku,
          lotNum: this.formData.fmLot
        }
        // 批次属性
        this.setLotAttrs(`${prefix}LotAtt`, skuObj, 'lotAtt')
      } else {
        index = 1
        this.$set(this.formData, `${prefix}EbcuNameCn`, skuObj.ebcuNameCn)
        // 包装规格
        this.$set(this.formData, `${prefix}Pack`, skuObj.packDesc)
        // 包装单位
        this.$set(this.formData, `${prefix}CdprDesc`, skuObj.rcvUomDesc)
        this.$set(this.formData, `${prefix}Uom`, skuObj.rcvUom)
        // 查询批次属性
        this.creatorGroup[1].lotAttrsParams = {
          ownerCode: this.formData.toOwner,
          skuCode: this.formData.toSku,
          lotNum: this.formData.toLot
        }
      }
      this.$set(this.formData, `${prefix}Owner`, skuObj.ownerCode)
      this.$set(this.formData, `${prefix}Lot`, skuObj.lotNum)
      // 包装规格
      this.$set(this.formData, `${prefix}CdpaFormat`, skuObj.packCode)
    },
    // 设置批次属性
    setLotAttrs (prefix, skuObj, objPrefix) {
      new Array(16).fill('').map((item, index) => {
        // 只有 new Array 不 fill 的话, 无法执行 map
        this.$set(this.formData, `${prefix}${fix(index + 1)}`, skuObj[`${objPrefix}${fix(index + 1)}`]) // 源批次属性
      })
    },
    // 批次属性组件获取到属性配置对象
    getLotConfig (lotConfig, prefix) {
      const lotObj = lotConfig.lotObj
      this[`${prefix}LotCode`] = lotObj.lotCode
      if (this.fmLotCode === this.toLotCode) {
        // 设置相同批次属性
        this.setLotAttrs('lotAtt', this.formData, 'fmLotAtt')
      } else {
        // 清除目标批次属性
        this.clearToLotAtt()
      }
    },
    // 清除目标批次属性信息 ##与业务强烈耦合的代码
    clearToLotAtt () {
      // 前四个写死的批次属性
      new Array(4).fill('').map((item, index) => {
        this.formData[`lotAtt${fix(index + 1)}`] = this.formData[`fmLotAtt${fix(index + 1)}`] || null
      })
      // 后面的真清除
      new Array(12).fill('').map((item, index) => {
        this.formData[`lotAtt${fix(index + 5)}`] = null
      })
    },
    // 选择了目标货主清除商品信息
    ownerChange () {
      this.$set(this.formData, 'toSku', undefined)
      this.$set(this.formData, 'toSkuName', undefined)
    },

    /**
     * 调用共用查询框前操作
     * */
    // 商品
    skuBefore (prefix) {
      let queryParams = {}
      switch (prefix) {
        case 'fm':
          queryParams = {
            ownerCodeParam: this.mainFormData.fmOwner,
            skuCodeParam: this.mainFormData.fmSku || '',
            isAllowTf: 'N'
          }
          break
        case 'to':
          queryParams = {
            ownerCodeParam: this.formData.toOwner,
          }
          break
      }
      return {
        queryParams
      }
    },
    // 包装单位
    cdprBefore (prefix) {
      return {
        queryParams: {
          packCode: this.formData[`${prefix}CdpaFormat`],
        }
      }
    },
    // 输入框变化
    // 调整数变化
    qtyUomChange (prefix) {
      this.formData[`${prefix}QtyEa`] = (+this.formData[`${prefix}QtyUom`]).toFixed(2)
    }
  },
}
</script>

<style lang="scss" scoped>
  .member {
    display: inline-block;
    width: 48%;
    margin: 1%;
    /deep/
    .el-form-item {
      width: 45%;
      .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 100%;
      }
    }
  }
  .el-collapse-item {
    margin-bottom: 20px;
  }
  .creator__foot {
    margin-top: 20px;
  }
</style>
