<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-item label="散货柜编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['bulkNo', validatorRules.bulkNo]" placeholder="请输入散货柜编号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <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="12" >
            <a-form-item label="货柜号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['containerNo', validatorRules.containerNo]" placeholder="请输入货柜号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="装柜日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择装柜日期" v-decorator="['loadingDate', validatorRules.loadingDate]" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <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="iostDeliveryRecordListTable.loading"
          :columns="iostDeliveryRecordListTable.columns"
          :dataSource="iostDeliveryRecordListTable.dataSource"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @valueChange="onValueChange"
          @beforePopupCallback="(values, others, id, row, column, index, rows, target)=>beforePopupCallback(values, others, id, row, column, index, rows, target)"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import { axios } from '@/utils/request'
  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: 'IostDeliveryRecordForm',
    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: {
          bulkNo: {
            rules: [
              { required: true, message: '请输入散货柜编号!'},
              { validator: (rule, value, callback) => validateDuplicateValue('iost_delivery_record', 'bulk_no', value, this.model.id, callback)},
            ]
          },
          warehouseName: {
            rules: [
              { required: true, message: '请输入仓库名称!'},
            ]
          },
          containerNo: {
            rules: [
              { required: true, message: '请输入货柜号!'},
            ]
          },
          loadingDate: {
            rules: [
              { required: true, message: '请输入装柜日期!'},
            ]
          },
        },
        refKeys: ['iostDeliveryRecordList', ],
        tableKeys:['iostDeliveryRecordList', ],
        activeKey: 'iostDeliveryRecordList',
        // 出库记录表
        iostDeliveryRecordListTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '入仓号',
              key: 'receivingNo',
              type: FormTypes.popup,
              popupCode:"iost_delivery_record",
              destFields:"receivingNo,customerName,nameChs,nameEng,description,picture,note,unit,cases,casesActual,packages,length,width,height,volume,weight,material,price,sourceId,sourceEntryId,volumeTotal,packageFlag,packagesTotal,weightTotal,money",
              orgFields:"receiving_no,customer_name,name_chs,name_eng,description,picture,note,unit,cases,cases,packages,length,width,height,volume,weight,material,price,source_id,source_entry_id,volume_total,package_flag,packages_total,weight_total,money",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              multi: true,
            },
            {
              title: '客户中文名称',
              key: 'customerName',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '商品描述',
              key: 'description',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '商品中文名称',
              key: 'nameChs',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '商品英文名称',
              key: 'nameEng',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '图片',
              key: 'picture',
              type: FormTypes.image,
              token:true,
              responseName:"message",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '组装标示',
              key: 'packageFlag',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '备注',
              key: 'note',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '件数',
              key: 'cases',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '单件装箱数',
              key: 'packages',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '总装箱数',
              key: 'packagesTotal',
              type: FormTypes.inputNumber,
              width:"200px",
              defaultValue: '',
              statistics:'sum',
              disabled:true,
            },
            {
              title: '实际件数',
              key: 'casesActual',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              statistics:'sum',
            },
            {
              title: '长(cm)',
              key: 'length',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '宽(cm)',
              key: 'width',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '高(cm)',
              key: 'height',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '单件体积',
              key: 'volume',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '总体积',
              key: 'volumeTotal',
              type: FormTypes.inputNumber,
              width:"200px",
              defaultValue: '',
              statistics:'sum',
              disabled:true,
            },
            {
              title: '箱重(kg)',
              key: 'weight',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '总重量(kg)',
              key: 'weightTotal',
              type: FormTypes.inputNumber,
              width:"200px",
              defaultValue: '',
              statistics:'sum',
              disabled:true,
            },
            {
              title: '材质',
              key: 'material',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled:true,
            },
            {
              title: '单价',
              key: 'price',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '金额',
              key: 'money',
              type: FormTypes.inputNumber,
              width:"200px",
              defaultValue: '',
              statistics:'sum',
              disabled:true,
            },
            {
              title: 'receiving_no',
              key: 'receiving_no',
              type:"hidden"
            },

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

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

            {
              title: 'name_eng',
              key: 'name_eng',
              type:"hidden"
            },
            {
              title: 'packages_total',
              key: 'packages_total',
              type:"hidden"
            },
            {
              title: 'volume_total',
              key: 'volume_total',
              type:"hidden"
            },
            {
              title: 'weight_total',
              key: 'weight_total',
              type:"hidden"
            },
            {
              title: 'sourceId',
              key: 'sourceId',
              type:"hidden"
            },
            {
              title: 'sourceEntryId',
              key: 'sourceEntryId',
              type:"hidden"
            },
          ]
        },
        url: {
          add: "/basedata/iostDeliveryRecord/add",
          edit: "/basedata/iostDeliveryRecord/edit",
          queryById: "/basedata/iostDeliveryRecord/queryById",
          iostDeliveryRecordList: {
            list: '/basedata/iostDeliveryRecord/queryIostDeliveryRecordListByMainId'
          },
        }
      }
    },
    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: {
      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.iostDeliveryRecordListTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let fieldval = pick(this.model,'bulkNo','warehouseName','containerNo','loadingDate', 'createBy')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.iostDeliveryRecordList.list, params, this.iostDeliveryRecordListTable)
        }
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          iostDeliveryRecordListList: allValues.tablesValue[0].values,
        }
      },
      //单元值改变一个字符就触发一次
      onValueChange(event) {
        const { type, row, column, value, target } = event

        if(column.key === 'price')
        {
          
          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 === 'casesActual')
        {
          if(row.packages === '') return;
          
          if(row.packageFlag === '')
          {
            let result = row.packages * row.casesActual;
            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;
              }

              if(curRow.packages === '') continue;

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

          let result = row.packages * row.casesActual;
          target.recalcOneStatisticsColumn('packagesTotal');

          result = row.weight * row.casesActual;
          result = result.toFixed(3)
          result = result.substring(0, result.length - 1)

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


          if(row.volume > 0)
          {
            result = row.volume * row.casesActual;
            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');
        }
      },
      //渲染流程表单数据
      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);
            }
          })
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(row){
       this.form.setFieldsValue(pick(row,'bulkNo','warehouseName','containerNo','loadingDate', 'createBy'))
     },
      beforePopupCallback:async function(values, others, id, row, column, index, rows, target){
        let packageFlagPara = [];
        for(let i = 0; i < values.length; i++)
        {
          let sourceId = others["sourceId"][i]
          let sourceEntryId = others["sourceEntryId"][i]
          let packageFlag = others["packageFlag"][i]
          let casesActual = others["casesActual"][i]
          packageFlagPara.push({id:sourceId, entryId:sourceEntryId, packageFlag, casesActual});
        }

        values.length = 0
        others.length = 0

        if(packageFlagPara.length > 0)
        {
          let url = `${window._CONFIG['domianURL']}/basedata/iostReceiving/getPackageMaterials`;
          let res = await axios.post(url,{packageMaterialsVOs:packageFlagPara});

          if(!res.success) return;
          let datas = res.result;
          if(datas.length === 0) return;
          target.removeRows([row.id])

          datas.forEach(data => {
            target.push(data);
          });

        }
      }
    }
  }
</script>

<style scoped>
</style>