<template>
  <div class="ele-body">
    <el-card shadow="never" :loading="loading">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <headerTitle title="基本信息">
          <template slot-scope="right">
            <div
              style="
                padding-bottom: 10px;
                position: fixed;
                right: 0;
                width: 250px;
                background: #fff;
                z-index: 999;
              "
            >
              <el-button @click="cancel">返回</el-button>
              <el-button type="primary" @click="save">保存</el-button>
              <el-button
                type="primary"
                v-if="isNeed_process_is_close"
                @click="save('sub')"
                >提交</el-button
              >
            </div>
          </template>
        </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="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="附件">
              <fileMain v-model="form.files" type="view"></fileMain>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <headerTitle title="物品清单" style="margin-top: 15px"></headerTitle>
      <el-button
        type="primary"
        style="margin-bottom: 10px"
        @click="openSupplier"
        v-click-once
        >新增报价单</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"
      >
      </inventoryTable>
      <headerTitle title="报价清单" style="margin-top: 15px"></headerTitle>
      <inquiryManageList
        generatedType="inquiry"
        ref="inquiryManageRef"
        @changeInquiryManageList="changeInquiryManageList"
        @supplierManageChange="supplierManageChange"
        @supplierSelect="supplierSelect"
      ></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"
      ></inquiryTable>
      <process-submit-dialog
        api-fun-name="purchaseinquiryStatusAPI"
        :processSubmitDialogFlag.sync="processSubmitDialogFlag"
        v-if="processSubmitDialogFlag"
        ref="processSubmitDialogRef"
        @reload="reload"
      ></process-submit-dialog>
    </el-card>
  </div>
  <!--  </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,
    updateRelationStatus
  } from '@/api/saleManage/contact';

  import { deepClone } from '@/utils';
  import {
    finishPageTab,
    getRouteTabKey,
    reloadPageTab,
    removePageTab
  } from '@/utils/page-tab-util';
  import _ from 'lodash';
  // import fileMain from '@/components/addDoc/index.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import { orderSourceType } from '@/enum/dict';

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

      return {
        activeName: '1',
        businessId: '',
        visible: false,
        supplierVisible: false,
        processSubmitDialogFlag: 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('结算方式');

      if (this.$route.query.id) {
        this.open(this.$route.query);
      }
    },

    methods: {
      openSupplier() {
        if (!this.form.planCode)
          return this.$message.warning('请先选择采购计划');
        if (!this.$refs.inventoryTable.selection.length)
          return this.$message.warning('请选择产品');
        this.$refs.supplierManageDialogRef.open();
      },
      //获取询价详情
      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 categoryIds = [...data.detailList].map((item) => item.productId);
          let supplierObj = await contactQueryByCategoryIdsAPI({ categoryIds });
          [...data.detailList].forEach((item) => {
            item.supplierList = supplierObj[item.productId] || [];
          });
          this.list = orderSourceType.includes(this.form.sourceType) ? [...data.detailList, ...data.rawList, ...data.outputList] : [...data.detailList];
          this.rawList = data.rawList;
          this.outputList = data.outputList;
          this.$nextTick(() => {
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
          });
          if (type == 'init') {
            await this.getplanData(data.planId, type);
          }
          // this.$nextTick(() => {

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

      //获取计划详情
      async getplanData(id, type) {
        this.loading = true;
        let data = await getplanDetail(id);
        this.rawList = data.rawDetailList;
        this.outputList = data.outputDetailList;
        this.supplierList = [];
        this.loading = false;
        if (data) {
          let categoryIds = [...data.detailList].map((item) => item.productId);
          let supplierObj = await contactQueryByCategoryIdsAPI({ categoryIds });
          [...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) {
              item.supplierIds = item.supplierId
                ? [item.supplierId]
                : [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;
          this.form.isFirstProcess = data.isFirstProcess;
          this.form.inquiryName = data.planName;
          this.form.sourceType = data.sourceType;

          // if (type == 'change') {
          //   this.supplierList.forEach((item) => {
          //     this.$refs['inquiryTable' + item.supplierId][0]&&this.$refs['inquiryTable' + item.supplierId][0].putTableValue(
          //       data.detailList
          //     );
          //   });
          // }
          if (type == 'init') {
            return;
          }
          if(orderSourceType.includes(this.form.sourceType)){
            this.list = [
              ...data.detailList,
              ...data.rawDetailList,
              ...data.outputDetailList
            ];
          } else {
            this.list = [...data.detailList];
          }
          data.detailList.forEach((item) => {
            item.isWinner = 1;
          });
          this.$nextTick(() => {
            this.$refs.inventoryTable &&
              this.$refs.inventoryTable.putTableValue(data.detailList);
            // this.$refs.rawDetailListRef &&
            //   this.$refs.rawDetailListRef.putTableValue(data.rawDetailList); //原料
            // this.$refs.outputDetailListRef &&
            //   this.$refs.outputDetailListRef.putTableValue(
            //     data.outputDetailList
            //   );
          });
        }
      },

      async open({ type, id }) {
        this.title = type === 'add' ? '新增' : '修改';
        this.activeName = '1';

        this.visible = true;
        if (type == 'add') {
          this.isUpdate = false;
          if (id) {
            await this.getplanData(id);
            //是否生成过核价单
            let res = await isHasGeneratedInquiryAPI(id);
            if (res) this.$message.warning('该计划已生成过核价单，请注意。');
          }
        } else {
          this.isUpdate = true;
          await this.getDetailData(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, errors) => {
                  console.log(valid, errors);
                  if (!valid) {
                    // 解析错误信息
                    let errorMessages = [];
                    if (errors) {
                      console.log('Errors structure:', errors);
                        for (let field in errors) {
                          if (errors[field]) {
                            if (Array.isArray(errors[field])) {
                              errors[field].forEach(error => {
                                if (typeof error === 'string') {
                                  errorMessages.push(error);
                                } else if (error && error.message) {
                                  errorMessages.push(error.message);
                                } else {
                                  errorMessages.push(JSON.stringify(error));
                                }
                              });
                            } else if (typeof errors[field] === 'string') {
                              errorMessages.push(errors[field]);
                            } else if (errors[field] && errors[field].message) {
                              errorMessages.push(errors[field].message);
                            } else {
                              errorMessages.push(JSON.stringify(errors[field]));
                            }
                          }
                        }
                    }
                    if (errorMessages.length > 0) {
                      reject(`${item.supplierName}缺少必填项：${errorMessages.join('；')}`);
                    } else {
                      reject(`${item.supplierName} 的表单验证失败，请检查必填项`);
                    }
                  } else {
                    resolve(true);
                  }
                }
              );
            })
          );
        });
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid, errors) => {
              if (!valid) {
                // 解析错误信息
                let errorMessages = [];
                if (errors) {
                  console.log('Main form errors structure:', errors);
                    for (let field in errors) {
                      if (errors[field]) {
                        if (Array.isArray(errors[field])) {
                          errors[field].forEach(error => {
                            if (typeof error === 'string') {
                              errorMessages.push(error);
                            } else if (error && error.message) {
                              errorMessages.push(error.message);
                            } else {
                              errorMessages.push(JSON.stringify(error));
                            }
                          });
                        } else if (typeof errors[field] === 'string') {
                          errorMessages.push(errors[field]);
                        } else if (errors[field] && errors[field].message) {
                          errorMessages.push(errors[field].message);
                        } else {
                          errorMessages.push(JSON.stringify(errors[field]));
                        }
                      }
                    }
                }
                if (errorMessages.length > 0) {
                  reject(`${errorMessages.join('；')}`);
                } else {
                  reject('主表单验证失败，请检查必填项');
                }
              } else {
                resolve(true);
              }
            });
          }),
          ...promises
        ]);
      },

      //计划删除
      delList(productCode) {
        this.supplierList.forEach((item) => {
          this.$refs['inquiryTable' + item.supplierId][0] &&
            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.form.planId = data.id;
        // this.form.planCode = data.planCode;

        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) {
        console.log(row);
        // if (!row) {
        //   this.$message.warning('请选择供应商');
        //   return;
        // }
        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);
          });
        });
      },

      setIsInquiry(supplierList) {
        this.$nextTick(() => {
          // this.supplierList.forEach((item) => {
          //   supplierList.push(
          //     this.$refs['inquiryTable' + item.supplierId][0].getTableValue()
          //   );
          // });
          this.$refs.inventoryTable.setIsInquiry(supplierList);
        });
      },
      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);
        console.log(supplierIndex);
        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) => {
            item['deliveryDate'] = val.expectReceiveDate;
            val['remark'] = '';
            val.supplierName = item.name;
            val.supplierProductCode = val.productCode;
            val.supplierProductName = val.productName;
            val.reqTotalCount = val.totalCount;
            val.isWinner = 1;
          });

          let supplierIndex = supplierIds.indexOf(item.supplierId);
          if (supplierIndex == -1) {
            this.supplierList.push(item);
          } else {
            console.log(1);
            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 save(type) {
        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;
          //  let arr = this.form.supplierList.map(item => item.resultList).flat(2);
          //  console.log(arr);
          //  let a = _.groupBy(arr,'productName')
          //  for (let key in a) {
          //    console.log(key,a[key]);
          //    if(a[key].some(item => item.isWinner ==='')) return this.$message.warning(key+'至少选择一家中标供应商')
          //  }
          //  console.log(a);
          //  return

          // 表单验证通过，执行保存操作
          this.loading = true;
          if (this.$refs.inventoryTable.getTableValue().length == 0) {
            this.$message.warning('物品清单不能为空');
            return;
          }
          if (!this.isUpdate) {
            delete this.form.id;
          }
          console.log('orderSourceType~~~', orderSourceType, this.form.sourceType);
          this.form.supplierList.forEach((item) => {
            if (orderSourceType.includes(this.sourceType)) {
              item.resultList = [
                ...item.resultList,
                ...this.rawList,
                ...this.outputList
              ];
            }
          });
          let supplierIds = this.form.supplierList.map(
            (item) => item.supplierId
          );

          this.form.files = this.form.files || [];
          let API = this.isUpdate ? UpdateInformation : addPurchaseinquiry;
          API(this.form)
            .then((res) => {
              this.loading = false;

              this.$message.success('操作成功');

              updateRelationStatus(supplierIds);
              if (type === 'sub') {
                this.sub(res);
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        } catch (error) {
          console.log(error);
          // 表单验证未通过，显示错误提示
          if (typeof error === 'string') {
            this.$message.warning(error);
          } else {
            this.$message.warning('表单验证失败，请检查必填项');
          }
          // 表单验证未通过，不执行保存操作
        }
      },
      async sub(res) {
        let data = await getpurchaseinquiry(this.businessId || res);
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: 'purchase_inquiry_approve',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.inquiryCode,
              businessName: data.inquiryName,
              businessType: '采购核价'
            }
            // callBackMethodType : '1',
            // callBackMethod : 'proTargetPlanApproveApiImpl.updatePlanApprovalStatus',
            // pcHandle : '/bpm/handleTask/components/project-manage/plan-manage/submit.vue',
            // pcView : '/bpm/handleTask/components/project-manage/plan-manage/detailDialog.vue',
            // miniHandle : '',
            // miniView : '',
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
        // submit({
        //   businessId: this.businessId || res
        // }).then((res) => {
        //   this.cancel();
        //   this.$emit('done');
        // });
      },
      reload() {
        this.cancel();
        this.$emit('done');
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      cancel() {
        reloadPageTab({ fullPath: '/inquiryManage' });
        removePageTab({
          key: '/purchasingManage/inquiryManage/components/addDialog'
        });
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }
</style>
