<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"
    :append-to-body="true"
    width="70%"
    :maxable="true"
    :resizable="true"
    @close="cancel"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="el-form-box"
    >
      <headerTitle title="基本信息"></headerTitle>
      <el-row gutter="12">
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="询价方名称" prop="contactName">
            <el-input
              clearable
              v-model="form.contactName"
              @click.native="handParent"
              :disabled="!!contactData.id || !!businessOpportunityData.id"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="有无商机" prop="opportunityType">
            <el-select
              v-model="form.opportunityType"
              placeholder="请选择"
              style="width: 100%"
              @change="opportunityTypeChange"
              :disabled="!!businessOpportunityData.id"
            >
              <el-option
                v-for="item in opportunityTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="关联商机"
            prop="opportunityId"
            :rules="[
              {
                required: form.opportunityType === 1 ? true : false,
                message: '请选择关联商机',
                trigger: 'change'
              }
            ]"
          >
            <el-select
              :disabled="
                form.opportunityType === 0 || !!businessOpportunityData.id
              "
              v-model="form.opportunityId"
              placeholder="请选择"
              style="width: 100%"
              @change="opportunityChange"
            >
              <el-option
                v-for="item in businessList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="询价方联系人" prop="contactLinkName">
            <el-autocomplete
              v-model="form.contactLinkName"
              :fetch-suggestions="queryContactLink"
              @select="handleContactSelect"
              @input="handleContactInput"
              placeholder="请输入或选择询价方联系人"
              style="width: 100%"
              clearable
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="询价方电话" prop="contactTel">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.contactTel"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="询价方传真" prop="contactFax">
            <el-input
              clearable
              v-model="form.contactFax"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="	询价方Email" prop="contactEmail">
            <el-input
              clearable
              v-model="form.contactEmail"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="询价方地址" prop="contactAddress">
            <el-input
              clearable
              v-model="form.contactAddress"
              placeholder="请输入"
            />
          </el-form-item>
          
          <el-form-item label="结算方式" prop="settlementMode">
            <DictSelection
              dictName="结算方式"
              clearable
              v-model="form.settlementMode"
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="报价方名称" prop="quoteName">
            <el-input
              v-if="enterprisePage.length <= 1"
              clearable
              v-model="form.quoteName"
              placeholder="请输入"
            />
            <el-select
              v-if="enterprisePage.length > 1"
              style="width: 100%"
              v-model="form.quoteName"
              placeholder="请选择"
              @change="getEnterprise()"
            >
              <el-option
                v-for="item in enterprisePage"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="报价方联系人" prop="quoteLinkName">
            <el-input
              clearable
              v-model="form.quoteLinkName"
              @click.native="handHead()"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item prop="quoteTel" label="报价方联系电话">
            <el-input clearable v-model="form.quoteTel" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="quoteFax" label="报价方传真">
            <el-input clearable v-model="form.quoteFax" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="报价方Email" prop="quoteEmail">
            <el-input
              clearable
              v-model="form.quoteEmail"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item label="报价方地址" prop="quoteAddress">
            <el-input
              clearable
              v-model="form.quoteAddress"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item prop="askFile" label="附件">
            <fileMain v-model="form.askFile"></fileMain>
          </el-form-item>

          <el-form-item label="是否接受拆单" prop="acceptUnpack">
            <el-select
              v-model="form.acceptUnpack"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in acceptUnpackoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <headerTitle title="报价单物品清单"></headerTitle>
      <inventoryTable
        ref="inventoryTable"
        :customerMark="form.customerMark"
        :isTemporary="true"
        :isDiscount="false"
        :cacheKeyUrl="cacheKeyUrl"
        :quoteType="form.type"
      ></inventoryTable>

      <!-- <el-row style="margin-top: 20px">
        <el-col :span="6">
          <el-form-item prop="taxRate" label="税率">
            <el-input clearable v-model="form.taxRate" placeholder="请输入">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="deliveryDate" label="交货日期">
            <el-date-picker
              v-model="form.deliveryDate"
              value-format="yyyy-MM-dd"
              placeholder="请选择交货日期"
              type="date"
              style="width: 100%"
              class="filter-item"
            ></el-date-picker>
          </el-form-item>
        </el-col>
  
      </el-row> -->
    </el-form>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save" v-click-once>保存</el-button>
      <el-button
        type="primary"
        @click="isNeed_process_is_close && save('sub')"
        v-click-once
        >提交</el-button
      >
      <el-button @click="cancel">返回</el-button>
    </div>

    <parentList
      ref="parentRef"
      classType="1"
      @changeParent="changeParent"
    ></parentList>
    <head-list ref="headRef" @changeParent="changePersonel"></head-list>
    <process-submit-dialog
      api-fun-name="quoteUpdateStatusAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </ele-modal>
</template>

<script>
import { emailReg, phoneReg, numberReg, telReg } from 'ele-admin';
import { acceptUnpackoptions } from '@/enum/dict';
import inventoryTable from '@/BIZComponents/inventoryTable.vue';

import { categoryData } from 'element-china-category-data';
import fileUpload from '@/components/upload/fileUpload';
import { cityData } from 'ele-admin/packages/utils/regions';
import dictMixins from '@/mixins/dictMixins';
import deptSelect from '@/components/CommomSelect/dept-select.vue';
import personSelect from '@/components/CommomSelect/person-select.vue';
import parentList from '@/views/saleManage/contact/components/parentList.vue';
import {
  getDetail,
  UpdateInformation,
  addInformation,
  submit
} from '@/api/saleManage/quotation';
import {
  getOpportunityDetail,
  isHasGeneratedQuoteAPI
} from '@/api/saleManage/businessOpportunity';
import { getTableList } from '@/api/saleManage/businessOpportunity';
import { enterprisePage } from '@/api/contractManage/contractBook';
import { getcontactlink } from '@/api/saleManage/businessFollow';
import headList from '@/BIZComponents/user-select/user-select.vue';
import { copyObj } from '@/utils/util';
import { contactDetail, updateRelationStatus } from '@/api/saleManage/contact';
// import fileMain from '@/components/addDoc/index.vue';
import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';

export default {
  props: {
    categoryTreeList: Array,
    contactData: {
      default: () => {
        return {};
      }
    },
    businessOpportunityData: {
      default: () => {
        return {};
      }
    }
  },
  mixins: [dictMixins],
  components: {
    processSubmitDialog,
    // fileMain,
    fileUpload,
    headList,
    inventoryTable,
    deptSelect,
    parentList,
    personSelect
  },
  data() {
    let formDef = {
      id: '',
      acceptUnpack: 1,
      askFile: [],
      contactAddress: '',
      opportunityId: '',
      contactEmail: '',
      contactFax: '',
      contactId: '',
      contactLinkId: '',
      contactLinkName: '',
      contactName: '',
      contactTel: '',
      deliveryDate: '',
      settlementMode: '',
      settlementModeName: '',
      quoteAddress: '',
      quoteEmail: '',
      quoteFax: '',
      quoteLinkId: '',
      quoteLinkName: '',
      quoteName: '',
      quoteTel: '',
      taxRate: null,
      totalPrice: null,
      opportunityType: null,

      type: 1
    };

    return {
      fullscreen: false,
      cacheKeyUrl: 'eos-saleManage-quotation-inventoryTable',
      opportunityTypeList: [
        { label: '有', value: 1 },
        { label: '无', value: 0 }
      ],
      typeOptions: [
        { label: '产品销售', value: 1 },
        { label: '生产加工', value: 2 }
      ],
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],
      acceptUnpackoptions,
      visible: false,
      processSubmitDialogFlag: false,
      title: '',
      row: {},
      activeName: 'base',
      formDef,
      form: copyObj(formDef),
      // removeBankList: [],
      // removeLinkList: [],
      tableBankData: [],
      tableLinkData: [],
      businessList: [], //商机列表
      rules: {
        // opportunityId: [
        //   { required: true, message: '请选择关联商机', trigger: 'change' }
        // ],
        contactName: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
        contactLinkName: [
          { required: true, message: '请选择联系人', trigger: 'change' }
        ],
        acceptUnpack: [
          { required: true, message: '请选择是否接受', trigger: 'change' }
        ],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        contactTel: [
          // {
          //   required: true,
          //   pattern: phoneReg,
          //   message: '请输入联系电话',
          //   trigger: 'blur'
          // },
          {
            required: true, // 只保留必填校验
            message: '请输入联系电话', // 提示文字不变（仅提示必填）
            trigger: 'blur' // 触发时机（失去焦点时校验）
          }
        ],
        deliveryDate: [
          { required: true, message: '请选择交货日期', trigger: 'change' }
        ],
        settlementMode: [
          { required: true, message: '请选择结算方式', trigger: 'change' }
        ],
        quoteLinkName: [
          { required: true, message: '请输入报价方联系人', trigger: 'change' }
        ],
        quoteName: [
          { required: true, message: '请输入报价方名称', trigger: 'blur' }
        ],
        quoteTel: [
          {
            required: true,
            pattern: telReg,
            message: '请输入报价方联系电话',
            trigger: 'blur'
          }
        ],
        quoteEmail: [
          { pattern: emailReg, message: '邮箱格式不正确', trigger: 'blur' }
        ],
        contactEmail: [
          { pattern: emailReg, message: '邮箱格式不正确', trigger: 'blur' }
        ],
        taxRate: [
          { pattern: numberReg, message: '请输入数字', trigger: 'blur' }
        ]
      },
      businessId: '',
      options: {
        cityData,
        categoryData
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,

      // 组织机构树形结构数据
      groupTreeData: [],
      // 组织机构平铺数据
      groupData: [],
      enterprisePage: []
    };
  },
  created() {
    this.getEnterprisePage();
  },

  methods: {
    opportunityTypeChange() {
      if (this.form.opportunityType === 0) {
        this.form.opportunityId = '';
      }
    },
    //获取详情
    async getDetailData(id) {
      this.businessId = id;
      this.loading = true;
      const data = await getDetail(id);
      this.loading = false;
      if (data) {
        this.$nextTick(() => {
          this.form = data;
          // if (data.askFile !== '') {
          //   this.$set(this.form, 'askFile', [data?.askFile]);
          // }
          if (data.opportunityId) {
            this.form.opportunityType = 1;
          }
          this.$refs.inventoryTable &&
            this.$refs.inventoryTable.putTableValue(data);
          this.getLinkInfo(data.contactId);
          this.getBusinessList(data.contactId);
        });
      }
    },
    async opportunityChange(id) {
      //是否生成过报价单
      let res = await isHasGeneratedQuoteAPI(id);
      if (res) this.$message.warning('该商机已生成过报价单，请注意。');
      //获取台账库存
      getOpportunityDetail(id).then((res) => {
        if (res.productList.length > 0) {
          this.$refs.inventoryTable &&
            this.$refs.inventoryTable.putTableValue(res);
        }
      });
    },

    //更新联系人数据
    async getLinkInfo(contactId) {
      const data = await getcontactlink({ contactId });
      if (data && data?.length) {
        this.linkNameOptions = data;

        let firstLink =
          this.linkNameOptions.find((item) => item.ifChief == 1) || {};
        this.form = Object.assign({}, this.form, {
          contactLinkId: firstLink.id || this.linkNameOptions[0]?.id,
          contactLinkName:
            firstLink.linkName || this.linkNameOptions[0]?.linkName,
          contactTel:
            firstLink.mobilePhone || this.linkNameOptions[0]?.mobilePhone,
          contactEmail: firstLink.email || this.linkNameOptions[0]?.email
        });
        console.log(this.form);
      }
    },

    //获取客户的商机列表
    async getBusinessList(id) {
      if (!this.form.contactId)
        return this.$message.error('请先选择询价方名称');
      const data = await getTableList({
        pageNum: 1,
        size: 30,
        contactId: id,
        approvalStatus: 2,
        status: 1
      });
      this.businessList = data.list;
    },
    queryContactLink(queryString, callback) {
      const filtered = queryString
        ? this.linkNameOptions.filter((item) =>
            item.linkName.toLowerCase().includes(queryString.toLowerCase())
          )
        : this.linkNameOptions;
      callback(filtered.map((item) => ({ ...item, value: item.linkName })));
    },

    handleContactSelect(selectedItem) {
      this.form.contactLinkId = selectedItem.id;
      this.form.contactTel =
        selectedItem.mobilePhone || selectedItem.phone || '';
      this.form.contactEmail = selectedItem.email || '';
    },

    handleContactInput() {
      const isExist = this.linkNameOptions.some(
        (item) => item.linkName === this.form.contactLinkName
      );
      if (!isExist) {
        this.form.contactLinkId = ''; // 手动输入时无对应ID
      }
    },
    handHead() {
      let item = {
        id: this.form.quoteLinkId
      };
      this.$refs.headRef.open(item);
    },
    //选择报价方人回调
    changePersonel(obj, index) {
      this.$set(this.form, 'quoteLinkId', obj.id);
      this.$set(this.form, 'quoteLinkName', obj.name);
      this.$set(this.form, 'quoteTel', obj.phone);
      this.$set(this.form, 'quoteEmail', obj.email);
    },
    //选择客户回调
    async changeParent(obj, type) {
      const { base, other } = await contactDetail(obj.id);
      this.form = Object.assign({}, this.form, {
        contactId: base.id,
        contactName: base.name,
        contactAddress: other.addressName + other.address,
        contactLinkId: '',
        contactLinkName: '',
        contactEmail: '',
        contactTel: '',
        customerMark: base.serialNo
      });

      this.getLinkInfo(obj.id);
      this.getBusinessList(base.id);
      if (type == 'init') {
        return;
      }
      this.$nextTick(() => {
        if (this.form.opportunityType == 1) {
          this.$refs.inventoryTable.putTableValue([]);
          this.form.opportunityId = '';
        }
        this.$refs.inventoryTable.setCustomerMark(base.serialNo);
      });
    },

    handParent() {
      let item = {
        id: this.form.contactId
      };
      this.$refs.parentRef.open(item);
    },

    async open(type, row, contactCategoryId) {
      this.title = type === 'add' ? '新增' : '修改';
      this.row = row;
      this.visible = true;
      if (this.enterprisePage.length == 0) {
        await this.getEnterprisePage();
      }
      if (type == 'add') {
        let userInfo = this.$store.getters.user.info;
        this.isUpdate = false;
        userInfo.id = userInfo.userId;
        this.form.settlementMode = '3';
        this.changePersonel(userInfo);
        if (this.enterprisePage.length > 0) {
          this.form.quoteName = this.enterprisePage[0].name;
          // this.form.quoteTel = this.enterprisePage[0].tel;
          this.form.quoteFax = this.enterprisePage[0].fax;
          this.form.quoteAddress = this.enterprisePage[0].address;
        }
        if (this.contactData.id) {
          this.changeParent({ id: this.contactData.id }, 'init');
        }
        if (this.businessOpportunityData.id) {
          this.form.opportunityId = this.businessOpportunityData.id;
          await this.opportunityChange(this.businessOpportunityData.id);
          this.form.opportunityType = 1;
          this.changeParent(
            { id: this.businessOpportunityData.contactId },
            'init'
          );
        }
        if (row.id) {
          this.form.opportunityId = row.id;
          await this.opportunityChange(row.id);
          this.form.opportunityType = 1;
          this.changeParent({ id: row.contactId }, 'init');
        }
      } else {
        this.isUpdate = true;
        await this.getDetailData(row.id);
      }
    },
    getEnterprisePage() {
      enterprisePage({
        pageNum: 1,
        size: 100
      }).then((res) => {
        this.enterprisePage = [];
        this.enterprisePage.push(...res.list);
      });
    },
    getEnterprise() {
      let data = this.enterprisePage.find(
        (item) => item.name == this.form.quoteName
      );
      this.form.quoteName = data.name;

      // this.form.quoteTel = data.tel;
      this.form.quoteFax = data.fax;
      this.form.quoteAddress = data.address;
    },
    salesmanChange(val, info) {
      this.otherForm.salesmanName = info.name;
    },

    ifChiefChange(value, idx) {
      if (value === 1) {
        this.tableLinkData.forEach((e) => (e.ifChief = 0));
        this.tableLinkData[idx].ifChief = 1;
      }
    },

    // getValidate() {
    //   return new Promise((resolve, reject) => {
    //     this.$refs.form.validate((valid) => {
    //       if (!valid) {
    //         reject(false);
    //       } else {
    //         resolve(true);
    //       }
    //     });
    //   });
    // },
    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 save(type) {
      try {
        await this.getValidate();
        // 表单验证通过，执行保存操作
        this.loading = true;

        if (!this.isUpdate) {
          delete this.form.id;
        }
        let settlementModeName = this.getDictValue(
          '结算方式',
          this.form.settlementMode
        );

        let commitData = Object.assign({}, this.form, {
          settlementModeName,
          quoteProductList: this.$refs.inventoryTable.getTableValue(),
          totalPrice: this.$refs.inventoryTable.getPrice()[0]
        });
        if (this.isUpdate) {
          UpdateInformation(commitData)
            .then((res) => {
              this.loading = false;
              updateRelationStatus([this.form.contactId]);
              if (type === 'sub') {
                this.quotationSubmit(res);
                return;
              }
              this.$message.success('修改成功');
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        } else {
          addInformation(commitData)
            .then((res) => {
              this.loading = false;
              updateRelationStatus([this.form.contactId]);
              if (type === 'sub') {
                this.quotationSubmit(res);
                return;
              }
              this.$message.success('新增成功');
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        }
      } catch (error) {
        console.log(error);
        // 表单验证未通过，不执行保存操作
      }
    },
    async quotationSubmit(res) {
      const data = await getDetail(this.businessId || res);
      this.processSubmitDialogFlag = true;
      this.$nextTick(() => {
        let params = {
          businessId: this.businessId || res,
          businessKey: 'quote_approve',
          formCreateUserId: data.createUserId,
          variables: {
            businessCode: data.code,
            businessName: data.contactName,
            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');
    },
    cancel() {
      this.$nextTick(() => {
        this.activeName = 'base';
        // 关闭后，销毁所有的表单数据
        this.$refs['otherForm'] && this.$refs['otherForm'].resetFields();
        this.$refs['formRef'] && this.$refs['formRef'].resetFields();
        this.form = copyObj(this.formDef);
        this.visible = false;
      });
    }
  }
};
</script>
<style scoped lang="scss">
.TotalAmount {
  font-size: 16px;
  padding-right: 30px;
}
</style>
