<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="请选择"
              :disabled="isView"
            ></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" :disabled="isView"></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="附件">
            <fileMain v-model="form.files" :type="isView?'view':'add'"></fileMain>
         
          </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="请输入" :disabled="isView"
              size="small"
              maxlength="200"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <headerTitle title="物品清单" style="margin-top: 15px"></headerTitle>
    <el-button type="primary" @click="openSupplier" v-if="!isView">新增供应商</el-button>
    <el-button
        type="primary"
        style="margin-bottom: 10px"
        @click="supplierSelectAll"
        v-click-once
        >批量生成报价单</el-button
      >
    <inventoryTable
      ref="inventoryTable"
      @delList="delList"
      :acceptUnpack="form.acceptUnpack"
      @supplierSelect="supplierSelect"
      :status="isView?'Detail':''"
    ></inventoryTable>

    <headerTitle title="报价清单" style="margin-top: 15px"></headerTitle>
    <inquiryManageList
      ref="inquiryManageRef"
      @changeInquiryManageList="changeInquiryManageList"
      @supplierSelect="supplierSelect"
      @supplierManageChange="supplierManageChange"
    ></inquiryManageList>
    <supplierManageDialog
      ref="supplierManageDialogRef"
      @supplierManageChange="supplierManageChange"
    ></supplierManageDialog>
    <inquiryTable
      @removeSupplier="removeSupplier"
      :ref="'inquiryTable' + item.supplierId"
      v-for="item in supplierList"
      :key="item.supplierId"
      style="margin-top: 15px"
      :obj="item"
      :isUpdate="isUpdate"
      @deliveryDateChange="deliveryDateChange"
      :status="isView?'Detail':'edit'"

    ></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 { deepClone } from '@/utils';
  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';
  import { contactQueryByCategoryIdsAPI } from '@/api/bpm/components/supplierManage/contact';
  import { contactDetail } from '@/api/bpm/components/saleManage/contact';
  // import fileMain from '@/components/addDoc/index.vue';

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

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

        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.requestDict('产地');
      this.requestDict('质保期单位');
      this.requestDict('生产类型');
      this.requestDict('结算方式');
      this.getDetailData(this.businessId, 'init');
    },

    methods: {
      openSupplier() {
        if (this.list.length == 0) {
          this.$message.warning('请先选择采购计划');
          return;
        }
        this.$refs.supplierManageDialogRef.open();
      },
      //获取询价详情
      async getDetailData(id, type) {
        this.loading = true;
        let data = await getpurchaseinquiry(id);
        this.loading = false;
        if (data) {
          this.form = data;
          this.supplierList = data.supplierList;
          let supplierObj = await this.getSupplierObj(
            data.detailList,
            'productId'
          );
          data.detailList.forEach((item) => {
            item.supplierList = supplierObj[item.productId] || [];
          });
          this.list = [...data.detailList, ...data.rawList, ...data.outputList];
          this.rawList = data.rawList;
          this.outputList = data.outputList;
          this.supplierList = data.supplierList;
          this.$nextTick(() => {
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
            // this.setIsInquiry()
          });
          if (type == 'init') {
            this.getplanData(data.planId, type);
          }
          // console.log(this.form, 'this.form');
          // this.$nextTick(() => {

          // });
        }
      },
      deliveryDateChange(fn) {
        let data = this.$refs.inventoryTable.getTableValue() || [];
        fn(data);
      },

      setIsInquiry(supplierList) {
        // let supplierList = [];

        this.$nextTick(() => {
          // this.supplierList.forEach((item) => {
          //   supplierList.push(
          //     this.$refs['inquiryTable' + item.supplierId][0].getTableValue()
          //   );
          // });
          this.$refs.inventoryTable.setIsInquiry(supplierList);
        });
      },
      //获取计划详情
      async getplanData(id, type) {
        this.loading = true;
        let data = await getplanDetail(id);
        this.rawList = data.rawDetailList;
        this.outputList = data.outputDetailList;
        this.loading = false;
        if (data) {
          let supplierObj = await this.getSupplierObj(
            data.detailList,
            '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] || [];
            if (item.supplierList.length === 1) {
              item.supplierIds = [item.supplierList[0].id];
              // this.supplierSelect(item)
            }
          });
          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,
            ...data.rawDetailList,
            ...data.outputDetailList
          ];
          this.$nextTick(() => {
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
          });
        }
      },
      async getSupplierObj(productList, queryName) {
        try {
          let categoryIds = productList.map((item) => item[queryName]);
          return await contactQueryByCategoryIdsAPI({ categoryIds });
        } catch (e) {
          return Promise.resolve({});
        }
      },
      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) {
        this.supplierList = this.supplierList.filter(
          (item) => item.supplierId != supplierId
        );
        // this.setIsInquiry()
      },

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

      changeInquiryManageList(data) {
        this.getplanData(data.id, 'change');
      },
      supplierSelectAll() {
        if (!this.$refs.inventoryTable.selection.length)
          return this.$message.warning('请选择产品');
        this.$refs.inventoryTable.selection.forEach((item) => {
          this.supplierSelect(item);
        });
      },
      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;
        obj.supplierName = data.base.name;
        obj.reqTotalCount=obj.totalCount
        let params = {
          ...data.base,
          supplierId: data.base.id,
          supplierName: data.base.name,
          supplierCode: data.base.code,
          files: [],
          preferentialPrice: '',
          settlementMode: '4',
          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.$set(this.supplierList[supplierIndex], 'resultList', [
              ...this.supplierList[supplierIndex].resultList,
              obj
            ]);
            this.$nextTick(() => {
              this.$refs['inquiryTable' + data.base.id][0]?.putTableValue(
                this.supplierList[supplierIndex].resultList
              );
              this.$refs['inquiryTable' + data.base.id][0]?.getSpanArr();
            });
          }
        }
      },
      //供应商回调
      supplierManageChange(data) {
        let supplierIds = this.supplierList.map((item) => item.supplierId);
        data.forEach((item) => {
          item['files'] = [];
          item['supplierName'] = item.name;
          item['preferentialPrice'] = '';
          item['settlementMode'] = '4';
          item['settlementModeName'] = '分期付款';
          item['taxRate'] = '';
          item['totalPrice'] = '';
          item['resultList'] = copyObj(this.$refs.inventoryTable.selection);
          item['resultList'].forEach((val) => {
            val['remark'] = '';
            item['deliveryDate'] = val.expectReceiveDate;
            val.supplierName = item.name;
            reqTotalCount=val.totalCount
          });

          let supplierIndex = supplierIds.indexOf(item.supplierId);
          if (supplierIndex == -1) {
            this.supplierList.push(item);
          } else {
            item['resultList'].forEach((val) => {
              let isHave = this.supplierList[supplierIndex].resultList.some(
                (i) => i.productCode == val.productCode
              );
              console.log(isHave, supplierIndex);
              if (!isHave) {
                this.$set(this.supplierList[supplierIndex], 'resultList', [
                  ...this.supplierList[supplierIndex].resultList,
                  val
                ]);
                this.$refs['inquiryTable' + item.id][0]?.putTableValue(
                  this.supplierList[supplierIndex].resultList
                );
                this.$nextTick(() => {
                  this.$refs['inquiryTable' + item.id][0]?.getSpanArr();
                });
              }
            });
          }
        });
      },

      async getTableValue() {
        try {
          await this.getValidate();
          let supplierList = [];
          this.supplierList.forEach((item) => {
            supplierList.push(
              this.$refs['inquiryTable' + item.supplierId][0].getTableValue()
            );
          });
          this.setIsInquiry(supplierList);

          let is = false;
          supplierList.forEach((item) => {
            item.resultList.forEach((val) => {
              val['technicalDrawings'] = [];
              if (val.minimumOrderQuantity > val.totalCount) {
                is = true;
              }
            });
          });
          if (is) {
            this.$message.warning('购买数量不能小于最低订购量！');
            return;
          }
          this.form.detailList = this.list;
          this.form.supplierList = supplierList;
          // 表单验证通过，执行保存操作
          this.loading = true;

          if (this.$refs.inventoryTable.getTableValue().length == 0) {
            this.$message.warning('物品清单不能为空');
            return;
          }

          this.form.supplierList.forEach((item) => {
            item.resultList = [
              ...item.resultList,
              ...this.rawList,
              ...this.outputList
            ];
          });
          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>
