<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="60%"
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row>
        <el-col :span="12" style="height: 58px">
          <el-form-item label="需求来源类型" prop="sourceType">
            <DictSelection
              dictName="需求来源类型"
              clearable
              v-model="form.sourceType"
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="需求部门"
            prop="requireDeptId"
            style="margin-bottom: 22px"
          >
            <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"
            style="margin-bottom: 22px"
          >
            <personSelect
              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-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="附件">
            <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">保存</el-button>
      <el-button type="primary" @click="save('sub')">提交</el-button>

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

    <headerTitle title="需求清单"></headerTitle>
    <inventoryTable
      ref="inventoryTable"
      :delDetailIds="delDetailIds"
    ></inventoryTable>
  </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 '@/views/saleManage/businessOpportunity/components/headList.vue';
  import { copyObj } from '@/utils/util';
  import { listOrganizations } from '@/api/system/organization';

  export default {
    props: {
      categoryTreeList: Array
    },
    mixins: [dictMixins],
    components: {
      fileUpload,
      headList,
      inventoryTable,
      deptSelect,
      parentList,
      personSelect
    },
    data() {
      let formDef = {
        id: '',
        receiveDate: null,
        remark: null,
        requireDeptId: '',
        requireUserId: '',
        sourceCode: '',
        sourceId: '',
        sourceType: '',
        files: [],
        acceptUnpack: 1
      };

      return {
        visible: false,
        title: '',
        delDetailIds: [],
        formDef,
        form: copyObj(formDef),
        acceptUnpackList: [
          {
            label: '接受',
            value: 1
          },
          {
            label: '不接受',
            value: 0
          }
        ],
        rules: {
          requireDeptId: [
            { required: true, message: '请选择需求部门', trigger: 'change' }
          ],
          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: {
      // 获取公司数据
      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);
      },
      // //选择需求来源类型
      // 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);
            // }
            // 根据部门获取人员

            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;
        } else {
          this.isUpdate = true;
          this.getDetailData(row.id);
        }
      },
      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;
          if (!this.isUpdate) {
            delete this.form.id;
          }

          if (this.$refs.inventoryTable.getTableValue().length == 0) {
            this.$message.warning('需求清单不能为空');
            return;
          }
          this.form.files = this.form.files || [];

          this.form.sourceName = this.getDictValue('需求来源类型', this.form.sourceType);
          let commitData = Object.assign({}, this.form, {
            detailList: this.$refs.inventoryTable.getTableValue()
          });
          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);
          // 表单验证未通过，不执行保存操作
        }
      },
      saleOrderSubmit(res) {
        submit({
          businessId: res.id
          // productionSupervisorId
        }).then((res) => {
          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>
