<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" aria-readonly="true">
              <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">
            <a-form-item label="关联预算流程" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input v-decorator="['processUdgetPlanId']" placeholder="请输入关联预算流程" ></a-input>-->
              <h-plan v-decorator="['processUdgetPlanId']" :trigger-change="true"
                      code="demo" field="name"  orgFields="name" @mounted="getPlanList" @PlanIds="getPlanIds" @callType="getcallType"
                      destFields="name"  />
              <!--              <j-popup-->
              <!--                v-decorator="['one']"-->
              <!--                :trigger-change="true"-->
              <!--                code="user_msg"-->
              <!--                org-fields="username,realname"-->
              <!--                dest-fields="one,two"-->
              <!--                @callback="popupCallback"/>-->
            </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']" :trigger-change="true"
                                 dictCode="material_type"
                                 placeholder="物资类型" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-show="this.isTargetLibrary">
            <a-form-item label="入库目标库" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-item v-decorator="['targetLibrary',validatorRules.targetLibrary]"  />
              <!--              <a-radio v-for="item in puwwOptions" :key="item.id" :label="item.invisibleCode" :value="item.id"></a-radio>-->
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="入库总批次" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['warehousingBatch',validatorRules.warehousingBatch]" placeholder="请输入入库总批次"
                              style="width: 100%" />
            </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">
      <a-tab-pane tab="物资入库流程清单表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          ref="processMaterialWarehousingList"
          :loading="processMaterialWarehousingListTable.loading"
          :columns="processMaterialWarehousingListTable.columns"
          :dataSource="processMaterialWarehousingListTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          @valueChange ="onSelect"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="false" />
      </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 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 JSelectCompany from '../../../components/jeecgbiz/JSelectCompany'
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 JSelectItem from '@/components/jeecgbiz/JSelectItem'

  export default {
    name: 'ProcessMaterialWarehousingForm',
    mixins: [JEditableTableMixin],
    components: {
      JFormContainer,
      JDate,
      JUpload,
      JSelectDepart,
      JSelectUserByDep,
      JSelectCompany,
      JSelectItem
    },
    data() {
      return {
        invisibleCode:null,
        puwwOptions: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        selectedMainId:'',
        processUdgetPlanId:'',
        processUdgetPlanIds:'',
        isTargetLibrary: false,
        refKeys: ['processMaterialWarehousingList', ],
        tableKeys:['processMaterialWarehousingList', ],
        activeKey: 'processMaterialWarehousingList',
        // 物资入库流程清单表
        processMaterialWarehousingListTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料组',
              key: 'materialGroup',
              type: FormTypes.sel_search,
              disabled: true,
              width:"200px",
              placeholder: '请输入${title}',
              options:[]
            },
            {
              title: '物料号',
              key: 'materialNumber',
              type: FormTypes.sel_search,
              disabled: true,
              width:"200px",
              placeholder: '请输入${title}',
              options:[]
            },
            {
              title: 'WBS',
              key: 'wbs',
              type: FormTypes.input,
              dictCode:"",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料名称及规格型号',
              key: 'materialName',
              type: FormTypes.sel_search,
              disabled: true,
              dictCode:"",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'materialUnit',
              type: FormTypes.select,
              disabled: true,
              dictCode:"",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单价（元）',
              key: 'materialPrice',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '数量',
              key: 'materialQuantity',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '金额（元）',
              key: 'materialAmount',
              type: FormTypes.inputNumber,
              disabled: true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '供应商',
              key: 'supplierId',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '批次',
              key: 'supplierBatch',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '生产日期',
              key: 'productionTime',
              type: FormTypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '保质期(年）',
              key: 'expirationDate',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },

            {
              title: '计划详情id',
              key: 'processUdgetPlanMaterialId',
              type: FormTypes.input,
              width:"0px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          queryByIdDescription: "/description/processDescription/queryById",
          queryByIdMerchandiseNews: "/merchandisenews/processMerchandiseNews/queryById",
          getForm:'/actBusiness/getForm',
          add: "/hy/processMaterialWarehousing/add",
          edit: "/hy/processMaterialWarehousing/edit",
          addWarehousingApply: "/hy/processMaterialWarehousing/addWarehousingApply",
          editWarehousingApply: "/hy/processMaterialWarehousing/editWarehousingApply",
          queryById: "/hy/processMaterialWarehousing/queryById",
          list: "/hy/processUdgetPlan/queryProcessUdgetPlanMaterialByMainIds",
          puwwlist: "/unitwaste/processUnitWasteWarehouseCode/queryById",
          getFirstNode:'/actProcessIns/getFirstNode',
          processMaterialWarehousingList: {
            list: '/hy/processMaterialWarehousing/queryProcessMaterialWarehousingListByMainId'
          },
        },
        btndisabled: false,
        describes:'',
        assignees:'',
        validatorRules: {
          // 'blur'是鼠标失去焦点的时候会触发验证
          processUdgetPlanId: {rules: [{ required: true, message: '关联预算流程不能为空!' }]},
          targetLibrary: {rules:[{ required: this.isTargetLibrary, message: '入库目标库不能为空!' }]},
          warehousingBatch: {rules:[ { required: true, message: '入库总批次不能为空!'}]}
        },
      }
    },

  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
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()

    let company = sessionStorage.getItem('PARENT_ID')
    let puwwcid = sessionStorage.getItem('PUWWC_Id')
    let userInfo = sessionStorage.getItem('USER_INFORMATION')
    console.log(userInfo)
    // userInfo.company=company;
    if (!this.isNew) {
      this.init()
    }else {
      this.popupCallback(company, userInfo, puwwcid)
    }
  },
  watch:{
    'processMaterialWarehousingListTable.dataSource': { // 对对象的某一个属性进行深度监听
       handler(nv) {
        // console.log(nv)
         if(nv.length>0){
           this.echoStorage(nv);
         }
      },
      immediate: true,
      deep: true
    }
    },
  methods: {
    //tab 值改变触发事件
    onSelect(record){
      // console.log(record.row);
      if(record.row.materialPrice !== '' && record.row.materialQuantity !== ''){
        if(record.row.id !== undefined){
          let values = [
            {
              rowKey: record.row.id,
              values: {
                'materialAmount': record.row.materialPrice * record.row.materialQuantity,
              },
            },
          ]
          // console.log(values);
          this.$refs.processMaterialWarehousingList.setValues(values);
        }
      }



    },
    /*回显数据*/
    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) {
          if (res.result.materialType==1){
            this.isTargetLibrary=true;
          }
          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')
    },
    /*通过审批*/
    passTask() {
      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)
        for (let i = 0; i < formData.processMaterialWarehousingListList.length; i++) {
          if (i==0){
            this.describes=formData.processMaterialWarehousingListList[i].materialName
          }else {
            this.describes=this.describes+"---"+formData.processMaterialWarehousingListList[i].materialName
          }
        }
        formData.describes=this.describes;
        if (formData.materialType==1){
          if (!formData.targetLibrary){
            this.$message.error("请选择入库目标库");
            return;
          }
        }
        console.log('格式化后的数据', formData)
        this.form.validateFields((err, values) => {
          if (!err) {
            formData.procDefId = this.processData.id
            formData.procDeTitle = this.processData.name
            formData.title = this.processData.description
            formData.processUdgetPlanId=this.processUdgetPlanIds
            if (!formData.tableName) formData.tableName = this.processData.businessTable
            var url = this.url.addWarehousingApply
            let method = 'post'
            if (!this.isNew) {
              url = this.url.editWarehousingApply
              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;
            }
            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)
        if (formData.materialType==1){
          if (!formData.targetLibrary){
            this.$message.error("请选择入库目标库");
            return;
          }
        }
        formData.fileId = getStringArry(formData.fileId)
        for (let i = 0; i < formData.processMaterialWarehousingListList.length; i++) {
          if (i==0){
            this.describes=formData.processMaterialWarehousingListList[i].materialName
          }else {
            this.describes=this.describes+"---"+formData.processMaterialWarehousingListList[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.processUdgetPlanId=this.processUdgetPlanIds
            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)
            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.processMaterialWarehousingListTable.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', 'company', 'createTime', 'departId', 'createBy', 'processUdgetPlanId', 'materialType', 'targetLibrary', 'warehousingBatch', 'fileId','opinion')
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.data.id) {
        let params = { id: this.data.id }
        this.requestSubTableData(this.url.processMaterialWarehousingList.list, params, this.processMaterialWarehousingListTable)
      }
    },
    /** 查询某个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
          }
        }
        tab.dataSource = dataSource
        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        // tab.loading = false
      })
    },

    async echoStorage(nv){
      this.processMaterialWarehousingListTable.loading = true;
      for (const item of nv) {
        let par = { id : item.materialGroup,}
        let param = {id : item.materialNumber,}
        await getAction(this.url.queryByIdDescription,par).then( res=>{
          // console.log(res);
          if(res.success){
            this.processMaterialWarehousingListTable.columns[0].options= [{
              title : res.result.materialClassify,
              value :  item.materialGroup,
              disabled : true }];
          }
        })
        await getAction(this.url.queryByIdMerchandiseNews,param).then( res=>{
          // console.log(res);
          if(res.success){
            this.processMaterialWarehousingListTable.columns[1].options= [{
              title : res.result.materialsNumber,
              value :  item.materialNumber,
              disabled : true }];
          }
        })

      }
      this.processMaterialWarehousingListTable.loading = false;
    },

    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        processMaterialWarehousingListList: 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)
          }
        })
      }
    },
    getPlanIds(val){
      let ids=[]
      if (!!val){
        for (let i = 0; i < val.length; i++) {
          ids.push(val[i].id);
        }
      }
      this.processUdgetPlanIds=ids.join(",");
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    async getPlanList (val) {

      if (val.length>0){
        if (val[0].materialType==1){
          this.isTargetLibrary=true;
        }else {
          this.isTargetLibrary=false;
        }
      }
      let ids=[]
      if (!!val){
        for (let i = 0; i < val.length; i++) {
          ids.push(val[i].id);
        }
      }
      this.processUdgetPlanIds=ids.join(",");
      let params = {}
      params.ids = JSON.stringify(ids)
     await this.requestSubTableDatas(this.url.list, params, this.processMaterialWarehousingListTable)
      // getAction(this.url.list,params).then((res)=>{
      //   if(res.success){
      //     console.log('将要回填的数据',res.result)
      //   }
      // })
    },
    /** 查询某个tab的数据 */
    requestSubTableDatas(url, params, tab, success) {
      // tab.loading = true;
      if(this.disabled && !this.task ){
        console.log("执行了不重新查",tab.dataSource);


      }else{
        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",tab.dataSource)
          dataSource.forEach(item =>{
            let par = { id : item.materialGroup,}
            let param = {id : item.materialNumber,}
            getAction(this.url.queryByIdDescription,par).then( res=>{
              // console.log(res);
              if(res.success){
                this.processMaterialWarehousingListTable.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.processMaterialWarehousingListTable.columns[1].options= [{
                  title : res.result.materialsNumber,
                  value :  item.materialNumber,
                  disabled : true }];
              }
            })

          })
          tab.dataSource = dataSource;
          // console.log("tab.dataSource",tab.dataSource)
          typeof success === 'function' ? success(res) : ''
        }).finally(() => {
          tab.loading = false
        })

      }
      },
    getcallType(type) {
      this.data.materialType = type.materialType
      let fieldval = pick(this.data, 'materialType')
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
    },
    popupCallback(company, row, puwwcid) {
      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)
      })
    },
    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>