<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="70%"
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row>
        <el-col :span="8">
          <el-form-item
            label="采购计划单名称"
            prop="planCode">
            <el-input
              @click.native="handParent"
              v-model="form.planName"
              placeholder="请选择"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <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
            label="供应商"
            prop="supplierName"
            style="margin-bottom: 22px"
          >
            <el-input
              @click.native="openSupplier"
              v-model="form.supplierName"
              placeholder="请选择"
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <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="8">
          <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="8">
          <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="产品清单" style="margin-top: 15px"></headerTitle>
    <inventoryTable
      ref="inventoryTable"
      @delList="delList"
      :acceptUnpack="form.acceptUnpack"
      @supplierSelect="supplierSelect"
    ></inventoryTable>

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

    <inquiryManageList
      generatedType="inquiry"
      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>
  </ele-modal>
</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, isHasGeneratedInquiryAPI} from '@/api/purchasingManage/purchasePlanManage';
import {
  UpdateInformation,
  getpurchaseinquiry,
  addPurchaseinquiry,
  chooseWinner,
  submit
} from '@/api/purchasingManage/inquiryManage';

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

import {getFile} from '@/api/system/file';
import {contactDetail, contactQueryByCategoryIdsAPI} from "@/api/saleManage/contact";
import {deepClone} from "@/utils";

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

    return {
      businessId: '',
      visible: false,
      supplierVisible: false,
      title: '',
      supplierList: [],
      detailList: [],
      list: [],
      delDetailIds: [],
      supplierProducts: {},
      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() {
  },

  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;
      if (this.isUpdate) {
        chooseWinner(this.form);
      }
      this.$forceUpdate()
    },
    //获取询价详情
    async getDetailData(id, type) {
      this.businessId = id;
      this.loading = true;
      let data = await getpurchaseinquiry(id);
      this.loading = false;
      if (data) {
        this.form = data;
        this.supplierList = data.supplierList;
        let supplierObj = await contactQueryByCategoryIdsAPI(data.detailList.map(item => item.productId));
        data.detailList.forEach((item) => {
          item.supplierList = supplierObj[item.productId] || []
        });
        this.list = data.detailList;
        this.$nextTick(() => {
          this.$refs.inventoryTable &&
          this.$refs.inventoryTable.putTableValue(data.detailList);
        });
        if (type == 'init') {
          this.getplanData(data.planId, type);
        }
        // this.$nextTick(() => {

        // });
      }
    },

    //获取计划详情
    async getplanData(id, type) {
      this.loading = true;
      let data = await getplanDetail(id);
      this.loading = false;
      if (data) {
        let supplierObj = await contactQueryByCategoryIdsAPI(data.detailList.map(item => item.productId));
        data.detailList.forEach((item) => {
          if (item.arrivalWay == 2 && item.arrivalBatch.length > 0) {
            item.expectReceiveDate =
              item.arrivalBatch[item.arrivalBatch.length - 1].arriveDate;
          }
          item.supplierList = supplierObj[item.productId] || []
        });
        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);
        });
      }
    },

    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.getplanData(row.id);
          //是否生成过核价单
          let res = await isHasGeneratedInquiryAPI(row.id)
          if (res) this.$message.warning('该计划已生成过核价单，请注意。')
        }
      } else {
        this.isUpdate = true;
        this.getDetailData(row.id);
      }
      // this.init(row.id);
    },

    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');
    },
    async supplierSelect(row) {
      let supplierIds = Object.keys(this.supplierProducts);
      const promises = [];
      row.supplierIds.forEach(item => {
        if (!supplierIds.includes(item)) {
          promises.push(contactDetail(item));
        } else {
          this.productSetSupplier(this.supplierProducts[item], row)
        }
      });
      Promise.all(promises).then(results => {
        results.forEach((data, index) => {
          this.supplierProducts[data.base.id] = data;
          this.productSetSupplier(this.supplierProducts[data.base.id], row)
        });
      });
    },
    productSetSupplier(data, row) {
      let obj = deepClone(row);
      obj.supplierProductName = data.productList.find(item => item.productCode == row.productCode)?.productName
      obj.supplierProductCode = data.productList.find(item => item.productCode == row.productCode)?.productCode
      let params = {
        ...data.base,
        supplierId: data.base.id,
        supplierName: data.base.name,
        supplierCode: data.base.code,
        files: [],
        preferentialPrice: '',
        settlementMode: '',
        settlementModeName: '',
        taxRate: '',
        totalPrice: '',
        resultList: [obj],
      }
      let supplierIds = this.supplierList.map((item) => item.supplierId);
      let supplierIndex = supplierIds.indexOf(data.base.id)
      if (supplierIndex == -1) {
        this.supplierList.push(params);
      } else {
        let isHave = this.supplierList[supplierIndex].resultList.some(item => item.productCode == obj.productCode)
        if (!isHave) {
          // putTableValue
          this.supplierList[supplierIndex].resultList.push(obj)
          this.$refs['inquiryTable' + data.base.id][0].putTableValue(this.supplierList[supplierIndex].resultList)
        }
      }
      console.log(this.supplierList, this.$refs['inquiryTable' + data.base.id], '=====');
    },
    //供应商回调
    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);
        }
      });
      console.log(this.supplierList);
    },

    async save(type) {
      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;
        }
        if (!this.isUpdate) {
          delete this.form.id;
        }
        this.form.files = this.form.files || [];
        if (this.isUpdate) {
          if (!this.form.winnerId) return this.$message.warning('请选择中标单位')
          UpdateInformation(this.form)
            .then((res) => {
              this.loading = false;
              this.$message.success('修改成功');
              if (type === 'sub') {
                this.sub(res);
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        } else {
          addPurchaseinquiry(this.form)
            .then((res) => {
              this.loading = false;
              this.$message.success('新增成功');
              if (type === 'sub') {
                this.sub(res);
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        }
      } catch (error) {
        console.log(error);
        // 表单验证未通过，不执行保存操作
      }
    },
    sub(res) {
      submit({
        businessId: this.businessId || res
      }).then((res) => {
        this.cancel();
        this.$emit('done');
      });
    },
    downloadFile(file) {
      getFile({objectName: file.storePath}, file.name);
    },
    cancel() {
      this.$nextTick(() => {
        this.form = copyObj(this.formDef);
        this.supplierList = [];
        this.list = [];
        this.visible = false;
      });
    }
  }
};
</script>
<style scoped lang="scss">
.TotalAmount {
  font-size: 16px;
  padding-right: 30px;
}
</style>
