<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    :title="title"
    :close-on-click-modal="false"
    width="80%"
    :maxable="true"
    :resizable="true"
    @close="cancel"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="el-form-box"
      label-width="120px"
    >
      <headerTitle title="基本信息"></headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item label="需求类型" prop="sourceType">
            <el-select
              v-model="form.sourceType"
              placeholder="请选择"
              style="width: 100%"
              clearable
              @change="handleSourceType"
            >
              <el-option
                v-for="item in requirementSourceType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
   
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="需求单名称" prop="requirementName">
            <el-input
              v-model="form.requirementName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="需求部门" prop="requireDeptId">
            <ele-tree-select
              clearable
              :data="groupTreeData"
              v-model="form.requireDeptId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="change_principalDep"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="需求人" prop="requireUserId">
            <personSelect
              ref="directorRef"
              v-model="form.requireUserId"
              @selfChange="salesmanChange"
              :init="false"
            />
          </el-form-item>
        </el-col>

        <!-- v-if="form.sourceType==1"-->
        <el-col v-if="form.sourceType == 1" :span="12">
          <el-form-item label="销售合同">
            <el-input
              clearable
              v-model="form.saleContractName"
              @click.native="handleContractBtn"
              @clear="clearContrcat"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.sourceType == 1" :span="12">
          <el-form-item label="销售订单">
            <el-input
              clearable
              v-model="form.saleOrderNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
              @clear="clearSaleOrder"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="remark" label="是否接受拆单" label-width="120px">
            <el-select
              v-model="form.acceptUnpack"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in acceptUnpackList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用途" prop="useTo">
            <el-input
              type="textarea"
              resize="none"
              v-model="form.useTo"
              :rows="2"
              placeholder="请输入"
              size="small"
              maxlength="200"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="remark" label="备注">
            <el-input
              type="textarea"
              resize="none"
              v-model="form.remark"
              :rows="2"
              placeholder="请输入"
              size="small"
              maxlength="200"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="files" label="附件">
            <fileMain v-model="form.fileId"></fileMain>
            <!-- <fileUpload
              v-model="form.files"
              module="main"
              :showLib="false"
              :limit="1"
            /> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save" v-click-once>保存</el-button>
      <el-button type="primary" @click="save('sub')" v-click-once
        >提交</el-button
      >

      <el-button @click="cancel">返回</el-button>
    </div>

    <headerTitle title="需求清单"></headerTitle>
    <inventoryTable
      ref="inventoryTable"
      :delDetailIds="delDetailIds"
    ></inventoryTable>
    <contractListDialog
      ref="selectContractRef"
      @changeParent="changeContract"
      :hasGeneratedOrder="''"
      :isAdd="true"
    ></contractListDialog>
    <orderListDialog
      ref="orderListDialogRef"
      @changeParent="changeOrder"
    ></orderListDialog>
    <process-submit-dialog
      api-fun-name="purchaserequirementStatusAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </ele-modal>
</template>

<script>
  import inventoryTable from './inventoryTable.vue';

  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import parentList from '@/views/saleManage/contact/components/parentList.vue';

  import {
    addPurchaseNeedManage,
    getDetail,
    UpdateInformation,
    submit
  } from '@/api/purchasingManage/purchaseNeedManage';

  import headList from '@/BIZComponents/user-select/user-select.vue';
  import { copyObj } from '@/utils/util';
  import { listOrganizations } from '@/api/system/organization';
  import contractListDialog from '@/views/saleManage/saleOrder/components/contractListDialog.vue';
  import orderListDialog from '@/views/saleManage/saleOrder/invoice/components/orderListDialog.vue';
  import { getTableList as getSaleOrderListAPI } from '@/api/saleManage/saleorder';
  import fileMain from '@/components/addDoc/index';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import { getSaleOrderDetail } from '@/api/saleManage/saleorder';
  import { requirementSourceType } from '@/enum/dict.js';

  export default {
    props: {
      categoryTreeList: Array
    },
    mixins: [dictMixins],
    components: {
      processSubmitDialog,
      orderListDialog,
      contractListDialog,
      fileUpload,
      headList,
      inventoryTable,
      deptSelect,
      parentList,
      personSelect,
      fileMain,
    },
    data() {
      let formDef = {
        id: '',
        receiveDate: null,
        remark: null,
        requireDeptId: '',
        requireDeptName: '',
        requireUserId: '',
        requireUserName: '',
        sourceCode: '',
        sourceId: '',
        sourceType: '',
        requirementName: '',
        saleContractName: '',
        saleContractNo: '',
        saleContractId: '',
        saleOrderId: '',
        saleOrderNo: '',
        files: [],
        acceptUnpack: 1,
        fileId: [] //附件集合
      };

      return {
        clearing: false, //是否清除合同
        visible: false,
        processSubmitDialogFlag: false,
        fullscreen: false,
        title: '',
        requirementSourceType,
        delDetailIds: [],
        formDef,
        form: copyObj(formDef),
        acceptUnpackList: [
          {
            label: '接受',
            value: 1
          },
          {
            label: '不接受',
            value: 0
          }
        ],
        rules: {
          requireDeptId: [
            { required: true, message: '请选择需求部门', trigger: 'change' }
          ],
          requirementName: [
            { required: true, message: '请输入需求单名称', trigger: 'blur' }
          ],
          requireUserId: [
            { required: true, message: '请选择需求人', trigger: 'change' }
          ],
          useTo: [{ required: true, message: '请输入用途', trigger: 'change' }],
          sourceType: [
            { required: true, message: '请选择订单类型', trigger: 'change' }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,

        // 组织机构树形结构数据
        groupTreeData: [],
        // 组织机构平铺数据
        groupData: [],
        businessId: ''
      };
    },
    created() {
      this.getGroupAll();
    },

    methods: {
      listFormatte(data) {
        return data;
        // return data.filter((item) => item.dictCode != 1);
      },
      // 获取公司数据
      getGroupAll() {
        listOrganizations().then((list) => {
          this.groupData = list;
          this.groupTreeData = this.$util.toTreeData({
            data: list,
            idField: 'id',
            parentIdField: 'parentId'
          });
        });
      },

      // 选择负责人部门
      change_principalDep(id) {
        const info = this.groupData.find((e) => e.id == id);
        console.log(info);
        this.form.requireDeptName = info.name;
        this.form.requireUserId = '';
        this.form.requireUserName = '';
        // 根据部门获取人员
        this.$nextTick(() => {});
        this.getrequireUser(id);
      },
      // //选择需求类型
      // chaengSource(data) {
      //   this.form.sourceType = data?.dictValue;
      // },
      getrequireUser(groupId) {
        if (groupId) {
          this.$refs.directorRef.getList({ groupId });
        }
      },
      salesmanChange(val, info) {
        this.form.requireUserName = info.name;
      },
      //获取详情
      async getDetailData(id) {
        this.businessId = id;

        this.loading = true;
        const data = await getDetail(id);
        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            this.form = data;
            // if (data.files !== '') {
            //   this.$set(this.form, 'files', data?.files);
            // }
            // 根据部门获取人员
            if (this.form.fileId) {
              this.form.fileId = JSON.parse(this.form.fileId);
            }
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
            this.getrequireUser(this.form.requireDeptId);
          });
        }
      },

      async open(type, row, contactCategoryId) {
        this.title = type === 'add' ? '新增' : '修改';
        this.row = row;
        this.visible = true;
        if (type == 'add') {
          this.isUpdate = false;
          this.$nextTick(() => {
            this.form.requireDeptId = this.$store.getters.user.info.groupId;
            this.form.requireUserId = this.$store.getters.user.info.userId;
            this.form.requireDeptName = this.$store.getters.user.info.groupName;
            this.form.requireUserName = this.$store.getters.user.info.name;
            console.log(this.$store.getters.user.info.groupName);
            this.getrequireUser(this.form.requireDeptId);
          });
        } else {
          this.isUpdate = true;
          await this.getDetailData(row.id);
        }
      },

      //选择合同弹框
      handleContractBtn() {
        if (this.clearing) return;
        let item = {
          id: this.form.saleContractId
        };
        this.$refs.selectContractRef.open(item);
      },
      //选择合同回调
      changeContract(obj) {
        this.form = Object.assign({}, this.form, {
          saleContractId: obj.id,
          saleContractName: obj.contractName,
          saleContractNo: obj.contractNo
        });
        this.getSaleOrderList(this.form.saleContractId);
      },
      /* 表格数据源 */
      async getSaleOrderList(contractId) {
        let res = await getSaleOrderListAPI({
          pageNum: 1,
          size: 10,
          contractId
        });
        this.form.saleOrderId = res.list[0]?.id;
        this.form.saleOrderNo = res.list[0]?.orderNo;
        this.getSaleOrderDetail(this.form.saleOrderId);
      },
      //清除合同
      clearContrcat() {
        this.clearing = true;
        this.form.saleContractNo = '';
        this.form.saleContractId = '';
        this.form.saleContractName = '';
        setTimeout(() => {
          this.clearing = false;
        }, 500);
      },

      handleSourceType() {
        this.form.saleOrderId = '';
        this.form.saleOrderNo = '';
        this.form.saleContractNo = '';
        this.form.saleContractId = '';
        this.form.saleContractName = '';
      },

      //选择订单弹框
      handleOrderBtn() {
        if (this.clearing) return;
        let item = {
          id: this.form.saleOrderId
        };
        this.$refs.orderListDialogRef.open(item);
      },

      //选择订单回调
      async changeOrder(obj) {
        this.form = Object.assign({}, this.form, {
          saleOrderId: obj.id,
          saleOrderNo: obj.orderNo,
          saleContractId: obj.contractId,
          saleContractName: obj.contractName,
          saleContractNo: obj.contractNo
        });
        this.getSaleOrderDetail(obj.id);
      },
      async getSaleOrderDetail(id) {
        const data = await getSaleOrderDetail(id);
        data.productList.forEach((item) => {
          item.expectReceiveDate = item.produceDeliveryDeadline;
          item.arrivalWay = 1;
        });

        this.$nextTick(() => {
          this.$refs.inventoryTable.putTableValue(data.productList);
        });
      },

      //清除订单
      clearSaleOrder() {
        this.clearing = true;
        this.form.saleOrderId = '';
        this.form.saleOrderNo = '';
        setTimeout(() => {
          this.clearing = false;
        }, 500);
      },

      getValidate() {
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          new Promise((resolve, reject) => {
            this.$refs.inventoryTable.validateForm((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ]);
      },
      async save(type) {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;
          let isArrivalBatch = false;
          let detailList = this.$refs.inventoryTable.getTableValue();
          if (!this.isUpdate) {
            delete this.form.id;
          }

          if (detailList.length == 0) {
            this.$message.warning('需求清单不能为空');
            return;
          }
          detailList.forEach((v) => {
            if (
              v.arrivalWay == 2 &&
              (!v.arrivalBatch || v.arrivalBatch.length == 0)
            ) {
              isArrivalBatch = true;
            }
          });
          if (isArrivalBatch) {
            this.$message.warning('请设置分批时间');
            return;
          }

          this.form.files = this.form.files || [];

          this.form.sourceTypeName = this.requirementSourceType.find(
            (val) => val.value == this.form.sourceType
          )?.label;
          if (this.form.fileId) {
            this.form.fileId = JSON.stringify(this.form.fileId);
          }
          let commitData = Object.assign({}, this.form, {
            detailList
          });

          if (this.isUpdate) {
            UpdateInformation(commitData)
              .then((res) => {
                this.loading = false;
                this.$message.success('修改成功');
                if (type === 'sub') {
                  this.saleOrderSubmit(res);
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          } else {
            addPurchaseNeedManage(commitData)
              .then((res) => {
                this.loading = false;
                this.$message.success('新增成功');
                if (type === 'sub') {
                  this.saleOrderSubmit(res);
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          }
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      async saleOrderSubmit(res) {
        const data = await getDetail(res);
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: 'purchase_requirement_approve_tg',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.requirementCode,
              businessName: data.requirementName,
              businessType: data.sourceTypeName
            }
            // callBackMethodType : '1',
            // callBackMethod : 'proTargetPlanApproveApiImpl.updatePlanApprovalStatus',
            // pcHandle : '/bpm/handleTask/components/project-manage/plan-manage/submit.vue',
            // pcView : '/bpm/handleTask/components/project-manage/plan-manage/detailDialog.vue',
            // miniHandle : '',
            // miniView : '',
          };

          this.$refs.processSubmitDialogRef.init(params);
        });

        // submit({
        //   businessId: this.businessId || res
        //   // productionSupervisorId
        // }).then((res) => {
        //   this.cancel();
        //   this.$emit('done');
        // });
      },
      reload() {
        this.cancel();
        this.$emit('done');
      },
      cancel() {
        this.$nextTick(() => {
          this.activeName = 'base';
          // 关闭后，销毁所有的表单数据
          this.$refs['otherForm'] && this.$refs['otherForm'].resetFields();
          this.$refs['formRef'] && this.$refs['formRef'].resetFields();
          this.form = copyObj(this.formDef);
          this.visible = false;
        });
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }
</style>
