<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="planCode"
            style="margin-bottom: 22px"
          >
            <el-input
              @click.native="handParent"
              v-model="form.planName"
              placeholder="请选择"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="询价单名称"
            prop="inquiryName"
            style="margin-bottom: 22px"
          >
            <el-input
              v-model="form.inquiryName"
            ></el-input>
          </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
            >
              <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 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>
    <headerTitle title="产品清单" style="margin-top: 15px"></headerTitle>
    <inventoryTable
      ref="inventoryTable"
      @delList="delList"
      :acceptUnpack="form.acceptUnpack"
    ></inventoryTable>

    <headerTitle title="报价清单" style="margin-top: 15px"></headerTitle>
    <el-button type="primary" @click="openSupplier">新增供应商</el-button>

    <inquiryManageList
      ref="inquiryManageRef"
      @changeInquiryManageList="changeInquiryManageList"
    ></inquiryManageList>
    <supplierManageDialog
      ref="supplierManageDialogRef"
      @supplierManageChange="supplierManageChange"
    ></supplierManageDialog>
    <inquiryTable
      @removeSupplier="removeSupplier"
      @setSupplierId="setSupplierId"
      :ref="'inquiryTable' + item.supplierId"
      :radio="form.winnerId"
      v-for="item in supplierList"
      :key="item.supplierId"
      style="margin-top: 15px"
      :obj="item"
      :isUpdate="isUpdate"
    ></inquiryTable>
  </div>
</template>

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

  import inquiryManageList from './inquiryManage-list.vue';
  import supplierManageDialog from './supplierManageDialog.vue';

  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';

  import { getplanDetail } from '@/api/bpm/components/purchasingManage/purchasePlanManage';
  import {
    getpurchaseinquiry,
    chooseWinner
  } from '@/api/bpm/components/purchasingManage/inquiryManage';

  import { copyObj } from '@/utils/util';

  import { getFile } from '@/api/system/file';

  export default {
    mixins: [dictMixins],
    components: {
      fileUpload,
      inventoryTable,
      inquiryManageList,
      supplierManageDialog,
      inquiryTable
    },
    props: {
      businessId: {
        default: ''
      }
    },
    data() {
      let formDef = {
        id: '',
        planCode: null,
        planName: null,
        inquiryName: null,
        remark: null,
        planId: '',
        detailList: '',
        resultList: [],
        // supplierList: [],
        supplierName: '',
        files: [],
        acceptUnpack: ''
      };

      return {
        visible: false,
        supplierVisible: false,
        title: '',
        supplierList: [],
        detailList: [],
        list: [],
        delDetailIds: [],
        formDef,

        acceptUnpackList: [
          {
            label: '接受',
            value: 1
          },
          {
            label: '不接受',
            value: 0
          }
        ],
        form: copyObj(formDef),
        rules: {
          responsibleName: [
            { required: true, message: '请选择负责人', trigger: 'change' }
          ],
          requireDeptId: [
            { required: true, message: '请选择需求部门', trigger: 'change' }
          ],
          inquiryName: [
            { required: true, message: '请输入询价单名称', trigger: 'blur' }
          ],
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    created() {
      this.getDetailData(this.businessId, 'init');
    },

    methods: {
      openSupplier() {
        if (this.list.length == 0) {
          this.$message.warning('请先选择采购计划');
          return;
        }
        this.$refs.supplierManageDialogRef.open();
      },
      setSupplierId(data) {
        this.form.winnerId = data.supplierId;
        this.form.winnerName = data.supplierName;
        chooseWinner(this.form);
      },
      //获取询价详情
      async getDetailData(id, type) {
        this.loading = true;
        let data = await getpurchaseinquiry(id);
        this.loading = false;
        if (data) {
          this.form = data;
          this.list = data.detailList;
          this.supplierList = data.supplierList;
          this.$nextTick(() => {
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
          });
          if (type == 'init') {
            this.getplanData(data.planId, type);
          }
          // console.log(this.form, 'this.form');
          // this.$nextTick(() => {

          // });
        }
      },

      //获取计划详情
      async getplanData(id, type) {
        this.loading = true;
        let data = await getplanDetail(id);
        this.loading = false;
        if (data) {
          this.$set(this.form, 'acceptUnpack', data.acceptUnpack);
          this.form.planId = data.id;
          this.form.planCode = data.planCode;
          this.form.planName = data.planName;

          if (type == 'change') {
            this.supplierList.forEach((item) => {
              this.$refs['inquiryTable' + item.supplierId][0].putTableValue(
                data.detailList
              );
            });
          }
          if (type == 'init') {
            return;
          }
          this.list = data.detailList;
          this.$nextTick(() => {
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
          });
        }
      },

      getValidate() {
        let promises = [];
        this.supplierList.forEach((item) => {
          promises.push(
            new Promise((resolve, reject) => {
              this.$refs['inquiryTable' + item.supplierId][0].validateForm(
                (valid) => {
                  if (!valid) {
                    reject(false);
                  } else {
                    resolve(true);
                  }
                }
              );
            })
          );
        });
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          ...promises
        ]);
      },

      //计划删除
      delList(productCode) {
        this.supplierList.forEach((item) => {
          this.$refs['inquiryTable' + item.supplierId][0].remove(productCode);
        });
      },
      removeSupplier(supplierId) {
        if(supplierId == this.form.winnerId){
          this.form.winnerId = ''
          this.form.winnerName = ''
        }
        this.supplierList = this.supplierList.filter(
          (item) => item.supplierId != supplierId
        );
      },

      //选择产品
      handParent() {
        this.$refs.inquiryManageRef.open(this.form.planCode);
      },

      changeInquiryManageList(data) {
        // this.form.planId = data.id;
        // this.form.planCode = data.planCode;
        this.getplanData(data.id, 'change');
      },
      //供应商回调
      supplierManageChange(data) {
        let supplierIds = this.supplierList.map((item) => item.supplierId);
        data.forEach((item) => {
          item['files'] = [];
          item['preferentialPrice'] = '';
          item['settlementMode'] = '';
          item['settlementModeName'] = '';
          item['taxRate'] = '';
          item['totalPrice'] = '';
          item['resultList'] = copyObj(this.list);
          item['resultList'].forEach((val) => {
            val['remark'] = '';
          });
          if (!supplierIds.includes(item.supplierId)) {
            this.supplierList.push(item);
          }
        });
      },

      async getTableValue() {
        let supplierList = [];
        this.supplierList.forEach((item) => {
          supplierList.push(
            this.$refs['inquiryTable' + item.supplierId][0].getTableValue()
          );
        });
        supplierList.forEach((item) => {
          item.resultList.forEach((val) => {
            val['technicalDrawings'] = [];
          });
        });

        this.form.detailList = this.list;
        this.form.supplierList = supplierList;

        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

          if (this.$refs.inventoryTable.getTableValue().length == 0) {
            this.$message.warning('产品清单不能为空');
            return;
          }
          this.form.files = this.form.files || [];
          return this.form;
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }
</style>
