<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="60%"
    @close="cancel"
    :maxable="true"
    :resizable="true"
  >

    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="需求类型"
            prop="sourceType"
            style="margin-bottom: 22px"
          >

          <el-select
              v-model="form.sourceType"
              placeholder="请选择"
              style="width: 100%"
              clearable
              :disabled="!!form.requirementCode"
            >
              <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"
            style="margin-bottom: 22px"
          >
            <el-input
              @click.native="handParent"
              v-model="form.requirementName"
              placeholder="请选择"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="计划单名称"
            prop="planName"
            style="margin-bottom: 22px"
          >
            <el-input v-model="form.planName" placeholder="请选择"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="责任人"
            prop="responsibleName"
            style="margin-bottom: 22px"
          >
            <el-input
              @click.native="openStaffSelection"
              v-model="form.responsibleName"
              placeholder="请选择"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="需求部门"
            prop="requireDeptId"
            style="margin-bottom: 22px"
          >
            <ele-tree-select
              :disabled="!!form.requirementCode"
              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"
            style="margin-bottom: 22px"
          >
            <personSelect
              :disabled="!!form.requirementCode"
              ref="directorRef"
              v-model="form.requireUserId"
              @selfChange="salesmanChange"
              :init="false"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="remark" label="是否接受拆单" label-width="120px">
            <el-radio-group
              v-model="form.acceptUnpack"
              :disabled="!!form.requirementCode"
            >
              <el-radio v-for="item in acceptUnpackList" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="remark" label="是否需要核价" label-width="120px">
            <el-radio-group v-model="form.needInquiry">
              <el-radio v-for="item in needInquiryList" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      

        <el-col :span="12">
          <el-form-item prop="files" label="附件">
            <fileMain v-model="form.files"></fileMain>
          
          </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-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="计划清单" style="margin-top: 15px"></headerTitle>
    <el-tabs v-model="activeName" style="margin-top: 15px" type="border-card">
      <el-tab-pane label="物品清单" name="1">
        <inventoryTable
          :needInquiry="form.needInquiry"
          ref="inventoryTable"
        ></inventoryTable>
      </el-tab-pane>
      <el-tab-pane
        label="带料清单"
        name="2"
        v-if="orderSourceType.includes(form.sourceType)"
      >
        <inventoryTable
          :needInquiry="form.needInquiry"
          ref="rawDetailListRef"
          :detailType="1"
        ></inventoryTable>
      </el-tab-pane>
      <el-tab-pane
        label="产出清单"
        name="3"
        v-if="orderSourceType.includes(form.sourceType)"
      >
        <inventoryTable
          :needInquiry="form.needInquiry"
          ref="outputDetailListRef"
          :detailType="2"
        ></inventoryTable>
      </el-tab-pane>
    </el-tabs>

    <purchaseNeedList
      generatedType="plan"
      ref="purchaseNeedList"
      @changeParent="changeParent"
    ></purchaseNeedList>
    <staffSelection
      ref="staffSelection"
      @confirm="confirmStaffSelection"
    ></staffSelection>
    <process-submit-dialog
      api-fun-name="purchaseplanStatusAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </ele-modal>
</template>

<script>
  import inventoryTable from './inventoryTable.vue';
  import purchaseNeedList from './purchaseNeed-list.vue';
  import staffSelection from './staffSelection.vue';

  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import personSelect from '@/components/CommomSelect/person-select.vue';

  import {
    getDetail,
    isHasGeneratedPlanAPI
  } from '@/api/purchasingManage/purchaseNeedManage';
  import {
    getplanDetail,
    UpdateInformation,
    addPurchaseplanManage,
    saveAndSubmitPurchasePlanAPI
  } from '@/api/purchasingManage/purchasePlanManage';
  import { getCode } from '@/api/login/index.js';
  import headList from '@/BIZComponents/user-select/user-select.vue';
  import { copyObj } from '@/utils/util';
  import { listOrganizations } from '@/api/system/organization';
  import { getFile } from '@/api/system/file';
  // import fileMain from '@/components/addDoc/index.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import { orderSourceType,requirementSourceType } from '@/enum/dict';

  export default {
    props: {
      categoryTreeList: Array,
      saleOrderData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },

    mixins: [dictMixins],
    components: {
      processSubmitDialog,
      // fileMain,
      fileUpload,
      headList,
      inventoryTable,
      purchaseNeedList,
      personSelect,
      staffSelection,
    },
    data() {
      let formDef = {
        id: '',
        expectReceiveDate: null,
        remark: null,
        requireDeptId: '',
        requireUserId: '',
        sourceCode: '',
        sourceId: '',
        sourceType: '',
        files: [],
        planName: '',
        responsibleName: '',
        responsibleId: '',
        requirementId: '',
        requirementName: '',
        sourceTypeName: '',
        acceptUnpack: 1,
        needInquiry: 1,
        isFirstProcess: 0
      };

      return {
        orderSourceType,
        requirementSourceType,
        activeName: '1',
        fullscreen: false,
        visible: false,
        processSubmitDialogFlag: false,
        title: '',
        detailList: [],
        delDetailIds: [],
        formDef,
        form: copyObj(formDef),
        selectList: [],
        acceptUnpackList: [
          {
            label: '接受',
            value: 1
          },
          {
            label: '不接受',
            value: 0
          }
        ],
        needInquiryList: [
          {
            label: '是',
            value: 1
          },
          {
            label: '否',
            value: 0
          }
        ],
        processList: [
          {
            label: '是',
            value: 1
          },
          {
            label: '否',
            value: 0
          }
        ],
        columns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            width: 150,
            prop: 'productCategoryName',
            label: '分类',
            slot: 'productCategoryName'
          },
          {
            width: 140,
            prop: 'productCode',
            label: '编码',
            slot: 'productCode'
          },
          {
            width: 240,
            prop: 'productName',
            label: '名称',
            slot: 'productName'
          },
          {
            width: 150,
            prop: 'productBrand',
            label: '牌号',
            slot: 'productBrand'
          },

          {
            width: 80,
            prop: 'totalCount',
            label: '数量',
            slot: 'totalCount'
          },
          {
            width: 100,
            prop: 'measuringUnit',
            label: '单位',
            slot: 'measuringUnit'
          },
          {
            width: 130,
            prop: 'modelType',
            label: '型号',
            slot: 'modelType'
          },

          {
            width: 120,
            prop: 'specification',
            label: '规格',
            slot: 'specification'
          },
          {
            width: 130,
            prop: 'brand',
            label: '品牌',
            slot: 'brand'
          },
          {
            width: 130,
            prop: 'supplierName',
            label: '供应商',
            slot: 'supplierName',
            headerSlot: 'headerSupplierName'
          },
          {
            width: 170,
            prop: 'expectReceiveDate',
            label: '到货日期',
            slot: 'expectReceiveDate'
          },
          {
            width: 140,
            prop: 'files',
            label: '附件',
            slot: 'files'
          },
          {
            width: 220,
            prop: 'remark',
            label: '备注',
            slot: 'remark'
          }
        ],
        rules: {
          responsibleName: [
            { required: true, message: '请选择责任人', trigger: 'change' }
          ],
          requireDeptId: [
            { required: true, message: '请选择需求部门', trigger: 'change' }
          ],
          requireUserId: [
            { required: true, message: '请选择需求人', trigger: 'change' }
          ],
          expectReceiveDate: [
            { required: true, message: '请选择到货日期', trigger: 'change' }
          ],
          sourceId: [
            { required: true, message: '请选择来源类型', trigger: 'change' }
          ],
          sourceType: [
            { required: true, message: '请选择订单类型', trigger: 'change' }
          ],
          planName: [
            { required: true, message: '请输入计划单名称', trigger: 'blur' }
          ]
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,

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

    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);
        this.form.requireDeptName = info.name;
        this.form.requireUserId = '';
        this.form.requireUserName = '';
        // 根据部门获取人员
        this.$nextTick(() => {});
        this.getrequireUser(id);
      },

      getrequireUser(groupId) {
        if (groupId) {
          this.$refs.directorRef.getList({ groupId });
        }
      },
      salesmanChange(val, info) {
        this.form.requireUserName = info.name;
      },
      openStaffSelection() {
        this.$refs.staffSelection.open(
          this.form.responsibleName
            ? [{ name: this.form.responsibleName, id: this.form.responsibleId }]
            : []
        );
      },
      confirmStaffSelection(data) {
        this.form.responsibleName = (data && data[0].name) || '';
        this.form.responsibleId = (data && data[0].id) || '';
      },

      //获取计划详情
      async getplanData(id) {
        this.loading = true;
        let data = await getplanDetail(id);
        this.loading = false;
        if (data) {
          this.form = data;

          this.$nextTick(() => {
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
            this.$refs.rawDetailListRef &&
              this.$refs.rawDetailListRef.putTableValue(data.rawDetailList); //原料
            this.$refs.outputDetailListRef &&
              this.$refs.outputDetailListRef.putTableValue(
                data.outputDetailList
              ); //产成品
            // 根据部门获取人员
            this.getrequireUser(this.form.requireDeptId);
          });
        }
      },
      //获取需求详情
      async getDetailData(id, type = '') {
        this.loading = true;
        let data = await getDetail(id);
        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            for (let key in data) {
              if (key != 'id') {
                this.form[key] = data[key];
              } else {
                this.form.requirementId = data[key];
              }
            }

            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
            // 根据部门获取人员
            this.getrequireUser(this.form.requireDeptId);
          });
        }
      },

      async open(type, row, contactCategoryId) {
        this.activeName = '1';
        this.title = type === 'add' ? '新增' : '修改';
        this.row = row;
        this.visible = true;
        if (type == 'add') {
          this.isUpdate = false;
          if (row.id) {
            let res = await isHasGeneratedPlanAPI(row.id);
            if (res) this.$message.warning('该需求已经生成过计划，请注意');
            await this.getDetailData(row.id);
            
          }
          this.$set(this.form,'planName',await getCode('purchase_plan_code_name'))
        } else {
          this.isUpdate = true;
          await this.init(row.id);
        }
        await this.getGroupAll();
      },

      getValidate() {
        let promiseAll = [
          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);
                this.activeName = '1';
              } else {
                resolve(true);
              }
            });
          })
        ];
        if (
          this.$refs.rawDetailListRef &&
          this.$refs.rawDetailListRef.validateForm
        ) {
          promiseAll.push(
            new Promise((resolve, reject) => {
              this.$refs.rawDetailListRef.validateForm((valid) => {
                if (!valid) {
                  reject(false);
                  this.activeName = '2';
                } else {
                  resolve(true);
                }
              });
            })
          );
        }
        if (
          this.$refs.outputDetailListRef &&
          this.$refs.outputDetailListRef.validateForm
        ) {
          promiseAll.push(
            new Promise((resolve, reject) => {
              this.$refs.outputDetailListRef.validateForm((valid) => {
                if (!valid) {
                  reject(false);
                  this.activeName = '3';
                } else {
                  resolve(true);
                }
              });
            })
          );
        }
        return Promise.all(promiseAll);
      },
      //选择产品
      handParent() {
        this.$refs.purchaseNeedList.open(this.form.requirementCode);
      },
      changeParent(data) {
        this.getDetailData(data.id);
      },
      async save(type = '') {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

          if (this.$refs.inventoryTable.getTableValue().length == 0) {
            this.$message.warning('物品清单不能为空');
            return;
          }
          if (!this.isUpdate) {
            delete this.form.id;
          }
          this.form.sourceTypeName = this.requirementSourceType.find(
            (val) => val.value == this.form.sourceType
          )?.label;
          this.form.files = this.form.files || [];
          const rawDetailList =
            (this.$refs.rawDetailListRef &&
              this.$refs.rawDetailListRef.getTableValue()) ||
            [];
          const outputDetailList =
            (this.$refs.outputDetailListRef &&
              this.$refs.outputDetailListRef.getTableValue()) ||
            [];

          const detailList = [
            ...this.$refs.inventoryTable.getTableValue(),
            ...rawDetailList,
            ...outputDetailList
          ];
          this.form.detailList = detailList;

          // let API = type == 'sub' ? saveAndSubmitPurchasePlanAPI : this.isUpdate ? UpdateInformation : addPurchaseplanManage;
          let API = this.isUpdate ? UpdateInformation : addPurchaseplanManage;
          API(this.form)
            .then((res) => {
              this.loading = false;
              this.$message.success('修改成功');
              if (type == 'sub') {
                this.submit(res);
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      async submit(res) {
        console.log(res);
        let data = await getplanDetail(this.form.id || res);
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: 'purchase_plan_approve',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.planCode,
              businessName: data.planName,
              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);
        });
      },
      reload() {
        this.cancel();
        this.$emit('done');
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      cancel() {
        this.$nextTick(() => {
          // 关闭后，销毁所有的表单数据
          this.$refs['otherForm'] && this.$refs['otherForm'].resetFields();
          this.$refs['formRef'] && this.$refs['formRef'].resetFields();
          this.form = copyObj(this.formDef);

          this.visible = false;
        });
      },
      async init(id) {
        if (id) await this.getplanData(id);
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }
</style>
