<template>
  <ContentWrap class="mt-10px">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="151px"
    >
      <ContentWrap style="border: none;font-weight: 700">
        基础信息
      </ContentWrap>
      <el-row>
        
        
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <SelectComponent :customerList="customerList" :disabled="!!formType || route.query.bizId" v-model="formData.customerId" @change="onCustomerChange"  />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formType">
          <el-form-item label="合同名称" prop="name">
            <el-input v-model="formData.name" disabled placeholder="请输入合同名称" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8" v-if="formType">
          <el-form-item label="合同编号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="报价单编号" prop="quotationId">
            <el-select
              disabled
              @change="handleQuotationChange"
              v-model="formData.quotationId"
              placeholder=""
              class="w-1/1"
            >
              <el-option
                v-for="item in quotationList"
                :key="item.id"
                :label="item.no"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="签约人" prop="contractor">
            <el-select
              v-model="formData.contractor"
              class="w-1/1"
              disabled
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="授信额度" prop="creditLimit">
            <el-input v-model="formData.creditLimit" placeholder="" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="授信方式" prop="creditMethod" >
            <el-select v-model="formData.creditMethod" placeholder="" disabled>
              <el-option
                v-for="dict in getIntDictOptions('credit_method')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="授信计算周期" prop="creditCalcCycle" >
            <el-input v-model="formData.creditCalcCycle" placeholder="" disabled />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
        <el-form-item label="票据模板" prop="invoiceTemplateId">
          <el-select v-model="formData.invoiceTemplateId" disabled placeholder="">
            <el-option
              v-for="dict in templateOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-col> -->
        <el-col :span="8">
          <el-form-item label="第几次报价" prop="quotationTimes">
            <el-input v-model="formData.quotationTimes" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="账期" prop="paymentTerm">
          <el-select v-model="formData.paymentTerm" disabled placeholder="">
            <el-option
              v-for="dict in getStrDictOptions('payment_term')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
     
        <el-col :span="8">
          <el-form-item label="基础服务费合计" prop="onlinePrice">
            <el-input
              disabled
              v-model="formData.onlinePrice"
              placeholder="" 
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="线下总金额" prop="offlinePrice">
            <el-input
              disabled
              v-model="formData.offlinePrice"
              placeholder="" 
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="服务费收入合计" prop="price">
            <el-input
              disabled
               placeholder=""
              v-model="formData.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
         
      </el-row>
      <el-row>
      <el-col :span="24">
        <ContentWrap style="border: none;font-weight: 700">
          甲方基本信息
        </ContentWrap>
      </el-col>
      <el-col :span="8">
        <el-form-item label="甲方名称" prop="partyName">
          <el-select
              v-model="formData.customerId"
              disabled=""
              placeholder=""
              class="w-1/1"
            >
              <el-option
                v-for="item in contactList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="8">
        <el-form-item label="客户编号" prop="customerId">
          <el-input v-model="formData.customerId" disabled placeholder="客户编号" />
        </el-form-item>
      </el-col> -->
      <el-col :span="8">
        <el-form-item label="法人代表" prop="legalPersonName">
          <el-input v-model="formData.legalPersonName" placeholder="" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="统一信用代码" prop="creditNo">
          <el-input v-model="formData.creditNo" placeholder="" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="企业类型" prop="regType">
          <el-input v-model="formData.regType" placeholder="" disabled />
        </el-form-item>
      </el-col>
      <!-- <el-col :span="8">
        <el-form-item label="融资信息" prop="financingInfo">
          <el-input v-model="formData.financingInfo" placeholder="融资信息" disabled  />
        </el-form-item>
      </el-col> -->
      <el-col :span="8">
        <el-form-item label="实缴资金" prop="actualCapital">
          <el-input v-model="formData.actualCapital" placeholder="" disabled  />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="参保人数" prop="socialEmployeeNum">
          <el-input v-model="formData.socialEmployeeNum" placeholder="" disabled  />
        </el-form-item>
      </el-col>
      <!-- <el-col :span="8">
        <el-form-item label="上市情况" prop="listingStatus">
          <el-input v-model="formData.listingStatus" placeholder="上市情况" disabled />
        </el-form-item>
      </el-col> -->
      <el-col :span="8">
        <el-form-item label="注册地址" prop="registeredAddress">
          <el-input v-model="formData.registeredAddress" placeholder="" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <ContentWrap style="border: none;font-weight: 700">
          乙方基本信息
        </ContentWrap>
      </el-col>
      <el-col :span="8">
          <el-form-item label="合作类型" prop="partnerType">
             <el-select v-model="formData.partnerType" disabled  clearable placeholder="请选择合作类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_PARTNER_TYPE1)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      <el-col :span="8">
        <el-form-item label="合作主体" prop="partnerCompanyId">
          <el-select v-model="formData.partnerCompanyId" placeholder="" disabled >
            <el-option
              v-for="dict in orgList"
              :key="dict.id"
              :label="dict.orgName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="开户行" prop="bankName">
          <el-input v-model="formData.bankName" placeholder="" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="formData.bankAccount" placeholder="" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="法人代表" prop="legalRepresentative">
          <el-input v-model="formData.legalRepresentative" placeholder="" disabled />
        </el-form-item>
      </el-col>
      <!-- <el-col :span="8">
        <el-form-item label="商务负责人" prop="ownerUserId">
          <el-select
              v-model="formData.ownerUserId"
              disabled
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
        </el-form-item>
      </el-col> -->
      <!-- <el-col :span="8">
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="formData.ownerUserMobile"
            placeholder=""
            disabled
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="E-mail" prop="email">
          <el-input
            v-model="formData.ownerUserEmail"
            placeholder=""
            disabled
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="微信号" prop="wechat">
          <el-input
            v-model="formData.ownerUserWechat"
            placeholder=""
            disabled
          />
        </el-form-item>
      </el-col> -->
      <el-col :span="8">
        <el-form-item label="归属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            :data="deptTree"
            disabled
            :props="defaultProps"
            check-strictly
            node-key="id"
            placeholder=""
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <ContentWrap style="border: none;font-weight: 700">
          合同信息
        </ContentWrap>
      </el-col>
      <el-col :span="8">
          <el-form-item label="合同类型" prop="contractType">
            <el-radio-group v-model="formData.contractType">
              <el-radio :label="1">甲方合同</el-radio>
              <el-radio :label="2">乙方合同</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="违约金比例（%）" prop="penaltyRate">
            <el-select v-model="formData.penaltyRate" placeholder="请选择违约金比例">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CONTRACT_PENALTY_RATE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="延期付款利率（%）" prop="latePaymentRate">
            <el-select v-model="formData.latePaymentRate" placeholder="请选择延期付款利率">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CONTRACT_LATE_PAYMENT_RATE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同签订日期" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="date"
              @change="changeTime"
              value-format="x"
              format="YYYY-MM-DD"
              placeholder="选择合同签订日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同期限(月)" prop="contractTerm">
            <el-input v-model="formData.contractTerm" @input="changeTime" oninput = "value=value.replace(/[^\d]/g,'')" placeholder="请输入合同期限(月)" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              value-format="x"
              disabled
              placeholder="选择合同结束时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        
        <el-col :span="8">
          <el-form-item label="账单日" prop="statementDate">
            <el-select v-model="formData.statementDate" disabled placeholder="请选择账单日"  >
              <el-option
                v-for="(dict, index) in statement"
                :key="index"
                :label="index + 1"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最晚付款日" prop="lastPayDate">
            <el-select v-model="formData.lastPayDate" disabled placeholder="请选择最晚付款日"  >
              <el-option
                v-for="(dict, index) in statement"
                :key="index"
                :label="index + 1"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="票据模板" prop="invoiceTemplateId">
            <el-input v-model="formData.invoiceTemplateId" placeholder="请输入票据模板" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row> -->
      <el-col :span="24">
        <ContentWrap style="border: none;font-weight: 700">
          对接信息
        </ContentWrap>
      </el-col>
      <!-- <el-col :span="8">
        <el-form-item label="财务结算方式" prop="settleMethod">
          <el-radio-group v-model="formData.settleMethod">
            <el-radio :label="1">按月结算</el-radio>
            <el-radio :label="0">按项目结算</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col> -->
      
        <el-col :span="8">
          <el-form-item label="服务对接人" prop="servicor">
            <el-select
               class="w-1/1"
               placeholder="请选择服务对接人"
              v-model="formData.servicor"
              filterable
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="技术对接人" prop="technicalLead">
            <el-select
               class="w-1/1"
               placeholder="请选择技术对接人"
              v-model="formData.technicalLead"
              filterable
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算对接人" prop="settlementLead">
            <el-select
               class="w-1/1"
               placeholder="请选择结算对接人"
              v-model="formData.settlementLead"
              filterable
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="维护人" prop="afterSaleUserId">
          <el-select v-model="formData.afterSaleUserId" disabled placeholder="请选择售后维护人">
            <el-option
              v-for="dict in userOptions"
              :key="dict.id"
              :label="dict.nickname"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="拓展人" prop="clueDeveloper">
            <el-select
               class="w-1/1"
               placeholder="请选择拓展人"
               disabled
              v-model="formData.clueDeveloper"
              filterable
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      <!-- <el-col :span="8">
        <el-form-item label="维护人" prop="afterSaleUserId">
          <el-select v-model="formData.afterSaleUserId" placeholder="请选择售后维护人">
            <el-option
              v-for="dict in userOptions"
              :key="dict.id"
              :label="dict.nickname"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-col> -->
      <!-- <el-col :span="8">
          <el-form-item label="协作人" prop="collUserId">
            <el-select v-model="formData.collUserId" placeholder="请选择协作人">
              <el-option
                v-for="dict in userOptions"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
      <!-- <el-col :span="24">
        <el-form-item label="合同正文" prop="contractBody">
          <el-input v-model="formData.contractBody" type="textarea" rows="5" placeholder="请输入合同正文" />
        </el-form-item>
      </el-col> -->
      <el-col :span="24">
        <el-form-item label="合同补充协议" prop="contractAgreement">
          <el-input v-model="formData.contractAgreement" type="textarea" rows="5" placeholder="请输入合同补充协议" />
        </el-form-item>
      </el-col>
        
      </el-row>
      <ContentWrap style="border: none;font-weight:700">
        产品清单
      </ContentWrap>
      <!-- 子表的表单 -->
      <ContentWrap>
            <ContractProductForm
              ref="productFormRef"
               :formFields="formFields"
              :products="formData.products"
              :disabled="disabled"
              :type="1"
            />
      </ContentWrap>
      <ContentWrap style="border: none;font-weight:700">
       <span style="color: #f56c6c">*</span> 合同甲方关联单位
      </ContentWrap>
      <ContentWrap>
        <ContractAAuthorizedCompanyForm :formFields="formFields" ref="contractAAuthorizedCompanyFormRef" :data="formData.contractAAuthorizedCompanys" :contract-id="formData.id" :customerId="formData.customerId" />
      </ContentWrap>
      <ContentWrap style="border: none;font-weight:700">
        <span style="color: #f56c6c">*</span> 合同甲方授权人信息
      </ContentWrap>
      <ContentWrap>
        <ContractAAuthorizedPersonForm :formFields="formFields" ref="contractAAuthorizedPersonFormRef" :contract-id="formData.id" :customerId="formData.customerId" />
      </ContentWrap>
      <!-- <ContentWrap style="border: none;font-weight:700">
        合同乙方授权人信息
      </ContentWrap>
      <ContentWrap>
        <ContractBAuthorizedPersonForm :formFields="formFields" ref="contractBAuthorizedPersonFormRef" :userOptions="userOptions" :contract-id="formData.id" />
      </ContentWrap> -->
    </el-form>
    <!-- 显示在其他页面时的判断type -->
    <div style="text-align: right" v-if="!type">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="goBack">取 消</el-button>
    </div>
  </ContentWrap>
</template>
<script lang="ts" setup>
import * as CustomerApi from '@/api/crm/customer'
import * as ContractApi from '@/api/crm/contract'
import * as ContactApi from '@/api/crm/contact'
import * as UserApi from '@/api/system/user'
import { QuotationApi,QuotationVO } from '@/api/crm/quotation'
import { erpPriceMultiply, erpPriceInputFormatter } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import { BillTemplateApi, BillTemplateVO } from '@/api/crm/billtemplate'
import ContractProductForm from '@/views/crm/contract/components/ContractProductForm.vue'
import ContractAAuthorizedCompanyForm from './components/ContractAAuthorizedCompanyForm.vue'
import ContractAAuthorizedPersonForm from './components/ContractAAuthorizedPersonForm.vue'
import ContractBAuthorizedPersonForm from './components/ContractBAuthorizedPersonForm.vue'
import { propTypes } from '@/utils/propTypes'
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import moment from 'moment';


const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { proxy }: any = getCurrentInstance();
const props = defineProps({
  id: propTypes.number.def(undefined),
  type: propTypes.number.def(undefined),
  changeType: propTypes.number.def(undefined),//合同变更不回显数据
})
const statement = ref(new Array(31).fill(null))
const templateOptions = ref([]) 
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const deptTree = ref() // 部门树形结构
const formFields = ref({ 
  productsother: 1,
  productsproductName: 1,
  productscategory: 1,
  productsdetailType: 1,
  productsproductUnit: 1,
  productsbasicServiceFee: 1,
  productsadvancePaymentServiceFee: 1,
  productsbookingPaymentServiceFee: 1,
  productsbillSortingServiceFee: 1,
  productstotalServiceFee: 1,
  productsproductInvoice: 1,
  productsproductInvoiceItem: 1,
  productsserviceInvoice: 1,
  productsserviceInvoiceItem: 1,
  productsother1: 1,
  contractAAuthorizedCompanysother: 1,
  contractAAuthorizedCompanyscustomerName: 1,
  contractAAuthorizedCompanysunifiedCreditCode: 1,
  contractAAuthorizedCompanysinvoicingAddress: 1,
  contractAAuthorizedCompanysinvoicingTelephone: 1,
  contractAAuthorizedCompanyscompanyBank: 1,
  contractAAuthorizedCompanyscompanyAccount: 1,
  contractAAuthorizedCompanyscompanyAddress: 1,
  contractAAuthorizedCompanysother2: 1,
  contractAAuthorizedPersonsother: 1,
  contractAAuthorizedPersonscustomerName: 1,
  contractAAuthorizedPersonsauthPersonType: 1,
  contractAAuthorizedPersonsphoneNumber: 1,
  contractAAuthorizedPersonswechat: 1,
  contractAAuthorizedPersonsidNumber: 1,
  contractAAuthorizedPersonsemail: 1,
  contractAAuthorizedPersonsother2: 1,
  contractBAuthorizedPersonsother: 1,
  contractBAuthorizedPersonsauthType: 1,
  contractBAuthorizedPersonsuserId: 1,
  contractBAuthorizedPersonspostName: 1,
  contractBAuthorizedPersonsuserRank: 1,
  contractBAuthorizedPersonsauthDesc: 1,
  contractBAuthorizedPersonsphoneNumber: 1,
  contractBAuthorizedPersonswechat: 1,
  contractBAuthorizedPersonsemail: 1,
  contractBAuthorizedPersonsother2: 1,
})
const formData = ref({
  id: undefined,
  name: undefined,
  no: undefined,
  customerId: undefined,
  partyName: undefined,
  lastPayDate: undefined,
  partAddress: undefined,
  secPartyPerson: undefined,
  wechat: undefined,
  quotationId: undefined,
  invoiceTemplateId: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  startTime: undefined,
  endTime: undefined,
  penaltyRate: undefined,
  latePaymentRate: undefined,
  settleMethod: undefined,
  lastPayDate: undefined,
  contractTerm: undefined,
  signUserId: undefined,
  signPhoneNumber: undefined,
  signEmail: undefined,
  signWechat: undefined,
  offlinePrice: undefined,
  onlinePrice: undefined,
  ownerUserId: undefined,
  clueDeveloper: undefined,
  contractor: undefined,
  afterSaleUserId: undefined,
  collUserId: undefined,
  totalPrice: undefined,
  contractBody: undefined,
  contractAgreement: undefined,
  creditMethod: undefined,
  creditCalcCycle: undefined,
  creditLimit: undefined,
  partnerCompanyId: undefined,
  deptId: undefined,
  quotationTimes: undefined,
  statementDate: undefined,
  contractType: 2,
  contractAAuthorizedCompanys: [],
  products: []
})
const formRules = reactive({
  name: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  quotationId: [{ required: true, message: '报价单编号不能为空', trigger: 'blur' }],
  orderDate: [{ required: true, message: '下单日期不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '合同签订日期不能为空', trigger: 'change' }],
  contractTerm: [{ required: true, message: '合同期限不能为空', trigger: 'blur' }],
  // ownerUserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  // statementDate: [{ required: true, message: '账单日不能为空', trigger: 'change' }],
  contractType: [{ required: true, message: '合同类型不能为空', trigger: 'change' }],
  penaltyRate: [{ required: true, message: '违约金比例不能为空', trigger: 'blur' }],
  latePaymentRate: [{ required: true, message: '延期付款利率不能为空', trigger: 'blur' }],
  collUserId: [{ required: true, message: '协作人不能为空', trigger: 'blur' }],
  settleMethod: [{ required: true, message: '财务结算方式不能为空', trigger: 'change' }],
  servicor: [{ required: true, message: '服务对接人不能为空', trigger: 'change' }],
  technicalLead: [{ required: true, message: '技术对接人不能为空', trigger: 'change' }],
  settlementLead: [{ required: true, message: '结算对接人不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const customerList = ref([]) // 客户列表的数据
const quotationList = ref<QuotationVO[]>([])
const contactList = ref<ContactApi.ContactVO[]>([])
const orgList = ref([])

/** 子表的表单 */
const subTabsName = ref('product')
const productFormRef = ref()
const contractAAuthorizedCompanyFormRef = ref()
const contractAAuthorizedPersonFormRef = ref()
const contractBAuthorizedPersonFormRef = ref()

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value,
  (val) => {
    if (!val) {
      return
    }
    // const totalPrice = val.products.reduce((prev, curr) => prev + curr.totalPrice, 0)
    // 赋值
    // formData.value.totalPrice = totalPrice
  },
  { deep: true }
)

/** 打开弹窗 */
const open = async (type: string) => {
  if (type) {
    // formLoading.value = true
    try {
      let data = await ContractApi.getContract(type)
      data.legalPersonName = data.customerDO.legalPersonName
      data.creditNo = data.customerDO.creditNo
      data.registeredAddress = data.customerDO.registeredAddress
      data.actualCapital = data.customerDO.actualCapital
      data.socialEmployeeNum = data.customerDO.socialEmployeeNum
      handleQuotationChange(formData.value.quotationId)
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
  
}
/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}
defineExpose({ open, validate, getData }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  if(contractAAuthorizedCompanyFormRef.value.getData().length) {
  } else {
    return message.warning('请完善合同甲方关联单位')
  } 

   if(contractAAuthorizedPersonFormRef.value.getData().length) {
    const contractAAuthorizedPerson = await contractAAuthorizedPersonFormRef.value.validate()
    if (!contractAAuthorizedPerson) return message.warning('请完善合同甲方授权人信息')
  } else {
    return message.warning('请完善合同甲方授权人信息')
  } 

  // if(contractBAuthorizedPersonFormRef.value.getData().length) {
  //   const contractBAuthorizedPersonPerson = await contractBAuthorizedPersonFormRef.value.validate()
  //   if (!contractBAuthorizedPersonPerson) return message.warning('请完善合同乙方授权人信息')
  // } else {
  //   return message.warning('请完善合同乙方授权人信息')
  // } 

  formLoading.value = true

  try {
    const data = unref(formData.value) as unknown as ContractApi.ContractVO
    // 拼接子表的数据
    data.contractAAuthorizedCompanys = contractAAuthorizedCompanyFormRef.value.getData()
    data.contractAAuthorizedPersons = contractAAuthorizedPersonFormRef.value.getData()
    // data.contractBAuthorizedPersons = contractBAuthorizedPersonFormRef.value.getData()
    if (!formType.value ) {
      await ContractApi.createContract(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractApi.updateContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    goBack()
  } finally {
    formLoading.value = false
  }
}

const goBack = ()=> {
  proxy.$router.go(-1)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    no: undefined,
    customerId: undefined,
    quotationId: undefined,
    invoiceTemplateId: undefined,
    processInstanceId: undefined,
    auditStatus: undefined,
    startTime: undefined,
    endTime: undefined,
    penaltyRate: undefined,
    latePaymentRate: undefined,
    settleMethod: undefined,
    lastPayDate: undefined,
    contractTerm: undefined,
    signUserId: undefined,
    signPhoneNumber: undefined,
    signEmail: undefined,
    signWechat: undefined,
    offlinePrice: undefined,
    onlinePrice: undefined,
    ownerUserId: undefined,
    clueDeveloper: undefined,
    contractor: undefined,
    afterSaleUserId: undefined,
    collUserId: undefined,
    totalPrice: undefined,
    contractBody: undefined,
    contractAgreement: undefined,
    creditMethod: undefined,
    creditCalcCycle: undefined,
    creditLimit: undefined,
    partnerCompanyId: undefined,
    deptId: undefined,
    quotationTimes: undefined,
    paymentTerm: undefined,
    products: []
  }
  formRef.value?.resetFields()
}


/** 处理商机变化 */
const handleQuotationChange = async (quotationId: number) => {
  if (!quotationId) return
  try {
    console.log('%csrc/views/crm/contract/ContractForm.vue:886 222', 'color: #007acc;', 222);
    const quotation = await QuotationApi.getQuotation(quotationId)
    formData.value.products = quotation.products;
    // formData.value.customerId = quotation.customerId; 

    formData.value.invoiceTemplateId = quotation.invoiceTemplateId; 

    formData.value.ownerUserId = quotation.ownerUserId;
    formData.value.ownerUserMobile = quotation.ownerUserMobile;
    formData.value.ownerUserWechat = quotation.ownerUserWechat;
    formData.value.ownerUserEmail = quotation.ownerUserEmail;
    formData.value.clueDeveloper = quotation.clueDeveloper;
    formData.value.signUserId = quotation.signUserId;
    formData.value.signPhoneNumber = quotation.signPhoneNumber;
    formData.value.signEmail = quotation.signEmail;
    formData.value.paymentTerm = quotation.paymentTerm;

    formData.value.partnerCompanyId = quotation.partnerCompanyId;
    formData.value.statementDate = quotation.statementDate;
    formData.value.lastPayDate = quotation.lastPayDate;

    formData.value.partnerType = quotation.partnerType;
    formData.value.creditLimit = quotation.creditLimit;
    formData.value.creditMethod = quotation.creditMethod;
    formData.value.creditCalcCycle = quotation.creditCalcCycle;

    formData.value.deptId = quotation.deptId;
    formData.value.offlinePrice = quotation.offlinePrice;
    formData.value.onlinePrice = quotation.onlinePrice;
    formData.value.totalPrice = quotation.totalPrice;
    
     const customerRes = await ContractApi.quotationTimes(quotation.id);
     formData.value.quotationTimes = customerRes.quotationTimes;
    //  await onCustomerChange(quotation.customerId);
     await onPartnerChange(quotation.partnerCompanyId);
  } catch (err) {
  } finally {

  }
  
}

const onCustomerChange = async (customerId: string) => {
  if (!customerId) return;

  try {
    formLoading.value = true;
    // let customerRes = {}
    // if(formType.value) {
    //   customerRes = await CustomerApi.getCustomer(customerId);
    // }else {
    let customerRes = await CustomerApi.getCustomerDetail(customerId);
    formData.value.quotationId = customerRes.quotationId;
    formData.value.servicor = customerRes.servicor;
    formData.value.technicalLead = customerRes.technicalLead;
    formData.value.settlementLead = customerRes.settlementLead;
    // }
    formData.value.companyType = customerRes.companyType;
    formData.value.listingStatus = customerRes.listingStatus;
    formData.value.financingInfo = customerRes.financingInfo;
    formData.value.paidInCapital = customerRes.paidInCapital;
    formData.value.insuredCount = customerRes.insuredCount;
    formData.value.establishmentDate = customerRes.establishmentDate;
    formData.value.enterpriseType = customerRes.enterpriseType;
    formData.value.actualCapital = customerRes.actualCapital;

    formData.value.partAddress = customerRes.partAddress;
    formData.value.listingStatus = customerRes.listingStatus;
    formData.value.legalPersonName = customerRes.legalPersonName;
    formData.value.creditNo = customerRes.creditNo;
    formData.value.regType = customerRes.regType;
    formData.value.financingInfo = customerRes.financingInfo;
    formData.value.socialEmployeeNum = customerRes.socialEmployeeNum;
    formData.value.registeredAddress = customerRes.registeredAddress;
    formData.value.afterSaleUserId = customerRes.maintainer;
    formData.value.clueDeveloper = customerRes.clueDeveloper;
    
     await handleQuotationChange(customerRes.quotationId);

  } catch (err) {
    console.error('获取客户详情失败:', err);
  } finally {
    formLoading.value = false;
  }
}

const onPartnerChange = async (id: string) => {
  if (!id) return
  try {
    formLoading.value = true;
    const res = await ContractApi.getOrgInfo(id);
    formData.value.bankName = res.bankName;
    formData.value.bankAccount = res.bankAccount;
    formData.value.legalRepresentative = res.legalRepresentative;
    formData.value.businessLicenseNumber = res.businessLicenseNumber;
    formData.value.businessLicense = res.businessLicense;
    // formData.value.partnerCompanyId = res.partnerCompanyId;
  } catch (err) {
  } finally {
    formLoading.value = false;
  }
}

const changeTime = ()=> {
  if(formData.value.startTime && formData.value.contractTerm) {
    let year = new Date(formData.value.startTime).getFullYear()
    let month = new Date(formData.value.startTime).getMonth() + 1
    let day = new Date(formData.value.startTime).getDate()
    let addYear = Math.floor(formData.value.contractTerm / 12)
    let addMonth = formData.value.contractTerm % 12
    let remainMonth = addMonth + month
    let lastMonth = remainMonth
    if (remainMonth >= 12) {
      lastMonth = remainMonth - 12
      addYear = addYear + 1
    }
    let newMonth = lastMonth <= 10 ? ("0" + lastMonth) :lastMonth
    let newDay = day <= 10 ? ("0" + day) :day
    let lastYear = addYear + year
    let time = lastYear + '-' + newMonth + '-' + newDay
     formData.value.endTime = new Date(time).getTime()

  }
}


/** 动态获取客户联系人 */
const getContactOptions = computed(() =>
  contactList.value.filter((item) => item.customerId == formData.value.customerId)
)

const route = useRoute();
onMounted(async () => {
  formData.value.contractor = useUserStore().getUser.id;
  let isId = props.id || route.query.id
  if(!props.changeType) {
    formType.value = props.id || route.query.id
  
    if (formType.value) await open(formType.value)
  }

  if(route.query.bizId) {

    formData.value.customerId = Number(route.query.bizId)
    
    onCustomerChange(formData.value.customerId)
  }

  // if(formData.value.customerId) onCustomerChange(formData.value.customerId)
  // 获得客户列表
  customerList.value = await CustomerApi.getSelfCustomerSimpleList()
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 获得报价列表
  if(isId) {
    let data = await QuotationApi.getQuotationPage({
      pageNo: 1,
      pageSize: 999,
      no: undefined,
      sceneType: '1',
    })
    quotationList.value = data.list

  } else {
    quotationList.value = await QuotationApi.getSelfSimpleQuotationList()
  }

  // //票据
  //  const tempData = await BillTemplateApi.getBillTemplatePage({
  //   pageNo: 1,
  //   pageSize: 1000,
  // })
  // templateOptions.value = tempData.list


  // 获得部门树
  deptTree.value = handleTree(await DeptApi.getSimpleDeptList())
  // 默认新建时选中自己
  // if (formType.value === 'create') {
  //   formData.value.ownerUserId = useUserStore().getUser.id
  // }
  // 获取联系人
  contactList.value = await CustomerApi.getSelfCustomerSimpleList()
  const data = await ContractApi.getOrg({
    pageNo: 1,
    pageSize: 1000
  })
  orgList.value = data.list


});
</script>
