<template>
  <div>
    <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"
          >
          <DictSelection
              dictName="需求来源类型"
              clearable
              v-model="form.sourceType"
              :listFormatte="listFormatte"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="height: 58px">
          <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"
            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" style="height: 58px">
          <el-form-item
            label="需求人"
            prop="requireUserId"
            style="margin-bottom: 0px"
          >
            <personSelect
              ref="directorRef"
              v-model="form.requireUserId"
              @selfChange="salesmanChange"
              :init="false"
            />
          </el-form-item>
        </el-col>
        <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="附件">
            <fileUpload
              v-model="form.files"
              module="main"
              :showLib="false"
              :limit="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <headerTitle title="需求清单"></headerTitle>
    <inventoryTable
      ref="inventoryTable"
      :delDetailIds="delDetailIds"
    ></inventoryTable>
    <contractListDialog
      ref="selectContractRef"
      @changeParent="changeContract"
      :hasGeneratedOrder="''"
    ></contractListDialog>
    <orderListDialog
      ref="orderListDialogRef"
      @changeParent="changeOrder"
    ></orderListDialog>
  </div>
</template>

<script>
  import inventoryTable from './inventoryTable.vue';
  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import { getDetail } from '@/api/bpm/components/purchasingManage/purchaseNeedManage';
  import { copyObj } from '@/utils/util';
  import { listOrganizations } from '@/api/system/organization';
  import ContractListDialog from "@/views/bpm/handleTask/components/saleOrder/contractListDialog.vue";
  import OrderListDialog from "@/views/bpm/handleTask/components/saleOrder/invoice/orderListDialog.vue";
  import {getTableList as getSaleOrderListAPI} from "@/api/bpm/components/saleManage/saleorder";

  export default {
    props: {
      businessId: {
        default: ''
      }
    },
    mixins: [dictMixins],
    components: {
      OrderListDialog,
      ContractListDialog,
      fileUpload,
      inventoryTable,
      personSelect
    },
    data() {
      let formDef = {
        id: '',
        receiveDate: null,
        remark: null,
        requireDeptId: '',
        requireUserId: '',
        sourceCode: '',
        requirementName: '',
        sourceId: '',
        sourceType: '',
        saleContractName: '',
        saleContractNo: '',
        saleContractId: '',
        saleOrderId: '',
        saleOrderNo: '',
        files: [],
        acceptUnpack: 1
      };

      return {
        clearing: false, //是否清除合同
        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' }
          ],
          requirementName: [
            { required: true, message: '请输入需求单名称', trigger: 'blur' }
          ],
          useTo: [{ required: true, message: '请输入用途', trigger: 'change' }],
          sourceType: [
            { required: true, message: '请选择需求类型', trigger: 'change' }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,

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

    methods: {
      listFormatte(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);
      },
      // //选择需求来源类型
      // 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.loading = true;
        const data = await getDetail(id);
        this.loading = false;
        this.getrequireUser(data.requireDeptId);

        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);
          });
        }
      },

      //选择合同弹框
      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

      },
      //清除合同
      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);
      },

      //选择订单回调
      changeOrder(obj) {
        this.form = Object.assign({}, this.form, {
          saleOrderId: obj.id,
          saleOrderNo: obj.orderNo,
          saleContractId: obj.contractId,
          saleContractName: obj.contractName,
          saleContractNo: obj.contractNo,
        })
      },
//清除订单
      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 getTableValue() {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

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

          this.form.sourceTypeName = this.getDictValue(
            '需求来源类型',
            this.form.sourceType
          );
          let commitData = Object.assign({}, this.form, {
            detailList: this.$refs.inventoryTable.getTableValue()
          });
          return commitData;
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }
</style>
