<template>
  <a-spin :spinning="confirmLoading" style="height: 650px;">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail" style="background-color: #e7f6ef;padding-top: 10px">
        <a-row>
          <a-col :span="8" v-show="false">
            <a-form-item label="ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['id']" placeholder="" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-show="false">
            <a-form-item label="ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['deliveryType']" placeholder="" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-show="false">
            <a-form-item label="ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['id']" placeholder="" style="width: 100%" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-show="false">
            <a-form-item label="isOffice" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['isOffice']" placeholder="" style="width: 100%" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="流程发起人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep v-decorator="['createBy']" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="流程发起公司" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-company v-decorator="['company']" multi disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="流程发起部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-depart v-decorator="['departId']" multi disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="流程发起时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择流程发起时间" v-decorator="['createTime']" :trigger-change="true" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="this.deliveryType==1 || this.isOffice==1">
            <a-form-item label="物资类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" @change="isMaterialType"
                                 v-decorator="['materialType',validatorRules.materialType]" :trigger-change="true"
                                 dictCode="stronger_material_type" placeholder="请选择物资类型"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="this.deliveryType==2 && this.isOffice==2">
            <a-form-item label="物资类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" @change="isMaterialType"
                                 v-decorator="['materialType',validatorRules.materialType]" :trigger-change="true"
                                 dictCode="material_type" placeholder="请选择物资类型"/>
            </a-form-item>
          </a-col>
          <!--<a-col :span="8">
            <a-form-item label="出库时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择出库时间" v-decorator="['deliveryTime',validatorRules.deliveryTime]"
                      :trigger-change="true" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </a-form-item>
          </a-col>-->
          <a-col :span="8">
            <a-form-item label="文件" :labelCol="labelCol3" :wrapperCol="wrapperCol3" style="z-index: 10000">
              <j-upload v-decorator="['fileId']" :trigger-change="true"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs"
            style="background-color: #eaf3ea;margin-top: 20px;padding: 0px 10px">
      <a-tab-pane tab="物资出库流程出库清单" :key="refKeys[0]" :forceRender="true">
        <c-editable-table
          ref="processMaterialsDeliveryList"
          :loading="processMaterialsDeliveryListTable.loading"
          :columns="processMaterialsDeliveryListTable.columns"
          :dataSource="processMaterialsDeliveryListTable.dataSource"
          :maxHeight="300"
          :verify="this.deliveryType"
          :isabled="isabled"
          :verify-type="this.accountingAttributesVal"
          @valueChange="onSelect"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @descriptionFetch="addid"
        >
          <template v-slot:repertory="props">
            <a-tooltip placement="top">
              <template v-slot:title="props">
                <p>库存：{{ wateNumber}} </p>
              </template>
              <a-button @mouseenter="chaKan(props)" v-has="'stockRemoval:stock'">查看</a-button>
            </a-tooltip>
            <!--          <a-button @click="chaKan(props)">查看</a-button>-->
          </template>
          <!--          <template v-slot:qing="props">-->
          <!--            <a-input v-decorator="['pleaseSendNumber']" placeholder="请输入" style="width: 100%" @change="shuru"  type="number"/>-->
          <!--          </template>-->

        </c-editable-table>
      </a-tab-pane>
    </a-tabs>
    <!--    <j-form-container >
          <a-form :form="form">
            <a-row>
              <a-col :span="24"  >
                <a-form-item label="流程说明" >
                  <j-editor v-decorator="[ 'opinion', {} ]" triggerChange></j-editor>
                  &lt;!&ndash;<a-input type="textarea" v-decorator="[ 'opinion' ]" :rows="4" />&ndash;&gt;
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </j-form-container>-->
    <div class="div_process">
      <a-form-item v-if="!disabled" :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button type="primary" :disabled="disabled||btndisabled" @click="handleSubmit">保存</a-button>
        <a-button style="margin-left: 8px" type="primary" :disabled="disabled||btndisabled" @click="applySubmit">提交申请
        </a-button>
        <a-button style="margin-left: 8px" :disabled="disabled" @click="close">取消</a-button>
      </a-form-item>
      <a-form-item v-if="task" :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button type="primary" @click="passTask">通过</a-button>
        <a-button style="margin-left: 8px" @click="backTask">驳回</a-button>
      </a-form-item>
    </div>
  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import { getAction, getCurrentTime, httpAction, getStringArry, getRecord } from '@/api/manage'
  import { FormTypes, getRefPromise, validateFormAndTables } 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 JUpload from '@/components/jeecg/JUpload'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JSelectCompany from '../../../components/jeecgbiz/JSelectCompany'

  export default {
    name: 'ProcessMaterialsDeliveryForm',
    mixins: [JEditableTableMixin],
    components: {
      JFormContainer,
      JDate,
      JUpload,
      JSelectDepart,
      JSelectUserByDep,
      JDictSelectTag,
      JSelectCompany
    },
    data() {
      return {
        libraryAssociationIdInvisible: '',
        rolePlay: false,
        // actualNumbers: true, //实发数
        jiy: [],
        // heid: true,
        addId: '',
        wateNumber: 0,
        bigIdMerchandiseNewsList: [],
        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 }
        },
        labelCol3: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol3: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        refKeys: ['processMaterialsDeliveryList'],
        tableKeys: ['processMaterialsDeliveryList'],
        activeKey: 'processMaterialsDeliveryList',
        // 物资出库流程出库清单
        processMaterialsDeliveryListTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料组',
              key: 'materialGroup',
              // type: FormTypes.slot, //  <-------------改为 slot 格式
              // slotName: 'actions',   //  <-------------slot 的名称，对应 v-slot 冒号后面和等号前面的内容
              type: FormTypes.sel_search,
              dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              disabled: true,
              options: []
              // props:{title: 'show title'}
              // scopedSlots: { customRender: 'edit' },//引入的插槽
              // customRender:function (t,r,index) {
              //     console.log(t,r);
              //
              // }
            },
            {
              title: '物资编号',
              key: 'equipment',
              type: FormTypes.sel_search,
              dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              // defaultValue:'',
              options: [],
              disabled: this.disabled
            },
            {
              title: 'WBS',
              key: 'wbs',
              type: FormTypes.input,
              dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: this.disabled
            },
            {
              title: '物料名称及规格型号',
              key: 'materialName',
              type: FormTypes.input,
              dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: this.disabled
            },
            // {
            //   title: '规格',
            //   key: 'specification',
            //   type: FormTypes.input,
            //   dictCode: '',
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // }, {
            //   title: '型号',
            //   key: 'type',
            //   type: FormTypes.input,
            //   dictCode: '',
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            {
              title: '单位',
              key: 'materialUnit',
              type: FormTypes.input,
              dictCode: '',
              width: '130px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: this.disabled
            },
            // {
            //   title: '批次',
            //   key: 'batch',
            //   type: FormTypes.input,
            //   width:"200px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            // },
            {
              title: '请发数',
              key: 'pleaseSendNumber',
              type: FormTypes.inputNumber,
              width: '130px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: this.disabled
              // slotName: 'qing'
            },
            {
              title: '实发数',
              key: 'actualSendNumber',
              type: FormTypes.inputNumber,
              width: '130px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: this.actualNumber
            },
            {
              title: '库存',
              key: 'repertory',
              type: FormTypes.slot,
              width: '80px',
              // placeholder: '请输入${title}',
              // defaultValue: '',
              slotName: 'repertory',
              disabled: this.disabled
              // scopedSlots: {customRender: 'fileSlot'}
            },
            {
              title: '供货商',
              key: 'supplierId',
              type: FormTypes.input,
              dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: this.disabled
            },
            {
              title: '单价（元）',
              key: 'materialPrice',
              type: FormTypes.inputNumber,
              width: '130px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: true
            },
            {
              title: '金额（元）',
              key: 'materialAmount',
              type: FormTypes.inputNumber,
              width: '130px',
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: true
            },
            {
              title: '生产日期',
              key: 'productionTime',
              type: FormTypes.date,
              width: '200px',
              placeholder: '请输入${title}',
              disabled: this.disabled,
              defaultValue: ''
            },
            {
              title: '保质期',
              key: 'expirationDate',
              type: FormTypes.inputNumber,
              width: '130px',
              placeholder: '请输入${title}',
              disabled: this.disabled,
              defaultValue: ''
            },
            {
              title: '用途',
              key: 'purpose',
              type: FormTypes.input,
              width: '200px',
              placeholder: '请输入${title}',
              disabled: this.disabled,
              defaultValue: ''
            }
            // {
            //   title: '',
            //   key: 'MaterialsDeliveryId',
            //   type: FormTypes.input,
            //   width:"0px",
            //   defaultValue:'',
            //   disabled:true,
            //
            // },
          ]
        },
        url: {
          queryByIdDescription: '/description/processDescription/queryById',
          queryByIdMerchandiseNews: '/merchandisenews/processMerchandiseNews/queryById',
          getForm: '/actBusiness/getForm',
          add: '/hy/processMaterialsDelivery/add',
          edit: '/hy/processMaterialsDelivery/edit',
          addDeliveryApply: '/hy/processMaterialsDelivery/addDeliveryApply',
          editDeliveryApply: '/hy/processMaterialsDelivery/editDeliveryApply',
          queryById: '/hy/processMaterialsDelivery/queryById',
          descriptionRake: '/suppliesstronger/processSuppliesStronger/descriptionName', //查询总库物料组
          wasteMaterialsUrl: '/wastematerials/processWasteMaterials/wasteMaterialsName', //查询账外物料组
          merchandiseNewsList: '/suppliesstronger/processSuppliesStronger/merchandiseNews',
          wasteMaterialsList: '/wastematerials/processWasteMaterials/merchandiseNewsName', //账外
          puwwlist: '/unitwaste/processUnitWasteWarehouseCode/queryById',
          unitWasteWarehouseList: '/unitwaste/processUnitWasteWarehouseCode/queryById', //查询目标库
          getFirstNode: '/actProcessIns/getFirstNode',
          queryPageDepare: '/hy/processMaterialsDelivery/queryPageDepare',//查询部门
          processMaterialsDeliveryList: {
            list: '/hy/processMaterialsDelivery/queryProcessMaterialsDeliveryListByMainId'
          }
        },
        btndisabled: false,
        isabled: true,
        describes: '',
        assignees: '',
        deliveryType: '',
        isOffice: '',
        validatorRules: {
          // 'blur'是鼠标失去焦点的时候会触发验证
          materialType: { rules: [{ required: true, message: '请选择物资类型!' }] },
          deliveryTime: { rules: [{ required: true, message: '请选择出库时间!' }] },
          processPlan: { rules: [{ required: true, message: '请选择流程计划!' }] }
        },
        materialGroupId: undefined,
        accountingAttributesVal: '',
        hiegs: true
      }
    },
    props: {
      /*流程数据*/
      processData: {
        type: Object,
        default: () => {
          return {}
        },
        required: false
      },
      /*是否新增*/
      isNew: { type: Boolean, default: false, required: false },
      /*是否处理流程*/
      task: { type: Boolean, default: false, required: false },
      //流程表单data
      formData: {
        type: Object,
        default: () => {
        },
        required: false
      },
      //表单模式：false流程表单 true普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      actualNumber: {
        type: Boolean,
        // default: false, //默认值
        required: true //必传值
      },
      //表单禁用
      hieg: {
        type: Boolean,
        default: false,
        required: false
      },
      dianshang: {
        type: Number,
        default: 0,
        required: false
      }
    },
    computed: {
      formDisabled() {
        // console.log("执行了")
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        // console.log("============================",this.hiegs=this.hieg);
        console.log('2222222222222222', this.actualNumber)
        // if(this.disabled){
        //   this.isabled = false;
        // }
        this.hiegs = this.hieg
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    watch: {
      dianshang: {
        immediate: true,
        handler: function(val) {
          if (val == 1) {

          }
          this.deliveryType = val
        }
      }
    },
    created() {
      //如果是流程中表单，则需要加载流程表单data
      //this.showFlowData()

      let company = sessionStorage.getItem('PARENT_ID')
      let puwwcid = sessionStorage.getItem('PUWWC_Id')
      let userInfo = sessionStorage.getItem('USER_INFORMATION')
      // userInfo.company=company;
      if (!this.isNew) {
        this.init()
      } else {
        this.popupCallback(company, userInfo, puwwcid)
      }
    },
    methods: {

      async chaKan(log) {
        let pas = await log.target.getValuesPromise(log.rowIds)
        // console.log("执行了",pas);
        if (!!pas[log.index].repertory) {
          this.wateNumber = pas[log.index].repertory
        } else {
          this.wateNumber = 0
        }
      },

      //新增输入
      async addid(val) {
        // this.addId = val.row.id
        // console.log(val);
        this.materialGroupId = undefined
        // this.fetchData(this.accountingAttributesVal);
        // this.fetchMerchandiseNews();
        if (this.deliveryType !== 1) {
          // console.log("执行账外")
          //账外
          await this.fetchMerchandiseNewsZW()
        }else {
          // console.log("执行总库")
          //总库
          await this.fetchMerchandiseNews()
        }
        if (this.isOffice == 1) {
          //总库
          await this.fetchMerchandiseNews()
        }
      },
      //核算属性切换
      async isMaterialType(val) {
        if (val !== undefined) {
          this.accountingAttributesVal = val
          this.hiegs = false
          this.isabled = false
          if (this.deliveryType !== 1) {
            // console.log("执行账外")
            //账外
            await this.fetchMerchandiseNewsZW()
          } else {
            // console.log("执行总库")
            //总库
            await this.fetchMerchandiseNews()
          }

        }
      },
      async onSelect(record) {
        // console.log(record)
        let isMA = true
        // if (!!record.row.materialGroup  && !!record.row.materialGroup ) {
        //   // console.log("执行materialGroup111")
        //   if (!!record.row.id && record.row.materialGroup !== this.materialGroupId && record.column.key !== "allotNumber") {
        //     // console.log("执行materialGroup222")
        //     if (this.rolePlay) {
        //       // console.log("执行账外")
        //       //账外
        //       await this.fetchMerchandiseNewsZW(record.row.materialGroup, 1)
        //     } else {
        //       // console.log("执行总库")
        //       //总库
        //       await this.fetchMerchandiseNews(record.row.materialGroup, 1)
        //     }
        //
        //       let valu = [
        //         {
        //           rowKey: record.row.id,
        //           values: {
        //             'equipment': '',
        //             'materialGroup': record.row.materialGroup,
        //             'materialName': '',
        //             'materialUnit': '',
        //             'supplierId': '',
        //             'materialPrice': '',
        //             'actualSendNumber': '',
        //             'materialAmount': '',
        //             'pleaseSendNumber': ''
        //           }
        //         }
        //       ]
        //       // console.log(valu)
        //       this.$refs.processMaterialsDeliveryList.setValues(valu)
        //       this.materialGroupId = record.row.materialGroup
        //       isMA = false
        //     }
        // }
        let eAll = 0
        // if (!!record.row.materialGroup  && !! record.row.equipment && isMA) {
        let b = false
        for (const res of this.bigIdMerchandiseNewsList) {
          if (res.merchandiseNewsId === record.row.equipment) {
            b = true
          }
        }
        if (record.column.key == 'equipment' && isMA && record.row.materialGroup !== this.materialGroupId) {
          // console.log("执行materialNumber")
          if (!b) {
            if (this.accountingAttributesVal === '1') {
              //账外
              await this.fetchMerchandiseNewsZW(record.row.equipment)
            } else {
              //总库
              await this.fetchMerchandiseNews(record.row.equipment)
            }
          }

          await this.$refs.processMaterialsDeliveryList.getValues((a, b, c) => {
            // console.log("bbbbbbbbbbbbbb",b)
            b.forEach(item => {
              if (item.equipment === record.row.equipment && !!item.materialGroup && !record.row.materialGroup) {
                let values = [
                  {
                    rowKey: record.row.id,
                    values: {
                      'materialGroup': '',
                      'materialNumber': '',
                      'materialSeries': '',
                      'materialName': '',
                      'materialUnit': '',
                      'supplierId': '',
                      'materialAmount': '',
                      'materialType': ''
                    }
                  }
                ]
                // console.log("sadf1111")
                this.$refs.processMaterialsDeliveryList.setValues(values)
                return

              }
            })

          })

          let materialName = {}
          this.bigIdMerchandiseNewsList.forEach(item => {
            if (item.merchandiseNewsId === record.row.equipment) {
              materialName = {
                name: item.merchandiseName,
                unit: item.materialsUnit,
                materialGroup: item.materialClassify,
                supplierName: item.supplierId,
                price: item.materialPrice,
                descriptionId: item.descriptionId,
                residueNumber: item.residueNumber === undefined ? 0 : item.residueNumber
              }
            }
          })

          // console.log("materialName",materialName);
          if (record.row.id !== undefined && Object.keys(materialName).length > 0) {
            // console.log("materialName",materialName);

            this.processMaterialsDeliveryListTable.columns[0].options.push({
              title: materialName.materialGroup,
              value: materialName.descriptionId
            })

            let values = [
              {
                rowKey: record.row.id,
                values: {
                  'equipment': record.row.equipment,
                  'materialGroup': materialName.descriptionId,
                  'materialName': materialName.name,
                  'materialUnit': materialName.unit,
                  'supplierId': materialName.supplierName,
                  'materialPrice': materialName.price,
                  // 'actualSendNumber': materialName.residueNumber,
                  'repertory': materialName.residueNumber
                  // 'materialAmount': materialName.price * materialName.residueNumber
                }
              }
            ]
            this.$refs.processMaterialsDeliveryList.setValues(values)
          } else {
            // console.log("this.data.materialType",this.data.materialType)
            if (parseInt(this.deliveryType) !== 1) {
              //账外
              await this.getEquipmentInvisible(record.row.equipment)
              eAll = 2
            } else {
              //总库
              await this.getEquipmentAll(record.row.equipment)
              eAll = 1

            }

          }
          this.materialGroupId = record.row.equipment
        }

        // 根据请发数量计算
        if (record.column.key == 'pleaseSendNumber' && isMA || record.column.key == 'actualSendNumber' && isMA) {
          // console.log("执行了333333333333")
          let res = record.row
          let materialName = {}
          this.bigIdMerchandiseNewsList.forEach(item => {
            if (item.merchandiseNewsId === record.row.equipment) {
              materialName = {
                residueNumber: item.residueNumber === undefined ? 0 : item.residueNumber
              }
            }
          })
          // if (eAll === 0) {
          //   if (parseInt(res.pleaseSendNumber) > parseInt(materialName.residueNumber)) {
          //     this.$message.warn('输入请发数不能大于库存数')
          //     res.pleaseSendNumber = materialName.residueNumber
          //     res.actualSendNumber = materialName.residueNumber
          //   } else {
          //     res.actualSendNumber = res.pleaseSendNumber
          //   }
          // } else if (eAll === 1) {
          //   // console.log("000000000000000",this.equipmentAll);
          //   if (parseInt(res.pleaseSendNumber) > parseInt(this.equipmentAll[0].materialQuantity)) {
          //     this.$message.warn('输入请发数不能大于库存数')
          //     res.pleaseSendNumber = this.equipmentAll[0].materialQuantity
          //     res.actualSendNumber = this.equipmentAll[0].materialQuantity
          //   } else {
          //     res.actualSendNumber = res.pleaseSendNumber
          //   }
          // } else if (eAll === 2) {
          //   // console.log("00000000000022222",this.equipmentAll);
          //   if (parseInt(res.pleaseSendNumber) > parseInt(this.equipmentAll[0].residueNumber)) {
          //     this.$message.warn('输入请发数不能大于库存数')
          //     res.pleaseSendNumber = this.equipmentAll[0].residueNumber
          //     res.actualSendNumber = this.equipmentAll[0].residueNumber
          //   } else {
          //     res.actualSendNumber = res.pleaseSendNumber
          //   }
          // }
          if (res.id !== undefined) {
            let value = [
              {
                rowKey: res.id,
                values: {
                  // 'equipment': res.equipment,
                  // 'materialGroup': res.materialGroup,
                  // 'materialName': res.materialName,
                  // 'materialUnit': res.materialUnit,
                  // 'supplier': res.supplier,
                  // 'materialPrice': res.materialPrice,
                  'actualSendNumber': res.actualSendNumber,
                  'pleaseSendNumber': res.pleaseSendNumber,
                  'materialAmount': res.materialPrice * res.actualSendNumber
                }
              }
            ]
            this.$nextTick(() => {
              this.$refs.processMaterialsDeliveryList.setValues(value)
            })
          }

        }

      },
      //查询总出库库存信息
      getEquipmentAll(val) {
        return new Promise((resolve, reject) => {
          let ue = sessionStorage.getItem('USER_INFORMATION')
          let res = JSON.parse(ue)

          let pam = {
            merchandiseNewsId: val,
            departId: res.departIds
          }
          getAction(this.url.merchandiseNewsList, pam).then(res => {
            // console.log("dsfgsdfgb",res);
            if (res.success) {
              this.equipmentAll = res.result
            }
            resolve(this.equipmentAll)
          })

        })
      },
      //查询账外出库库存信息
      getEquipmentInvisible(val) {
        return new Promise((resolve, reject) => {
          let ue = sessionStorage.getItem('USER_INFORMATION')
          let res = JSON.parse(ue)

          let pam = {
            merchandiseNewsId: val,
            departId: res.departIds
          }
          getAction(this.url.wasteMaterialsList, pam).then(res => {
            // console.log("pppppppppppp",res);
            if (res.success) {
              this.equipmentAll = res.result
            }
            resolve(this.equipmentAll)
          })

        })
      },

      fetchMerchandiseNews(value) { //查询物料清单信息
        //查询大品类数据
        return new Promise((resolve, reject) => {
          //你的逻辑代码
          let par = {
            delFlag: 0,
            accountingAttributes: this.accountingAttributesVal,
            merchandiseNewsId: value
          }
          this.bigIdMerchandiseNewsList = []
          let qc = []
          let numberList = []
          if (this.processMaterialsDeliveryListTable.columns[1].options.length > 0) {
            this.processMaterialsDeliveryListTable.columns[1].options = []
          }
          this.$refs.processMaterialsDeliveryList.getValues((a, b, c) => {
            // console.log(a, b, c)
            b.forEach(item => {
              if (item.equipment !== '' && item.equipment !== undefined && item.equipment !== null) {
                numberList.push(item.equipment)
              }
            })
          })
          getAction(this.url.merchandiseNewsList, par).then((res) => {
            if (res.success) {
              // console.log(res.result)
              let newList = res.result
              // console.log('12312312:' + numberList.length)
              if (numberList.length > 0) {
                newList.forEach(item => {
                  qc.push({
                    title: item.materialsNumber,
                    value: item.merchandiseNewsId,
                    disabled: false
                  })
                })
                numberList.forEach(num => {
                  qc.forEach(i => {
                    // console.log(num)
                    // console.log(i.value)
                    if (num === i.value) {
                      // console.log(num, i.value)
                      i.disabled = true
                    }
                  })
                })
                this.processMaterialsDeliveryListTable.columns[1].options = qc
              } else {
                newList.forEach(item => {
                  this.processMaterialsDeliveryListTable.columns[1].options.push({
                    title: item.materialsNumber,
                    value: item.merchandiseNewsId,
                    disabled: false
                  })
                })
              }
              // console.log(this.processUdgetPlanMaterialTable.columns[1].options);
              resolve(this.bigIdMerchandiseNewsList = res.result)
              // return
            }
          })

        })

      },
      fetchMerchandiseNewsZW(value, did) { //查询账外物料清单信息
        //查询大品类数据
        return new Promise(async (resolve, reject) => {
          //你的逻辑代码
          let par = {
            delFlag: 0,
            merchandiseNewsId: value,
            accountingAttributes: this.accountingAttributesVal
          }
          let ue = sessionStorage.getItem('USER_INFORMATION')
          let res = JSON.parse(ue)
          let de = {
            id: res.departIds
          }
          let data = await getAction(this.url.queryPageDepare, de)
          // console.log(data.result);
          if (data.result.orgType === '3') {
            //  查询大品类数据 账外库
            par.departId = data.result.parentId
          } else {
            //  查询大品类数据 账外库
            par.departId = res.departIds
          }

          if (!res.departIds) {
            this.$message.warn('当前账号没有物资库！！！')
          }
          this.bigIdMerchandiseNewsList = []
          let qc = []
          let numberList = []
          if (this.processMaterialsDeliveryListTable.columns[1].options.length > 0) {
            this.processMaterialsDeliveryListTable.columns[1].options = []
          }
          this.$refs.processMaterialsDeliveryList.getValues((a, b, c) => {
            // console.log(a, b, c)
            b.forEach(item => {
              if (item.equipment !== '' && item.equipment !== undefined && item.equipment !== null) {
                numberList.push(item.equipment)
              }
            })
          })
          getAction(this.url.wasteMaterialsList, par).then((res) => {
            if (res.success) {
              // console.log(res.result);
              let newList = res.result
              // console.log("12312312:"+numberList.length);
              if (numberList.length > 0) {
                newList.forEach(item => {
                  qc.push({
                    title: item.materialsNumber,
                    value: item.merchandiseNewsId,
                    disabled: false
                  })
                })
                numberList.forEach(num => {
                  qc.forEach(i => {
                    if (num === i.value) {
                      // console.log(num,i.value);
                      i.disabled = true
                    }
                  })
                })
                this.processMaterialsDeliveryListTable.columns[1].options = qc
              } else {
                newList.forEach(item => {
                  this.processMaterialsDeliveryListTable.columns[1].options.push({
                    title: item.materialsNumber,
                    value: item.merchandiseNewsId,
                    disabled: false
                  })
                })
              }
              // console.log(this.processUdgetPlanMaterialTable.columns[1].options);
              resolve(this.bigIdMerchandiseNewsList = res.result)
              // return
            }
          })

        })

      },
      //table 值改变触发
      // async onSelect(record) {
      //   // console.log(record)
      //   if(record.row.materialGroup !== '' && record.row.materialGroup !== undefined && record.row.equipment === ''){
      //     // console.log("执行materialGroup")
      //     this.fetchMerchandiseNews(record.row.materialGroup,1);
      //   }
      //   if(record.row.materialGroup !== '' && record.row.materialGroup !== undefined && record.row.equipment !== '' && record.row.actualSendNumber === '' ){
      //     // console.log("执行materialNumber")
      //     let materialName = {}
      //     this.bigIdMerchandiseNewsList.forEach(item => {
      //       if (item.merchandiseNewsId === record.row.equipment) {
      //         materialName = {
      //           name: item.merchandiseName,
      //           unit: item.materialsUnit,
      //           supplierName: item.supplierName,
      //           price: item.price,
      //           batch: item.batch,
      //           MaterialsDeliveryId : item.id
      //           // residueNumber : item.residueNumber === undefined ? 0 : item.residueNumber,
      //         }
      //       }
      //     })
      //     let values = [
      //       {
      //         rowKey: record.row.id,
      //         values: {
      //           'equipment': record.row.equipment,
      //           'materialGroup': record.row.materialGroup,
      //           'materialName': materialName.name,
      //           'materialUnit': materialName.unit,
      //           'supplier': materialName.supplierName,
      //           'materialPrice': materialName.price,
      //           'batch' : materialName.batch,
      //           'MaterialsDeliveryId': materialName.MaterialsDeliveryId
      //           // 'actualSendNumber': materialName.residueNumber,
      //           // 'materialAmount': materialName.price * materialName.residueNumber,
      //         },
      //       },
      //     ]
      //     this.$refs.processMaterialsDeliveryList.setValues(values);
      //   }
      //   let a = false;
      //   // 根据请发数量计算
      //   if(record.row.pleaseSendNumber !== '' && record.row.pleaseSendNumber !== undefined){
      //     console.log("record.row",record.row);
      //     let numberStar = 0;
      //     let numberEnd = 0;
      //     // record.row.materialAmount = record.row.materialQuantity * record.row.materialPrice;
      //     // 获取被逻辑删除的字段id
      //     // let deleteIds = this.$refs.processMaterialsDeliveryList.getDeleteIds();
      //     // 获取所有表单的值，并进行验证
      //     let batcher = false;
      //     let { error, values } = this.$refs.processMaterialsDeliveryList.getValuesSync({  })
      //     // console.log( values);
      //       values.forEach( item => {
      //           //判断是不是操作第一个
      //           if(item.id === record.row.id){
      //             let bat = record.row.batch.substring(0,record.row.batch.indexOf('/'));
      //             if(parseInt(bat) === 1){
      //               // console.log("第一批");
      //                batcher = true;
      //             }
      //           }
      //           //判断下面是不是有一样的物资
      //           if(item.id !== record.row.id && item.equipment === record.row.equipment ){
      //               //有
      //               let cf = record.row.pleaseSendNumber - record.row.actualSendNumber;
      //               if(cf < 0 ){
      //                 let ba = record.row.batch.substring(0,record.row.batch.indexOf('/'));
      //                 if(parseInt(ba) === 1 ){
      //                   record.row.actualSendNumber = record.row.pleaseSendNumber;
      //                   //请减小
      //                   let values = [
      //                     {
      //                       rowKey: record.row.id,
      //                       values: {
      //                         'equipment': record.row.equipment,
      //                         'materialGroup': record.row.materialGroup,
      //                         'materialName': record.row.materialName,
      //                         'materialUnit': record.row.materialUnit,
      //                         'supplier': record.row.supplier,
      //                         'materialPrice': record.row.price ,
      //                         'actualSendNumber': record.row.actualSendNumber,
      //                         'materialAmount': record.row.price * record.row.actualSendNumber,
      //                         'pleaseSendNumber' : record.row.pleaseSendNumber,
      //                         'batch' : record.row.batch,
      //                       },
      //                     },
      //                   ]
      //                   this.$refs.processMaterialsDeliveryList.setValues(values);
      //                   this.$refs.processMaterialsDeliveryList.removeRows(item.id);
      //                 }else {
      //
      //                   batcher =true;
      //                 }
      //
      //               }else{
      //                 //请变大
      //                 this.$refs.processMaterialsDeliveryList.removeRows(item.id);
      //
      //               }
      //           }
      //
      //       })
      //     //第二行操作
      //     if(batcher){
      //       // console.log("执行了123")
      //       let num = 0;
      //       this.bigIdMerchandiseNewsList.forEach( item =>{
      //         // console.log("item",item);
      //         num =  record.row.pleaseSendNumber - item.residueNumber; //第二行显示的数量
      //         if(num > 0){
      //           // 限制最大数量
      //           record.row.pleaseSendNumber = item.residueNumber;
      //           record.row.actualSendNumber = record.row.pleaseSendNumber;
      //           record.row.MaterialsDeliveryId = item.id;
      //           //添加一行
      //           this.$refs.processMaterialsDeliveryList.handleClickAdd();
      //           this.jiy.push(this.addId);
      //           a =true;
      //         }else{
      //           record.row.actualSendNumber = record.row.pleaseSendNumber;
      //           record.row.MaterialsDeliveryId = item.id;
      //           // console.log("执行了222" ,record.row.actualSendNumber);
      //         }
      //
      //       });
      //       let drop = record.row.materialGroup;
      //       let values = [
      //         {
      //           rowKey: record.row.id,
      //           values: {
      //             'equipment': record.row.equipment,
      //             'materialGroup': record.row.materialGroup,
      //             'materialName': record.row.materialName,
      //             'materialUnit': record.row.materialUnit,
      //             'supplier': record.row.supplier,
      //             'materialPrice': record.row.materialPrice,
      //             'actualSendNumber': record.row.actualSendNumber,
      //             'materialAmount': record.row.actualSendNumber * record.row.materialPrice,
      //             'pleaseSendNumber' : record.row.pleaseSendNumber,
      //             'batch' : record.row.batch,
      //             'MaterialsDeliveryId': record.row.MaterialsDeliveryId,
      //           },
      //         },
      //       ]
      //       this.$refs.processMaterialsDeliveryList.setValues(values);
      //       //重新赋值
      //       if(a){
      //         let merchandiseNewser = {};
      //         let merchandiseNews = {};
      //         let is = false;
      //         let onIs= false;
      //         do{
      //           if(is){
      //             this.$refs.processMaterialsDeliveryList.handleClickAdd();
      //             merchandiseNewser =await this.fetchMerchandiseNews(drop,parseInt(numberStar));
      //           }else{
      //             merchandiseNewser =await this.fetchMerchandiseNews(drop,2);
      //           }
      //           merchandiseNewser.forEach( item => {
      //             merchandiseNews = item;
      //           });
      //           // console.log("numberStar",numberStar)
      //           numberStar = merchandiseNews.batch.substring(0,merchandiseNews.batch.indexOf("/"));
      //           numberEnd = merchandiseNews.batch.slice(numberStar.length+1);
      //           // console.log(merchandiseNews);
      //           let sum =  num - merchandiseNews.residueNumber; //剩余数量
      //           let isLose = parseInt(numberEnd) - parseInt(numberStar);
      //           // console.log("isLose",isLose);
      //           if(isLose === 0 ){
      //             onIs = true;
      //           }
      //           if( sum > 0 ){
      //             //第三批
      //               is = true;
      //               numberStar = parseInt(numberStar)+1;
      //             sum = merchandiseNews.residueNumber;
      //           }else{
      //             sum = num;
      //             // console.log("sum=================>",sum);
      //             is = false;
      //
      //           }
      //           let values = [
      //             {
      //               rowKey: this.addId,
      //               values: {
      //                 'equipment': record.row.equipment,
      //                 'materialGroup': record.row.materialGroup,
      //                 'materialName': record.row.materialName,
      //                 'materialUnit': record.row.materialUnit,
      //                 'supplier': record.row.supplier,
      //                 'materialPrice': merchandiseNews.price ? merchandiseNews.price : 0 ,
      //                 'actualSendNumber': sum ,
      //                 'materialAmount': sum * merchandiseNews.price ? sum * merchandiseNews.price : 0,
      //                 'pleaseSendNumber' : sum,
      //                 'batch' : merchandiseNews.batch,
      //                 'MaterialsDeliveryId': merchandiseNews.id,
      //               },
      //             },
      //           ]
      //           this.$refs.processMaterialsDeliveryList.setValues(values);
      //           //减小num 数量
      //           num = num - merchandiseNews.residueNumber;
      //           if(onIs){
      //             //还要继续查询
      //
      //             this.$message.warn('暂无更多库存！');
      //             is = false;
      //             return;
      //           }
      //         }while (is);
      //       }
      //
      //     }
      //
      //   }
      //
      // },
      // fetchMerchandiseNews(value,batch){ //查询物料清单信息
      //   //查询大品类数据
      //   return  new Promise((resolve, reject) => {
      //     //你的逻辑代码
      //     let par = {
      //       delFlag: 0,
      //       descriptionId:value,
      //       batchNum: batch,
      //     }
      //     this.bigIdMerchandiseNews = [];
      //     this.bigIdMerchandiseNewsList = [];
      //     let qc = [];
      //     let numberList = [];
      //     if(this.processMaterialsDeliveryListTable.columns[1].options.length > 0){
      //       this.processMaterialsDeliveryListTable.columns[1].options = [];
      //     }
      //     this.$refs.processMaterialsDeliveryList.getValues((a,b,c)=>{
      //       // console.log(a,b,c)
      //       b.forEach(item =>{
      //         if(item.equipment !== '' && item.equipment !== undefined && item.equipment !== null){
      //           numberList.push(item.materialNumber);
      //         }
      //       });
      //     });
      //     getAction(this.url.merchandiseNewsList,par).then((res)=>{
      //       if(res.success){
      //         console.log(res.result);
      //         let newList = res.result;
      //         // console.log("12312312:"+numberList.length);
      //         if(numberList.length > 0){
      //           newList.forEach( item => {
      //             qc.push({
      //               title : item.materialsNumber,
      //               value :  item.merchandiseNewsId,
      //               disabled : false
      //             })
      //           })
      //           numberList.forEach( num => {
      //             qc.forEach( i => {
      //               if(num === i.value){
      //                 // console.log(num,i.value);
      //                 i.disabled = true;
      //               }
      //             });
      //           })
      //           this.processMaterialsDeliveryListTable.columns[1].options = qc;
      //         }else{
      //           newList.forEach( item => {
      //             this.processMaterialsDeliveryListTable.columns[1].options.push({
      //               title : item.materialsNumber,
      //               value :  item.merchandiseNewsId,
      //               disabled : false
      //             })
      //           })
      //         }
      //         // console.log(this.processUdgetPlanMaterialTable.columns[1].options);
      //         resolve(this.bigIdMerchandiseNewsList = res.result );
      //         // return
      //       }
      //     });
      //
      //   });
      //
      // },

      fetchData(value) { //查询物料组
        //  console.log("this.data==============>",this.data) //部门id
        let params = {}
        params.id = sessionStorage.getItem('USER_INFORMATION')//关联中间表id

        let ue = sessionStorage.getItem('USER_INFORMATION')
        let res = JSON.parse(ue)
        if (res.realname !== '管理员') {
          // console.log("78979789",res);
          //  查询大品类数据 账外库
          let par = {
            delFlag: 0,
            accountingAttributes: value,
            departId: this.data.departId
          }
          getAction(this.url.wasteMaterialsUrl, par).then((res) => {
            // console.log(res)
            if (res.success) {
              if (this.processMaterialsDeliveryListTable.columns[0].options.length > 0) {
                this.processMaterialsDeliveryListTable.columns[0].options = []
              }
              res.result.forEach(item => {
                this.processMaterialsDeliveryListTable.columns[0].options.push({
                  title: item.materialClassify,
                  value: item.descriptionId
                })
              })
            }
          })
          this.rolePlay = true
        } else {
          //查询大品类数据 总库
          let par = {
            delFlag: 0,
            accountingAttributes: value
          }
          getAction(this.url.descriptionRake, par).then((res) => {
            // console.log('1231234123', res)
            if (res.success) {
              if (this.processMaterialsDeliveryListTable.columns[0].options.length > 0) {
                this.processMaterialsDeliveryListTable.columns[0].options = []
              }
              res.result.forEach(item => {
                this.processMaterialsDeliveryListTable.columns[0].options.push({
                  title: item.materialClassify,
                  value: item.descriptionId
                })
              })
            }
          })
          this.rolePlay = false
        }

        // getAction(this.url.unitWasteWarehouseList, params).then((res) => {
        //   console.log(res)
        //   if (res.success) {
        //     //  查询大品类数据 账外库
        //     let par = {
        //       delFlag: 0,
        //       accountingAttributes: value,
        //       departId: this.data.departId
        //     }
        //     getAction(this.url.wasteMaterialsUrl, par).then((res) => {
        //       console.log(res)
        //       if (res.success) {
        //         if (this.processMaterialsDeliveryListTable.columns[0].options.length > 0) {
        //           this.processMaterialsDeliveryListTable.columns[0].options = []
        //         }
        //         res.result.forEach(item => {
        //           this.processMaterialsDeliveryListTable.columns[0].options.push({
        //             title: item.descriptionName,
        //             value: item.descriptionId
        //           })
        //         })
        //       }
        //     })
        //     this.rolePlay = true;
        //   } else {
        //     //查询大品类数据 总库
        //     let par = {
        //       delFlag: 0,
        //       accountingAttributes: value
        //     }
        //     getAction(this.url.descriptionRake, par).then((res) => {
        //       if (res.success) {
        //         if (this.processMaterialsDeliveryListTable.columns[0].options.length > 0) {
        //           this.processMaterialsDeliveryListTable.columns[0].options = []
        //         }
        //         res.result.forEach(item => {
        //           this.processMaterialsDeliveryListTable.columns[0].options.push({
        //             title: item.descriptionName,
        //             value: item.descriptionId
        //           })
        //         })
        //       }
        //     })
        //     this.rolePlay = false;
        //   }
        // })

      },

      /*回显数据*/
      init() {
        this.btndisabled = true
        var r = this.processData
        this.getAssignees(r)
        if (!r.tableId) {
          return
        }
        this.getAction(this.url.queryById, {
          id: r.tableId
        }).then((res) => {
          if (res.success) {
            this.$emit('delivery', res.result.deliveryType)
            let formData = res.result
            formData.tableName = r.tableName
            this.data = formData
            console.log('表单回显数据', this.data)
            this.editAfter()
            this.btndisabled = false
          } else {
            this.$message.error(res.message)
          }
        })
      },
      close() {
        //todo 关闭后的回调
        this.$emit('close')
      },
      /*通过审批*/
      async passTask() {
        let qing = false
        if (!this.actualNumber) {
          await this.getAllTable().then(tables => {
            return validateFormAndTables(this.form, tables)
          }).then(allValues => {
            let formData = this.classifyIntoFormData(allValues)
            if (formData.processMaterialsDeliveryListList.length > 0) {

              formData.processMaterialsDeliveryListList.forEach(item => {
                if (!item.actualSendNumber) {
                  qing = true
                }
              })
              if (qing) {
                console.log('============', qing)
                this.$message.warning('请填写实发数！！！')
              } else {
                let method = 'put'
                httpAction(this.url.edit, formData, method).then((res) => {
                  if (res.success) {

                  }
                }).finally(() => {

                })
              }
            }
            console.log('所有数据========', formData)
          })
        }
        if (!qing) {
          console.log('============', qing)
          this.$emit('passTask')
        }

      },
      /*驳回审批*/
      backTask() {
        this.$emit('backTask')
      },
      /*提交申请*/
      applySubmit(e) {
        this.getAllTable().then(tables => {
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {

          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          formData.fileId = getStringArry(formData.fileId)
          console.log('所有数据', formData)
          if (new Date(formData.createTime).getTime() / 100 > new Date(formData.deliveryTime).getTime() / 100) {
            this.$message.error('出库时间不能小于当前流程发起时间')
            return
          }
          // if (formData.materialType === null || formData.materialType ==='' || formData.materialType === undefined){
          //   this.$message.error("物资类型不能为空")
          //   return;
          // }
          // if (formData.deliveryTime === null || formData.deliveryTime ==='' || formData.deliveryTime === undefined){
          //   this.$message.error("出库时间不能为空")
          //   return;
          // }
          for (let i = 0; i < formData.processMaterialsDeliveryListList.length; i++) {
            if (i == 0) {
              this.describes = formData.processMaterialsDeliveryListList[i].materialName
            } else {
              this.describes = this.describes + '---' + formData.processMaterialsDeliveryListList[i].materialName
            }
          }
          formData.describes = this.describes
          this.form.validateFields((err, values) => {
            if (!err) {
              formData.procDefId = this.processData.id
              formData.procDeTitle = this.processData.name
              formData.title = this.processData.description
              formData.targetLibrary = this.libraryAssociationIdInvisible
              formData.deliveryType = this.deliveryType
              formData.isOffice = this.isOffice
              if (!formData.tableName) formData.tableName = this.processData.businessTable
              console.log('格式化后的数据', formData)
              var url = this.url.addDeliveryApply
              let method = 'post'
              if (!this.isNew) {
                url = this.url.editDeliveryApply
                method = 'put'
                formData.assignees = this.assignees
                formData.tableName = this.processData.tableName
                formData.procDefId = this.processData.procDefId
                formData.procDeTitle = this.processData.processName
                formData.title = this.processData.title
                formData.processInstanceId = this.processData.id
              }
              if (formData.processMaterialsDeliveryListList.length > 0) {
                let qing = false
                formData.processMaterialsDeliveryListList.forEach(item => {
                  if (!!item.equipment) {
                    if (!item.pleaseSendNumber) {
                      qing = true
                    }
                  } else {
                    this.$message.warning('请填写数据！！！')
                  }

                })
                if (qing) {
                  this.$message.warning('请填写请发数！！！')
                  return
                }
              }

              console.log('提交方法', method)
              if (this.btndisabled === false) {
                this.btndisabled = true
                httpAction(url, formData, method).then((res) => {
                  if (res.success) {
                    this.$message.success('提交申请成功！')
                    //todo 将表单的数据传给父组件
                    this.$emit('loadData')
                    this.close()
                  } else {
                    this.$message.error(res.message)
                  }
                }).finally(() => {
                  this.btndisabled = false
                })
              }
            }
          })
        })

      },
      handleSubmit(e) {
        this.getAllTable().then(tables => {
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {

          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          formData.fileId = getStringArry(formData.fileId)
          console.log('所有数据', formData)
          if (new Date(formData.createTime).getTime() / 100 > new Date(formData.deliveryTime).getTime() / 100) {
            this.$message.error('出库时间不能小于当前流程发起时间')
            return
          }
          // if (formData.materialType === null || formData.materialType ==='' || formData.materialType === undefined){
          //   this.$message.error("物资类型不能为空")
          //   return;
          // }
          // if (formData.deliveryTime === null || formData.deliveryTime ==='' || formData.deliveryTime === undefined){
          //   this.$message.error("出库时间不能为空")
          //   return;
          // }
          for (let i = 0; i < formData.processMaterialsDeliveryListList.length; i++) {
            if (i == 0) {
              this.describes = formData.processMaterialsDeliveryListList[i].materialName
            } else {
              this.describes = this.describes + '---' + formData.processMaterialsDeliveryListList[i].materialName
            }
          }
          formData.describes = this.describes
          this.form.validateFields((err, values) => {
            if (!err) {
              formData.procDefId = this.processData.id
              formData.procDeTitle = this.processData.name
              formData.title = this.processData.description
              formData.targetLibrary = this.libraryAssociationIdInvisible
              formData.deliveryType = this.deliveryType
              formData.isOffice = this.isOffice
              if (!formData.tableName) formData.tableName = this.processData.businessTable
              console.log('格式化后的数据', formData)
              var url = this.url.add
              let method = 'post'
              if (!this.isNew) {
                url = this.url.edit
                method = 'put'
              }
              console.log('提交方法', method)
              if (this.btndisabled === false) {
                this.btndisabled = true
                httpAction(url, formData, method).then((res) => {
                  if (res.success) {
                    //this.$message.success("保存成功！")
                    //todo 将表单的数据传给父组件
                    this.$emit('afterSubmit', formData)
                  } else {
                    this.$message.error(res.message)
                  }
                }).finally(() => {
                  this.btndisabled = false
                })
              }
            }
          })
        })

      },
      addBefore() {
        this.form.resetFields()
        this.processMaterialsDeliveryListTable.dataSource = []
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        if (this.data.id != null && this.data.id != '' && this.data.id != undefined && this.data.fileId != null && this.data.fileId != '') {
          //1、文件回显
          this.data = getRecord(this.data)

        }
        console.log('回显数据', this.data)
        let fieldval = pick(this.data, 'id', 'deliveryType', 'company', 'createTime', 'departId', 'createBy', 'materialType', 'deliveryTime', 'fileId', 'opinion', 'isOffice')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.data.id) {
          let params = { id: this.data.id }
          this.requestSubTableData(this.url.processMaterialsDeliveryList.list, params, this.processMaterialsDeliveryListTable)
        }
      },

      /** 查询某个tab的数据 */
      requestSubTableData(url, params, tab, success) {
        tab.loading = true
        getAction(url, params).then(res => {
          let { result } = res
          let dataSource = []
          if (result) {
            if (Array.isArray(result)) {
              dataSource = result
            } else if (Array.isArray(result.records)) {
              dataSource = result.records
            }
          }

          // console.log('tab.dataSource', dataSource)
          dataSource.forEach(item => {
            let par = { id: item.materialGroup }
            let param = { id: item.equipment }
            getAction(this.url.queryByIdDescription, par).then(res => {
              // console.log(res);
              if (res.success) {
                this.processMaterialsDeliveryListTable.columns[0].options = [{
                  title: res.result.materialClassify,
                  value: item.materialGroup,
                  disabled: true
                }]
              }
            })
            getAction(this.url.queryByIdMerchandiseNews, param).then(res => {
              // console.log(res)
              if (res.success) {
                this.processMaterialsDeliveryListTable.columns[1].options = [{
                  title: res.result.materialsNumber,
                  value: item.equipment,
                  disabled: true
                }]
              }
            })
            if (this.actualNumber) {
              // console.log(item,"===========");
              item.actualSendNumber = null
            }
          })
          tab.dataSource = dataSource
          typeof success === 'function' ? success(res) : ''
        }).finally(() => {
          tab.loading = false
        })

      },

      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          processMaterialsDeliveryListList: 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)
            }
          })
        }
      },
      validateError(msg) {
        this.$message.error(msg)
      },
      popupCallback(company, row, puwwcid) {
        let res = JSON.parse(row)
        if (puwwcid != null) {
          let params = {}
          params.id = puwwcid
          this.getAction(this.url.puwwlist, params).then((rest) => {
            if (rest.success) {
              this.libraryAssociationIdInvisible = rest.result.unit
            }
          })

        }
        console.log('获取我的数据', res)
        if (res.orgType != 3) {
          let isDepartId = res.departIds
          this.getAction('/officeConfig/queryByDepartId', {
            id: isDepartId
          }).then((res) => {
            if (res.success) {
              console.log(res.result.length, '***********************************************************')
              if (res.result.length != 0) {
                this.isOffice = 1
                this.deliveryType = 2
              }
            }
          })
        } else if (res.orgType == 3) {
          this.isOffice = 2
          this.deliveryType = 2
        } else {
          this.deliveryType = 1
        }
        let param = {}
        param.createBy = res.username
        param.company = company
        param.departId = res.departIds
        param.createTime = getCurrentTime()
        this.data = param
        let fieldval = pick(this.data, 'createBy', 'company', 'departId', 'createTime')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
      },
      getAssignees(v) {
        getAction(this.url.getFirstNode, {
          procDefId: v.procDefId,
          tableId: v.tableId,
          tableName: v.tableName
        }).then(res => {
          if (res.success) {
            if (res.result.users && res.result.users.length > 0) {
              // 默认勾选
              let ids = []
              res.result.users.forEach(e => {
                ids.push(e.username)
              })
              this.assignees = ids.join(',')
            }

          }
        })
      }

    }
  }
</script>

<style scoped>
  .div_process {
    margin-top: 30px;
  }

  .ant-col-8 {
    height: 50px;
  }
</style>