<template>

  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <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">
            <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']" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="物资类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['materialType',validatorRules.materialType]"
                                 :trigger-change="true" dictCode="material_type"
                                 placeholder="请选择物资类型" @change="elect"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="流程计划" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['processPlan',validatorRules.processPlan]"
                                 :trigger-change="true" dictCode="process_plan"
                                 placeholder="请选择流程计划"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="需求时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择需求时间" v-decorator="['needTime',validatorRules.needTime]" :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="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['sort',validatorRules.sort]" placeholder="请输入序号"
                              style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-show="isPlanType">
            <a-form-item label="采购类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['planType']"
                                 :trigger-change="true" dictCode="plan_type"
                                 placeholder="请选择采购类型电商或非电商"/>
            </a-form-item>
          </a-col>
          <a-col :span="8" v-show="isSourceCapital">
            <a-form-item label="资金来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['sourceCapital']"
                                 :trigger-change="true" dictCode="source_capital"
                                 placeholder="请选择资金来源"/>
            </a-form-item>
          </a-col>


          <a-col :span="8">
            <a-form-item label="文件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <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" ref="tabs">
      <a-tab-pane tab="预算计划采购流程物料清单表" :key="refKeys[0]" :forceRender="true">
        <p-editable-table
          ref="processUdgetPlanMaterial"
          :loading="processUdgetPlanMaterialTable.loading"
          :columns="processUdgetPlanMaterialTable.columns"
          :dataSource="processUdgetPlanMaterialTable.dataSource"
          @valueChange="onSelect"
          :maxHeight="300"
          :action-button="true"
          :rowNumber="true"
          :disabled="hiegs"
          :isabled="isabled"
          :rowSelection="true"
          :actionButton="true"
          @shifu = "shifu"
          @descriptionFetch="fetchMerchandiseNews"
        >
          <template v-slot:action="props">
            <a-tooltip placement="top">
              <template v-slot:title="props">
                <p v-for="(item,index) in historyBigId" :key="index">历史价格：{{ item }}</p>
              </template>
              <a-button @mouseenter="chaKan(props)">查看</a-button>
            </a-tooltip>
            <!--          <a-button @click="chaKan(props)">查看</a-button>-->
          </template>
        </p-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>
              <!--<a-input type="textarea" v-decorator="[ 'opinion' ]" :rows="4" />-->
            </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 type="primary"  @click="ewrold">下载</a-button>-->
        <a-button style="margin-left: 8px" @click="backTask">驳回</a-button>
      </a-form-item>
    </div>
  </a-spin>
</template>

<script>

  const VALIDATE_NO_PASSED = Symbol()
  import pick from 'lodash.pick'
  import { getAction, httpAction, getCurrentTime, getStringArry, getRecord, downFile } from '@/api/manage'
  import { FormTypes, getRefPromise, validateFormAndTables } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'
  import JUpload from '@/components/jeecg/JUpload'
  import FileList from '@/components/jeecg/FileList'
  import JSelectCompany from '@/components/jeecgbiz/JSelectCompany'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JEditor from '@/components/jeecg/JEditor'

  // const columns = [
  //   {
  //     title: 'name',
  //     dataIndex: 'name',
  //     width: '25%',
  //     scopedSlots: { customRender: 'name' },
  //   },
  //   {
  //     title: 'age',
  //     dataIndex: 'age',
  //     width: '15%',
  //     scopedSlots: { customRender: 'age' },
  //   },
  //   {
  //     title: 'address',
  //     dataIndex: 'address',
  //     width: '40%',
  //     scopedSlots: { customRender: 'address' },
  //   },
  //   {
  //     title: 'operation',
  //     dataIndex: 'operation',
  //     scopedSlots: { customRender: 'operation' },
  //   },
  // ];
  // const data = [];
  // for (let i = 0; i < 100; i++) {
  //   data.push({
  //     key: i.toString(),
  //     name: `Edrward ${i}`,
  //     age: 32,
  //     address: `London Park no. ${i}`,
  //   });
  // }

  export default {
    name: 'ProcessUdgetPlanForm',
    mixins: [JEditableTableMixin],
    components: {
      JFormContainer,
      JDate,
      JUpload,
      FileList,
      JSelectDepart,
      JSelectUserByDep,
      JDictSelectTag,
      JSelectCompany,
      JEditor
    },
    data() {
      // this.cacheData = data.map(item => ({ ...item }));
      return {
        //用于回显物料号
        listId: [],
        // data,
        // columns,
        // editingKey: '',
        isabled: true,
        isPlanType: false,
        isSourceCapital: false,
        bigId: [],
        opinion: '',
        bigIdRake: [],
        materialGroups: '',
        materialId: '',
        bigIdRakeList: [],
        materialPrice: 0,
        materialAmount: 0,
        getMaterialAmount: 0,
        describes: '',
        hiegs: true,
        historyBigId: [],
        isHistoryBigId: false,
        bigIdMerchandiseNews: [],
        bigIdMerchandiseNewsList: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        refKeys: ['processUdgetPlanMaterial'],
        tableKeys: ['processUdgetPlanMaterial'],
        activeKey: 'processUdgetPlanMaterial',
        // 预算计划采购流程物料清单表
        processUdgetPlanMaterialTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料组',
              key: 'materialGroup',
              // type: FormTypes.slot, //  <-------------改为 slot 格式
              // slotName: 'actions',   //  <-------------slot 的名称，对应 v-slot 冒号后面和等号前面的内容
              // type: FormTypes.slot,
              type: FormTypes.sel_search,
              disabled: true,
              // slotName: 'group',
              width: '200px',
              options: []
              // scopedSlots: { customRender: 'edit' },//引入的插槽
              // customRender:function (t,r,index) {
              //     console.log(t,r);
              //
              // }

            },
            {
              title: '物料号',
              key: 'materialNumber',
              type: FormTypes.sel_search,
              dictCode: '',
              disabled: this.disabled,
              width: '200px',
              placeholder: '请输入${title}',
              options: []
              // // 表单验证规则
              // validateRules: [
              //   {
              //     required: true, // 必填
              //     message: '请输入${title}' // 提示的文本
              //   },
              //   {
              //     pattern: /^[a-z|A-Z][a-z|A-Z\d_-]{0,}$/, // 正则
              //     message: '${title}必须以字母开头，可包含数字、下划线、横杠'
              //   }
              // ]
            },
            // {
            //   title: '仓储地点_id',
            //   key: 'unitWasteWarehouseCodeId',
            //   type: FormTypes.input,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            // {
            //   title: '生产时间',
            //   key: 'productionTime',
            //   type: FormTypes.date,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            // {
            //   title: '保质期',
            //   key: 'expirationDate',
            //   type: FormTypes.date,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            // {
            //   title: '是否到货',
            //   key: 'arrivalNotice',
            //   type: FormTypes.inputNumber,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            // {
            //   title: '入库时间',
            //   key: 'storageTime',
            //   type: FormTypes.date,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            // {
            //   title: '入库人',
            //   key: 'librarySign',
            //   type: FormTypes.input,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            // {
            //   title: '核算属性',
            //   key: 'materialType',
            //   type: FormTypes.input,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            {
              title: '物料名称及规格型号',
              key: 'materialName',
              type: FormTypes.input,
              disabled: this.disabled,
              // type: FormTypes.sel_search,
              // dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''

            },
            {
              title: '系列',
              key: 'materialSeries',
              type: FormTypes.input,
              disabled: this.disabled,
              // dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            {
              title: '单位',
              key: 'materialUnit',
              type: FormTypes.input,
              disabled: this.disabled,
              // type: FormTypes.select,
              // dictCode: '',
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            {
              title: '单价(元）',
              key: 'materialPrice',
              type: FormTypes.inputNumber,
              disabled: this.disabled,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            {
              title: '对比单价',
              key: 'action',
              type: FormTypes.slot,
              disabled: this.disabled,
              width: '80px',
              // placeholder: '请输入${title}',
              // defaultValue: '',
              slotName: 'action'
              // scopedSlots: {customRender: 'fileSlot'}
            },
            {
              title: '数量',
              key: 'materialQuantity',
              type: FormTypes.inputNumber,
              disabled: this.disabled,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            {
              title: '金额（元）',
              key: 'materialAmount',
              type: FormTypes.inputNumber,
              disabled: true,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            {
              title: '供应商',
              key: 'supplierId',
              type: FormTypes.input,
              disabled: true,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            {
              title: '执行标准',
              key: 'materialStandard',
              type: FormTypes.input,
              disabled: this.disabled,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            // {
            //   title: '到货总批次',
            //   key: 'warehousingBatch',
            //   type: FormTypes.inputNumber,
            //   disabled: this.disabled,
            //   width: '200px',
            //   placeholder: '请输入${title}',
            //   defaultValue: ''
            // },
            {
              title: '交货时间',
              key: 'deliveryTime',
              type: FormTypes.date,
              disabled: this.disabled,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            },
            {
              title: '备注',
              key: 'remarks',
              type: FormTypes.input,
              disabled: this.disabled,
              width: '200px',
              placeholder: '请输入${title}',
              defaultValue: ''
            }
          ]
        },
        url: {
          add: '/hy/processUdgetPlan/add',
          edit: '/hy/processUdgetPlan/edit',
          addFromTableApply: '/hy/processUdgetPlan/addFromTableApply',
          editFromTableApply: '/hy/processUdgetPlan/editFromTableApply',
          queryById: '/hy/processUdgetPlan/queryById',
          selectdeparment: '/sys/selectByUser',
          descriptionRakeUrl: '/description/processDescription/list',
          descriptionRakeUrlId: '/description/processDescription/queryById',
          descriptionRake: '/description/processDescription/descriptionName',
          merchandiseNewsList: '/merchandisenews/processMerchandiseNews/merchandiseNewsList',
          historyUrl: '/suppliesstronger/processSuppliesStronger/list',
          getFirstNode: '/actProcessIns/getFirstNode',
          processUdgetPlanMaterial: {
            list: '/hy/processUdgetPlan/queryProcessUdgetPlanMaterialByMainId'
          },
          processUdgetPlanMaterialLists: '/hy/processUdgetPlan/queryProcessUdgetPlanMaterialByMainIdList'
        },
        btndisabled: false,
        isShowInput: '',
        assignees: '',
        // 表单校验
        validatorRules: {
          // 'blur'是鼠标失去焦点的时候会触发验证
          materialType: { rules: [{ required: true, message: '请选择物资类型!' }] },
          needTime: { rules: [{ required: true, message: '请选择需求时间!' }] },
          processPlan: { rules: [{ required: true, message: '请选择流程计划!' }] },
          sort: { rules: [{ required: true, type:'number', max:999999999999, message: '请输入序号!(0 ~ 12个字符)'},
                          // { type:'number', max:999999999999, message: '长度在 0 到 12 个字符'}
                          // {validator: this.lengthCheck}
                        ]
          }
        },
        isBu: undefined,
        planType: '',
        isShifu:false
      }
    },
    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
      },
      //表单禁用
      hieg: {
        type: Boolean,
        default: true,
        required: false
      },
      dianshang: {
        type: Number,
        default: 0,
        required: false
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        // console.log("523452345",this.disabled);
        // console.log("34523452345",this.hieg);
        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) {
          this.planType = val
          console.log("this.planType---",this.planType)
        }
      }
    },
    created() {
      //如果是流程中表单，则需要加载流程表单data
      //this.showFlowData()

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

    },
    mounted() {
      // console.log( this.$refs.processUdgetPlanMaterial);
      // this.form.setFieldsValue("materialGroup",123123);
    },
    methods: {
      lengthCheck(rule, value, callback){
        if (value.toString().length >= 12 ){
          // console.log("长度太长了");
          callback("长度应当在0 ~ 12 字符")
        }
      },
      selectRowChange(a, b, c) {
        // console.log("执行了",a,b,c);
      },
      shifu(){
        console.log("执行了");
        this.isShifu = true;
      },

      // handleChange(value, key, column) {
      //   const newData = [...this.data];
      //   const target = newData.find(item => key === item.key);
      //   if (target) {
      //     target[column] = value;
      //     this.data = newData;
      //   }
      // },
      // edit(key) {
      //   const newData = [...this.data];
      //   const target = newData.find(item => key === item.key);
      //   this.editingKey = key;
      //   if (target) {
      //     target.editable = true;
      //     this.data = newData;
      //   }
      // },
      // save(key) {
      //   const newData = [...this.data];
      //   const newCacheData = [...this.cacheData];
      //   const target = newData.find(item => key === item.key);
      //   const targetCache = newCacheData.find(item => key === item.key);
      //   if (target && targetCache) {
      //     delete target.editable;
      //     this.data = newData;
      //     Object.assign(targetCache, target);
      //     this.cacheData = newCacheData;
      //   }
      //   this.editingKey = '';
      // },
      // cancel(key) {
      //   const newData = [...this.data];
      //   const target = newData.find(item => key === item.key);
      //   this.editingKey = '';
      //   if (target) {
      //     Object.assign(target, this.cacheData.find(item => key === item.key));
      //     delete target.editable;
      //     this.data = newData;
      //   }
      // },

      elect(val) {
        if (val != undefined) {
          this.hiegs = false
          // this.fetchData();
          // this.fetchDataRake()
          this.fetchMerchandiseNews();
        }
      },
      //物料组选择触发
      onSelectRake(props, value) {
        // console.log('onSelect', value,props);
        this.searchRake(value, props)
      },
      //物料组输入触发
      onSearchRake(searchText) {
        // console.log(searchText)
        this.fetchDataRake(searchText)
      },
      fetchDataRake(value) {
        //查询大品类数据
        let par = {
          delFlag: 0,
          descriptionName: value,
          pageSize: 100
        }
        this.bigIdRake = []
        this.bigIdRakeList = []
        getAction(this.url.descriptionRakeUrl, par).then((res) => {
          if (res.success) {
            // console.log(res.result);
            res.result.records.forEach(item => {
              this.bigIdRake.push(item.materialClassify)
            })
            this.bigIdRakeList = res.result.records
          }
        })
      },
      //物料组触发集合
      async searchRake(val, pro) {
        // console.log(pro)
        for (const item of this.bigIdRakeList) {
          // console.log(item);
          if (item.descriptionName === val) {
            await this.fetchMerchandiseNews(item.id)
            this.materialId = item.id
          }
        }
        // console.log(this.materialId);

        if (pro.rowId !== undefined) {
          let values = [
            {
              rowKey: pro.rowId,
              values: {
                'materialNumber': '',
                'materialGroup': this.materialId,
                'materialSeries': '',
                'materialName': '',
                'materialUnit': '',
                'supplierId': '',
                'materialPrice': '',
                'materialQuantity': ''
              }
            }
          ]
          // console.log(values);
          this.$refs.processUdgetPlanMaterial.setValues(values)
        }

      },

      //查看历史价格
      async chaKan(log) {
        // console.log("00000000",log);
        let pas = await log.target.getValuesPromise(log.rowIds)
        // console.log("111111111",log.rowIds);
        // console.log("222222222222",pas);
        if (pas[log.index].materialNumber !== '' && pas[log.index].materialNumber !== null) {
          this.historyBigId = []
          //查询大品类数据
          let par = {
            delFlag: 0,
            merchandiseNewsId: pas[log.index].materialNumber,
            pageSize: 5
          }
          this.isHistoryBigId = false
          getAction(this.url.historyUrl, par).then((res) => {
            // console.log(res);
            if (res.success) {
              res.result.records.forEach(item => {
                if (parseInt(res.result.total) > 0) {
                  this.isHistoryBigId = true
                  this.historyBigId.push(item.materialPrice)
                }

              })

            }
          })
        }

      },
       //table 值改变触发
      async onSelect   (record)  {

        let isEr = true
        // if (!!record.row.materialGroup) {
        //   if (!!record.row.id && this.isBu !== record.row.materialGroup) {
        //     // console.log("1出发了",record.row);
        //     this.isabled = false
        //     this.fetchMerchandiseNews(record.row.materialGroup)
        //     this.isBu = record.row.materialGroup
        //     let values = [
        //       {
        //         rowKey: record.row.id,
        //         values: {
        //           'materialNumber': '',
        //           'materialSeries': '',
        //           'materialName': '',
        //           'materialUnit': '',
        //           'supplierId': '',
        //           'materialAmount': '',
        //           'materialType': ''
        //         }
        //       }
        //     ]
        //     this.$refs.processUdgetPlanMaterial.setValues(values)
        //     isEr = false
        //   }
        //   // if( record.row.id !== undefined && record.row.id !== ''   || record.row.materialNumber === '' || record.row.materialNumber === undefined){
        //   //   console.log("11出发了",record.row);
        //   // }
        // }
        // console.log("5555出发了",record.row);
        // if ( !!record.row.materialNumber && isEr) {
        let b = false;
        if(this.isShifu){
          // console.log("0出发了",record);
          for (const res of this.bigIdMerchandiseNewsList) {
            if(res.id === record.row.materialNumber ){
              b = true;
            }
          }
          if(!b){
            // console.log("进来了111");
            await this.fetchMerchandiseNews(null,record.row.materialNumber );
          }
        }
        this.isShifu = false;
        if(record.column.key !== 'materialPrice' && record.column.key !== 'materialQuantity'){
          if ( !!record.row.materialNumber && this.isBu !== record.row.materialNumber ) {
            // console.log("2出发了");
            let materialName = {}
            this.bigIdMerchandiseNewsList.forEach(item => {
              if (item.id === record.row.materialNumber) {
                materialName = {
                  materialClassify: item.materialClassify,
                  name: item.merchandiseName,
                  unit: item.materialsUnit,
                  supplierId: item.supplierId,
                  descriptionId: item.descriptionId
                }

              }
            })

            if (!!record.row.id && Object.keys(materialName).length > 0 ) {
              await this.$refs.processUdgetPlanMaterial.getValues((a, b, c) => {
                // console.log("bbbbbbbbbbbbbb",b)
                b.forEach(item => {
                  if (item.materialNumber === record.row.materialNumber && !!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.processUdgetPlanMaterial.setValues(values)
                    return ;

                  }
                })

              })


              this.processUdgetPlanMaterialTable.columns[0].options.push({
                title: materialName.materialClassify,
                value: materialName.descriptionId
              })
              let values = [
                {
                  rowKey: record.row.id,
                  values: {
                    'materialNumber': record.row.materialNumber,
                    'materialGroup': materialName.descriptionId,
                    // 'materialGroup': this.materialId,
                    'materialSeries': record.row.materialSeries,
                    'materialName': materialName.name,
                    'materialUnit': materialName.unit,
                    'supplierId': materialName.supplierId
                  }
                }
              ]
              this.$refs.processUdgetPlanMaterial.setValues(values)
              this.isBu = record.row.materialNumber;
              isEr = false
            }
          }
        }



        if (!!record.row.materialQuantity && !!record.row.materialPrice &&  isEr ) {
          // record.row.materialAmount = record.row.materialQuantity * record.row.materialPrice;
          // console.log("3出发了");
          //如果单价大于5万
          if (record.row.materialPrice > 50000) {
            this.materialPrice = record.row.materialPrice
          }
          //回填数据
          if (record.row.id !== undefined) {
            let values = [
              {
                rowKey: record.row.id,
                values: {
                  'materialNumber': record.row.materialNumber,
                  'materialGroup': record.row.materialGroup,
                  'materialSeries': record.row.materialSeries,
                  'materialName': record.row.materialName,
                  'materialUnit': record.row.materialUnit,
                  'materialAmount': record.row.materialQuantity * record.row.materialPrice,
                  'materialType': this.data.materialType
                }
              }
            ]
            this.$refs.processUdgetPlanMaterial.setValues(values)
            this.isabled = true
          }

        }

      },
      fetchMerchandiseNews(value,id) { //查询物料清单信息
        return new Promise((resolve, reject)=>{
          //查询大品类数据
          let par = {
            delFlag: 0,
            descriptionId: value,
            id:id
          }
          this.bigIdMerchandiseNews = []
          this.bigIdMerchandiseNewsList = []
          let qc = []
          let numberList = []
          if (this.processUdgetPlanMaterialTable.columns[1].options.length > 0) {
            this.processUdgetPlanMaterialTable.columns[1].options = []
          }
            this.$refs.processUdgetPlanMaterial.getValues((a, b, c) => {
              b.forEach(item => {
                if (item.materialNumber !== '' && item.materialNumber !== undefined && item.materialNumber !== null) {
                  numberList.push(item.materialNumber)
                }
              })

            })
          getAction(this.url.merchandiseNewsList, par).then((res) => {
            // console.log('12312', res.result)
            // console.log('12312')

            if (res.success) {
              let newList = res.result
              if (numberList.length > 0) {
                // console.log("大雨")
                newList.forEach(item => {
                  qc.push({
                    title: item.materialsNumber,
                    value: item.id,
                    disabled: false
                  })
                })
                numberList.forEach(num => {
                  qc.forEach(i => {
                    // console.log("111111111111111",i.value)
                    if (num === i.value && !!num) {
                      i.disabled = true
                    }
                  })
                })
                this.processUdgetPlanMaterialTable.columns[1].options = qc
              } else {
                // console.log("小雨")
                newList.forEach(item => {
                  this.processUdgetPlanMaterialTable.columns[1].options.push({
                    title: item.materialsNumber,
                    value: item.id,
                    disabled: false
                  })
                })
              }
              this.bigIdMerchandiseNewsList = res.result;
              // resolve( this.bigIdMerchandiseNewsList );
            }
            resolve( this.bigIdMerchandiseNewsList );
          })
        });

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

      descriptionFetchDatas(value) { //查询物料组
        //查询大品类数据
        let par = {
          delFlag: 0,
          pageSize: 50
        }
        this.bigId = []
        getAction(this.url.descriptionRakeUrl, par).then((res) => {
          // getAction(this.url.descriptionRake,par).then((res)=>{
          if (res.success) {
            if (this.processUdgetPlanMaterialTable.columns[0].options.length > 0) {
              this.processUdgetPlanMaterialTable.columns[0].options = []
            }
            res.result.records.forEach(item => {
              this.processUdgetPlanMaterialTable.columns[0].options.push({
                title: item.materialClassify,
                value: item.id
              })
            })
          }
        })
        this.isBu = undefined

      },
      /*回显数据*/
      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) {
            console.log("res.result.planType--",res.result.planType)
            this.$emit('planType',res.result.planType)
            this.planType = res.result.planType
            let formData = res.result
            formData.tableName = r.tableName
            this.data = formData
            if (formData.materialType) {
              // this.hieg=false;
              // this.fetchDataRake();
              this.descriptionFetchDatas()
            }
            this.editAfter()
            this.btndisabled = false
          } else {
            this.$message.error(res.message)
          }
        })
      },
      close() {
        //todo 关闭后的回调
        this.$emit('close')
      },
      /*通过审批*/
      passTask() {
        this.$emit('passTask')
      },
      /*导出world*/
      ewrold() {
        let formData = {}
        console.log(this.data.id, '数据回显>>>>>>>>>>>>>>>>>>>>>>>>>')
        formData.id = this.data.id
        downFile('/hy/processUdgetPlan/exportRequisition', formData).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }), '采购申请表')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '采购申请表')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      },
      /*驳回审批*/
      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)

          for (let i = 0; i < formData.processUdgetPlanMaterialList.length; i++) {
            if (i == 0) {
              this.describes = formData.processUdgetPlanMaterialList[i].materialName
            } else {
              this.describes = this.describes + '---' + formData.processUdgetPlanMaterialList[i].materialName
            }
          }
          formData.fileId = getStringArry(formData.fileId)
          formData.materialPrice = this.materialPrice
          formData.describes = this.describes
          if (new Date(formData.createTime).getTime() / 100 > new Date(formData.needTime).getTime() / 100) {
            this.$message.error('需求时间不能小于当前流程发起时间')
            return
          }
          console.log(this.opinion, '流程说明')
          this.form.validateFields((err, values) => {
            if (!err) {
              console.log(this.processData, '申请列表传值数据')
              formData.procDefId = this.processData.id
              formData.procDeTitle = this.processData.name
              formData.title = this.processData.description
              formData.planType=this.planType;
              console.log("this.planType++",this.planType)
              if (!formData.tableName) formData.tableName = this.processData.businessTable
              var url = this.url.addFromTableApply
              let method = 'post'
              if (!this.isNew) {
                url = this.url.editFromTableApply
                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
              }
              console.log(formData, '表单数据')
              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;
                })
              }
            }
          })
        })

      },
      addBefore() {
        this.form.resetFields()
        this.processUdgetPlanMaterialTable.dataSource = []
      },
      getAllTable() {
        if (!(this.refKeys instanceof Array)) {
          throw this.throwNotArray('refKeys')
        }
        let values = this.refKeys.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','planType', 'company', 'createTime', 'departId', 'createBy', 'materialType', 'processPlan', 'needTime','sort', 'orderNumber', 'fileId', 'opinion')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.data.id) {
          let params = { id: this.data.id }
          this.requestSubTableData(this.url.processUdgetPlanMaterialLists, params, this.processUdgetPlanMaterialTable)
          console.log('子表数据', this.processUdgetPlanMaterialTable)

        }
      },

      descriptionId(val){
        let pam = {
          id: val
        }
        getAction(this.url.descriptionRakeUrlId,pam).then(res =>{

          if(res.success){
            this.processUdgetPlanMaterialTable.columns[0].options.push({
              title: res.result.materialClassify,
              value: res.result.id
            })
          }
          // console.log(res.result.materialClassify);
        })
      },

      /** 查询某个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("result.records",dataSource);
          for (let i = 0; i < dataSource.length; i++) {
            this.listId.push(dataSource[i].materialGroup)
          }
          // console.log(this.listId)

          for (let i = 0; i < this.listId.length; i++) {
            // console.log(this.listId[i])\
            this.descriptionId(this.listId[i]);


            this.fetchMerchandiseNews(this.listId[i])
          }

          tab.dataSource = dataSource

          typeof success === 'function' ? success(res) : ''
        }).finally(() => {
          tab.loading = false
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        console.log('查看子表数据', allValues)
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          processUdgetPlanMaterialList: allValues.tablesValue[0].values
        }
      },
      // orgCodeTxt(a){
      // },
      //渲染流程表单数据
      showFlowData() {
        console.log(this.formBpm, '----------****')
        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) {
        let res = JSON.parse(row)
        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)
        })
      },
      // handler
      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)
          for (let i = 0; i < formData.processUdgetPlanMaterialList.length; i++) {
            if (i == 0) {
              this.describes = formData.processUdgetPlanMaterialList[i].materialName
            } else {
              this.describes = this.describes + '---' + formData.processUdgetPlanMaterialList[i].materialName
            }
          }
          formData.fileId = getStringArry(formData.fileId)
          formData.materialPrice = this.materialPrice
          formData.describes = this.describes
          if (new Date(formData.createTime).getTime() / 100 > new Date(formData.needTime).getTime() / 100) {
            this.$message.error('需求时间不能小于当前流程发起时间')
            return
          }
          console.log(formData, '表单数据')
          console.log(this.opinion, '流程说明')
          this.form.validateFields((err, values) => {
            if (!err) {
              formData.procDefId = this.processData.id
              formData.procDeTitle = this.processData.name
              formData.title = this.processData.description
              formData.planType=this.planType;
              if (!formData.tableName) formData.tableName = this.processData.businessTable
              var url = this.url.add
              let method = 'post'
              if (!this.isNew) {
                url = this.url.edit
                method = 'put'
              }
              console.log(formData, '格式化的数据')
              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;
                })
              }
            }
          })
        })

      },
      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;

  }
</style>