<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">
          <el-form-item
            label="采购需求"
            prop="requirementCode"
            style="margin-bottom: 22px"
          >
            <el-input
              @click.native="handParent"
              v-model="form.requirementCode"
              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="sourceType"
            style="margin-bottom: 22px"
          >
            <DictSelection
              dictName="需求来源类型"
              clearable
              v-model="form.sourceType"
              :disabled="!!form.requirementCode"
              :listFormatte="listFormatte"
             
            >
            <!--  v-if="form.sourceType != 1" -->
            </DictSelection>
            <!-- <el-input
              v-if="form.sourceType == 1"
              v-model="form.sourceTypeName"
              disabled
            ></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-select
              v-model="form.acceptUnpack"
              clearable
              style="width: 100%"
              :disabled="!!form.requirementCode"
            >
              <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" style="margin-bottom: 22px">
            <el-input
              type="textarea"
              resize="none"
              v-model="form.useTo"
              :disabled="!!form.requirementCode"
              :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-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">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>

    <headerTitle title="计划清单" style="margin-top: 15px"></headerTitle>
    <inventoryTable
      ref="inventoryTable"
      :delDetailIds="delDetailIds"
    ></inventoryTable>

    <purchaseNeedList
      ref="purchaseNeedList"
      @changeParent="changeParent"
    ></purchaseNeedList>
    <staffSelection
      ref="staffSelection"
      @confirm="confirmStaffSelection"
    ></staffSelection>
  </ele-modal>
</template>

<script>
  import inventoryTable from '@/views/purchasingManage/purchaseNeedManage/components/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 } from '@/api/purchasingManage/purchaseNeedManage';
  import {
    getplanDetail,
    UpdateInformation,
    addPurchaseplanManage
  } from '@/api/purchasingManage/purchasePlanManage';

  import headList from '@/views/saleManage/businessOpportunity/components/headList.vue';
  import { copyObj } from '@/utils/util';
  import { listOrganizations } from '@/api/system/organization';
  import { getFile } from '@/api/system/file';

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

      return {
        visible: false,
        title: '',
        detailList: [],
        delDetailIds: [],
        formDef,
        form: copyObj(formDef),
        selectList: [],
        acceptUnpackList: [
          {
            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: 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' }
          ]
        },

        // 提交状态
        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.$nextTick(() => {
            this.form = data;
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
            // 根据部门获取人员
            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.title = type === 'add' ? '新增' : '修改';
        this.row = row;
        this.visible = true;
        if (type == 'add') {
          this.isUpdate = false;
          if (row.id) {
            this.getDetailData(row.id);
          }
        } else {
          this.isUpdate = true;
        }
        this.init(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);
              }
            });
          })
        ]);
      },
      //选择产品
      handParent() {
        this.$refs.purchaseNeedList.open(this.form.requirementCode);
      },
      changeParent(data) {
        this.getDetailData(data.id);
      },
      async save() {
        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.getDictValue(
            '需求来源类型',
            this.form.sourceType
          );

          this.form.files = this.form.files || [];
          let commitData = Object.assign({}, this.form, {
            detailList: this.$refs.inventoryTable.getTableValue()
          });
          if (this.isUpdate) {
            UpdateInformation(commitData)
              .then((res) => {
                this.loading = false;
                this.$message.success('修改成功');
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          } else {
            addPurchaseplanManage(commitData)
              .then((res) => {
                this.loading = false;
                this.$message.success('新增成功');
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          }
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      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;
        });
      },
      async init(id) {
        await this.getGroupAll();
        if (id) await this.getplanData(id);
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }
</style>
