<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-item label="入仓号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['receivingNo', validatorRules.receivingNo]" placeholder="请输入入仓号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="送货厂家" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deliveryFactory', validatorRules.deliveryFactory]" placeholder="请输入送货厂家"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="仓库名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag v-decorator="['warehouseName', validatorRules.warehouseName]" dict="iost_storage,name,id" />
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="客户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-popup
                v-decorator="['customerName', validatorRules.customerName]"
                :trigger-change="true"
                org-fields="name_chs,code"
                dest-fields="customerName,customerCode"
                code="custome_list"
                @callback="popupCallback"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="送货人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deliveryMan', validatorRules.deliveryMan]" placeholder="请输入送货人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="总件数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['casesTotal']" placeholder="请输入总件数" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="客户编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['customerCode', validatorRules.customerCode]" placeholder="请输入客户编码"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['telephone', validatorRules.telephone]" placeholder="请输入联系电话"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择入库日期" v-decorator="['date', validatorRules.date]" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" >
            <a-form-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['createBy']" disabled=true></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="入仓列表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="iostReceivinglistTable.loading"
          :columns="iostReceivinglistTable.columns"
          :dataSource="iostReceivinglistTable.dataSource"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @valueChange="onValueChange"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'  
  import JSearchSelectTag from '@/components/dict/JSearchSelectTag'

  export default {
    name: 'IostReceivingForm',
    mixins: [JEditableTableMixin],
    components: {
      JFormContainer,
      JDate,
      JSearchSelectTag,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          receivingNo: {
            rules: [
              { required: true, message: '请输入入仓号!'},
              { validator: (rule, value, callback) => validateDuplicateValue('iost_receiving', 'receiving_no', value, this.model.id, callback)},
            ]
          },
          deliveryFactory: {
            rules: [
              { required: true, message: '请输入送货厂家!'},
            ]
          },
          warehouseName: {
            rules: [
              { required: true, message: '请输入仓库名称!'},
            ]
          },
          customerName: {
            rules: [
              { required: true, message: '请输入客户姓名!'},
            ]
          },
          deliveryMan: {
            rules: [
              { required: true, message: '请输入送货人!'},
            ]
          },
          customerCode: {
            rules: [
              { required: true, message: '请输入客户编码!'},
            ]
          },
          telephone: {
            rules: [
              { required: true, message: '请输入联系电话!'},
            ]
          },
          date: {
            rules: [
              { required: true, message: '请输入入库日期!'},
            ]
          },
        },
        refKeys: ['iostReceivinglist', ],
        tableKeys:['iostReceivinglist', ],
        activeKey: 'iostReceivinglist',
        // 入仓列表
        iostReceivinglistTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '商品中文名称',
              key: 'nameChs',
              type: FormTypes.popup,
              popupCode:"price_list",
              destFields:"nameChs,description,nameEng,price",
              orgFields:"name_chs,description,name_eng,price",
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '商品描述',
              key: 'description',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '商品英文名称',
              key: 'nameEng',
              type: FormTypes.input,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '图片',
              key: 'picture',
              type: FormTypes.image,
              token:true,
              responseName:"message",
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '材质',
              key: 'material',
              type: FormTypes.input,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '组装标示',
              key: 'packageFlag',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '备注',
              key: 'note',
              type: FormTypes.input,
              width:"150px",
              placeholder: '小中大包装规格 商品用途及说明',
              defaultValue: '',
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.input,
              width:"60px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '件数',
              key: 'cases',
              type: FormTypes.inputNumber,
              width:"60px",
              placeholder: '请输入${title}',
              defaultValue: '',
              statistics:'sum',
            },
            {
              title: '单件装箱数',
              key: 'packages',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '总装箱数',
              key: 'packagesTotal',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
              statistics:'sum',
            },
            {
              title: '长(cm)',
              key: 'length',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '宽(cm)',
              key: 'width',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '高(cm)',
              key: 'height',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '单件体积',
              key: 'volume',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '总体积',
              key: 'volumeTotal',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
              statistics:'sum',
            },
            {
              title: '单件箱重(kg)',
              key: 'weight',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '总重量(kg)',
              key: 'weightTotal',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
              statistics:'sum',
            },
            {
              title: '单价',
              key: 'price',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '金额',
              key: 'money',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue: '',
              statistics:'sum',
            },

            {
              title: 'name_chs',
              key: 'name_chs',
              type:"hidden"
            },


            {
              title: 'name_eng',
              key: 'name_eng',
              type:"hidden"
            },

          ]
        },
        url: {
          add: "/basedata/iostReceiving/add",
          edit: "/basedata/iostReceiving/edit",
          queryById: "/basedata/iostReceiving/queryById",
          iostReceivinglist: {
            list: '/basedata/iostReceiving/queryIostReceivinglistByMainId'
          },
        },
      }
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：false流程表单 true普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      
    },
    computed: {
      casesTotal:function(){
          var price_total = 0;
          this.iostReceivinglistTable.dataSource.forEach(item=>{
              price_total+=item.cases;
            })
          return price_total;
      },
      warehouseName:function() {
        return deliveryFactory;
      },
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      addBefore(){
        this.form.resetFields()
        this.iostReceivinglistTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let fieldval = pick(this.model,'receivingNo','deliveryFactory','warehouseName','customerName','deliveryMan','casesTotal','customerCode','telephone','date', 'createBy')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.iostReceivinglist.list, params, this.iostReceivinglistTable)
        }
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          iostReceivinglistList: allValues.tablesValue[0].values,
        }
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          })
        }
      },
      //单元值改变一个字符就触发一次
      onValueChange(event) {
        const { type, row, column, value, target } = event

        //触发：总重量=件数*箱重；　
        if(column.key === 'cases' || column.key === 'weight')
        {    
          let result = row.weight * row.cases;
          result = result.toFixed(3)
          result = result.substring(0, result.length - 1)
          target.setValues([{rowKey: row.id, values: {weightTotal: result}}]);
          target.recalcOneStatisticsColumn('weightTotal');
        }

        if(column.key === 'packages')
        {
          if(row.packageFlag === '')
          {
            let result = row.packages * row.cases;
            result = result.toFixed(1)
            result = result.substring(0, result.length - 2)
            target.setValues([{rowKey: row.id, values: {packagesTotal: result}}]);
          }
          else
          {
            let rows = target.getValuesSync({validate:false}).values;
            let cases = 0;
            for(let i = 0; i < rows.length; i++)
            {
              let curRow = rows[i]
              if(curRow.packageFlag !== row.packageFlag) 
              {
                continue;
              }
              if(curRow.cases > cases)
              {
                cases = curRow.cases;
                break;
              }
            }
            let result = row.packages * cases;
            result = result.toFixed(1)
            result = result.substring(0, result.length - 2)
            target.setValues([{rowKey: row.id, values: {packagesTotal: result}}]);
          }
        }

        //触发：总装箱数　＝　装箱数　×　件数　
        if (column.key === 'cases') {

          if(row.packageFlag === '')
          {
            let result = row.packages * row.cases;
            result = result.toFixed(1)
            result = result.substring(0, result.length - 2)
            target.setValues([{rowKey: row.id, values: {packagesTotal: result}}]);
          }
          else
          {
            let rows = target.getValuesSync({validate:false}).values;
            for(let i = 0; i < rows.length; i++)
            {
              let curRow = rows[i]
              if(curRow.packageFlag !== row.packageFlag) 
              {
                continue;
              }

              let result = curRow.packages * row.cases;
              console.log(row.cases)
              result = result.toFixed(1)
              result = result.substring(0, result.length - 2)
              target.setValues([{rowKey: curRow.id, values: {packagesTotal: result}}]);
            }
          }
          target.recalcOneStatisticsColumn('packagesTotal');

        }
        
        //触发：长、宽、高　触发体积
        if (column.key === 'length' || column.key === 'width' || column.key === 'height') {
          let result = ((row.length  * row.width * row.height / 1000000) + 0.001);
          result = result.toFixed(4)
          result = result.substring(0, result.length - 1)

          target.setValues([{rowKey: row.id, values: {volume: parseFloat(result)}}]);
          target.recalcOneStatisticsColumn('volume');
          
          result = result * row.cases;
          result = result.toFixed(4)
          result = result.substring(0, result.length - 1)

          target.setValues([{rowKey: row.id, values: {volumeTotal: result}}]);
          target.recalcOneStatisticsColumn('volumeTotal');
          
          result = row.price * result;
          result = result.toFixed(3)
          result = result.substring(0, result.length - 1)

          target.setValues([{rowKey: row.id, values: {money: result}}]);
          target.recalcOneStatisticsColumn('money');
        }

        //触发：总体积=件数*单件体积
        if (column.key === 'volume' || column.key === 'cases') {
          let result = row.volume * row.cases;
          result = result.toFixed(4)
          result = result.substring(0, result.length - 1)

          target.setValues([{rowKey: row.id, values: {volumeTotal: result}}]);
          target.recalcOneStatisticsColumn('volumeTotal');
          
          result = row.price * result;
          result = result.toFixed(3)
          result = result.substring(0, result.length - 1)

          target.setValues([{rowKey: row.id, values: {money: result}}]);
          target.recalcOneStatisticsColumn('money');
        }

        //触发：金额=单价*总体积
        if (column.key === 'price' || column.key === 'volumeTotal') {
          let result = row.price * row.volumeTotal;
          result = result.toFixed(3)
          result = result.substring(0, result.length - 1)

          target.setValues([{rowKey: row.id, values: {money: result}}]);
          target.recalcOneStatisticsColumn('money');
        }

        if (column.key === "cases") {
          this.calcTotalCases();
        }
      },
      calcTotalCases() {
        let { error, values } = this.$refs.iostReceivinglist.getValuesSync({ validate: false});
        let total = 0;
        for (let v of values) {
          let cases = Number(v['cases']);
          if (!isNaN(cases)) {
            total += cases;
          }
        }

        const that = this;
        that.$nextTick(() => {
          that.form.setFieldsValue({'casesTotal':total});
        })
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(row){
       this.form.setFieldsValue(pick(row,'receivingNo','deliveryFactory','warehouseName','customerName','deliveryMan','casesTotal','customerCode','telephone','date', 'createBy'))
     },
     
    },
  }
</script>

<style scoped>
</style>