<template>
  <ContentWrap class="mt-10px">
    <processForm
      ref="formRef"
      v-loading="formLoading"
      :fields="formFields"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
     
        <!-- <el-col :span="8">
          <el-form-item label="合同名称" prop="name">
            <el-input v-model="formData.name" disabled placeholder="" />
          </el-form-item>
        </el-col> -->
      <template #other>
        <el-col :span="24">
          <ContentWrap style="border: none;font-weight: 700">
            基础信息
          </ContentWrap>
        </el-col>
      </template>
      <template #customerId>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="formData.customerId"
               :disabled="formFields.customerId !== 2 || isTrue"
              placeholder=""
              class="w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #no>
        <el-col :span="8" v-if="formType">
          <el-form-item label="合同编号" prop="no">
            <el-input v-model="formData.no" disabled placeholder="" />
          </el-form-item>
        </el-col>
      </template>
      <template #quotationId>
        <el-col :span="8">
          <el-form-item label="报价单编号" prop="quotationId">
            <el-select
              @change="handleQuotationChange"
              v-model="formData.quotationId"
              placeholder=""
              disabled
              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>
      </template>
      <template #pricingUserId>
        <el-col :span="8">
          <el-form-item label="方案签约人" prop="pricingUserId">
            <el-select
              @change="handleQuotationChange"
              v-model="formData.pricingUserId"
               :disabled="formFields.pricingUserId !== 2 || isTrue"
               placeholder=""
              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>
      </template>
      <template #creditLimit>
        <el-col :span="8">
          <el-form-item label="授信额度" prop="creditLimit">
            <el-input v-model="formData.creditLimit" placeholder="" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template #creditMethod>
        <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>
      </template>
      <template #creditCalcCycle>
        <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> -->
      </template>
      <template #quotationTimes>
        <el-col :span="8">
          <el-form-item label="第几次报价" prop="quotationTimes">
            <el-input v-model="formData.quotationTimes" disabled placeholder="" />
          </el-form-item>
        </el-col>
      </template>
      <template #paymentTerm>
        <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>
      </template>
      <template #onlinePrice>
        <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> -->
      </template>
      <template #totalPrice>
        <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>
        </template>
      <template #other1>
        <el-col :span="24">
          <ContentWrap style="border: none;font-weight: 700">
            甲方基本信息
          </ContentWrap>
        </el-col>
      </template>
      <template #customerId1>
        <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> -->
      </template>
      <template #legalPersonName>
        <el-col :span="8">
          <el-form-item label="法人代表" prop="legalPersonName">
            <el-input v-model="formData.legalPersonName" placeholder="" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template #creditNo>
        <el-col :span="8">
          <el-form-item label="统一信用代码" prop="creditNo">
            <el-input v-model="formData.creditNo" placeholder="" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template #regType>
        <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> -->
      </template>
      <template #actualCapital>
        <el-col :span="8">
          <el-form-item label="实缴资金" prop="actualCapital">
            <el-input v-model="formData.actualCapital" placeholder="" disabled  />
          </el-form-item>
        </el-col>
      </template>
      <template #socialEmployeeNum>
        <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> -->
      </template>
      <template #registeredAddress>
        <el-col :span="8">
          <el-form-item label="注册地址" prop="registeredAddress">
            <el-input v-model="formData.registeredAddress" placeholder="" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template #other2>
        <el-col :span="24">
          <ContentWrap style="border: none;font-weight: 700">
            乙方基本信息
          </ContentWrap>
        </el-col>
      </template>
      <template #partnerCompanyId>
        <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>
      </template>
      <template #bankName>
        <el-col :span="8">
          <el-form-item label="开户行" prop="bankName">
            <el-input v-model="formData.bankName" placeholder="" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template #bankAccount>
        <el-col :span="8">
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="formData.bankAccount" placeholder="" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template #legalRepresentative>
        <el-col :span="8">
          <el-form-item label="法人代表" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" placeholder="" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template #ownerUserId>
        <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> -->
      </template>
      <template #deptId>
        <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>
      </template>
      <template #other3>
        <el-col :span="24">
          <ContentWrap style="border: none;font-weight: 700">
            合同信息
          </ContentWrap>
        </el-col>
      </template>
      <template #contractType>
        <el-col :span="8">
          <el-form-item label="合同类型" prop="contractType">
            <el-radio-group v-model="formData.contractType"  :disabled="formFields.contractType !== 2 || isTrue">
              <el-radio :label="1">单次合同</el-radio>
              <el-radio :label="2">框架合同</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </template>
      <template #startTime>
        <el-col :span="8">
          <el-form-item label="合同签订日期" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
               :disabled="formFields.startTime !== 2 || isTrue"
              type="date"
              value-format="x"
              placeholder=""
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </template>
      <template #endTime>
        <el-col :span="8">
          <el-form-item label="合同结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
               :disabled="formFields.endTime !== 2 || isTrue"
              value-format="x"
              placeholder=""
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </template>
      <template #contractTerm>
        <el-col :span="8">
          <el-form-item label="合同期限(月)" prop="contractTerm">
            <el-input v-model="formData.contractTerm"  :disabled="formFields.contractTerm !== 2 || isTrue" oninput = "value=value.replace(/[^\d]/g,'')" placeholder="" />
          </el-form-item>
        </el-col>
      </template>
      <template #statementDate>
        <el-col :span="8">
          <el-form-item label="账单日" prop="statementDate">
            <el-select v-model="formData.statementDate"  :disabled="formFields.statementDate !== 2 || isTrue" placeholder=""  >
              <el-option
                v-for="(dict, index) in statement"
                :key="index"
                :label="index + 1"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #lastPayDate>
        <el-col :span="8">
          <el-form-item label="最晚付款日" prop="lastPayDate">
            <el-select v-model="formData.lastPayDate"  :disabled="formFields.lastPayDate !== 2 || isTrue" placeholder=""  >
              <el-option
                v-for="(dict, index) in statement"
                :key="index"
                :label="index + 1"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #penaltyRate>
        <el-col :span="8">
          <el-form-item label="违约金比例" prop="penaltyRate">
            <el-input v-model="formData.penaltyRate"  :disabled="formFields.penaltyRate !== 2 || isTrue" placeholder="" />
          </el-form-item>
        </el-col>
      </template>
      <template #latePaymentRate>
        <el-col :span="8">
          <el-form-item label="延期付款利率" prop="latePaymentRate">
            <el-input v-model="formData.latePaymentRate"  :disabled="formFields.latePaymentRate !== 2 || isTrue" placeholder="" />
          </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> -->
      </template>
      <template #other4>
        <el-col :span="24">
          <ContentWrap style="border: none;font-weight: 700">
            财务与客服对接信息
          </ContentWrap>
        </el-col>
      </template>
      <template #settleMethod>
        <el-col :span="8">
          <el-form-item label="财务结算方式" prop="settleMethod">
            <el-radio-group v-model="formData.settleMethod"  :disabled="formFields.settleMethod !== 2 || isTrue">
              <el-radio :label="1">按月结算</el-radio>
              <el-radio :label="0">按项目结算</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </template>
      <template #afterSaleUserId>
        <el-col :span="8">
          <el-form-item label="售后维护人" prop="afterSaleUserId">
            <el-select v-model="formData.afterSaleUserId"  :disabled="formFields.afterSaleUserId !== 2 || isTrue" placeholder="">
              <el-option
                v-for="dict in userOptions"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #collUserId>
        <el-col :span="8">
          <el-form-item label="协作人" prop="collUserId">
            <el-select v-model="formData.collUserId"  :disabled="formFields.collUserId !== 2 || isTrue" placeholder="">
              <el-option
                v-for="dict in userOptions"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #contractBody>
        <el-col :span="24">
          <el-form-item label="合同正文" prop="contractBody">
            <el-input v-model="formData.contractBody"  :disabled="formFields.contractBody !== 2 || isTrue" type="textarea" rows="5" placeholder="" />
          </el-form-item>
        </el-col>
      </template>
      <template #contractAgreement>
        <el-col :span="24">
          <el-form-item label="合同补充协议" prop="contractAgreement">
            <el-input v-model="formData.contractAgreement"  :disabled="formFields.contractAgreement !== 2 || isTrue" type="textarea" rows="5" placeholder="" />
          </el-form-item>
        </el-col>
      </template>
      <template #other5>

      
        <!-- 子表的表单 -->
        <ContentWrap style="border: none;font-weight:700">
          产品清单
        </ContentWrap>
        <ContentWrap>
          <ContractProductForm
          :type="1"
            :formFields="formFields"
            ref="productFormRef"
            :products="formData.products"
            :disabled="disabled"
          />
        </ContentWrap>
        <ContentWrap style="border: none;font-weight:700">
          合同甲方关联单位
        </ContentWrap>
        <el-col :span="24">
          <ContentWrap>
            <ContractAAuthorizedCompanyForm :type="1" :formFields="formFields" ref="contractAAuthorizedCompanyFormRef" :data="formData.contractAAuthorizedCompanys" :contract-id="formData.id" />
          </ContentWrap>
        </el-col>
        <ContentWrap style="border: none;font-weight:700">
          合同甲方授权人信息
        </ContentWrap>
        <el-col :span="24">
          <ContentWrap>
            <ContractAAuthorizedPersonForm :type="1" :formFields="formFields" ref="contractAAuthorizedPersonFormRef" :contract-id="formData.id" />
          </ContentWrap>
        </el-col>
        <ContentWrap style="border: none;font-weight:700">
          合同乙方授权人信息
        </ContentWrap>
        <el-col :span="24">
          <ContentWrap>
            <ContractBAuthorizedPersonForm :type="1" :formFields="formFields" ref="contractBAuthorizedPersonFormRef" :userOptions="userOptions" :contract-id="formData.id" />
          </ContentWrap>
        </el-col>
      </template>
    </processForm>
    <!-- 显示在其他页面时的判断type -->
  </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 { getLimitForm } from '@/api/bpm/form'

const isTrue = ref(false)
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { proxy }: any = getCurrentInstance();
const props = defineProps({
  id: propTypes.number.def(undefined),
  type: propTypes.number.def(undefined),
})
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({ 
  other: 1,
  customerId: 1,
  no: 1,
  quotationId: 1,
  pricingUserId: 1,
  creditLimit: 1,
  creditMethod: 1,
  creditCalcCycle: 1,
  quotationTimes: 1,
  paymentTerm: 1,
  onlinePrice: 1,
  totalPrice: 1,
  other1: 1,
  customerId1: 1,
  legalPersonName: 1,
  creditNo: 1,
  regType: 1,
  actualCapital: 1,
  socialEmployeeNum: 1,
  registeredAddress: 1,
  other2: 1,
  partnerCompanyId: 1,
  bankName: 1,
  bankAccount: 1,
  legalRepresentative: 1,
  ownerUserId: 1,
  deptId: 1,
  other3: 1,
  contractType: 1,
  startTime: 1,
  endTime: 1,
  contractTerm: 1,
  statementDate: 1,
  lastPayDate: 1,
  penaltyRate: 1,
  latePaymentRate: 1,
  other4: 1,
  settleMethod: 1,
  afterSaleUserId: 1,
  collUserId: 1,
  contractBody: 1,
  contractAgreement: 1,
  other5: 1,
  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,
  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,
  expanderUserId: undefined,
  pricingUserId: 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,
  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' }],
  // 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' }],
})
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 statement = ref(new Array(31).fill(null))

/** 子表的表单 */
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 {
      formData.value = await ContractApi.getContract(type)
    } 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) {
    const contractAAuthorizedCompanyValid = await contractAAuthorizedCompanyFormRef.value.validate()
    if (!contractAAuthorizedCompanyValid) return message.warning('请完善合同甲方关联单位')
  } 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('请完善合同乙方授权人信息')
  } 

  return
  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,
    expanderUserId: undefined,
    pricingUserId: 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 {
    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.expanderUserId = quotation.expanderUserId;
    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.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;
    const customerRes = await CustomerApi.getCustomer(customerId);
    formData.value.cooperationType = customerRes.cooperationType;
    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.creditCode = customerRes.creditCode;
    formData.value.regType = customerRes.regType;
    formData.value.financingInfo = customerRes.financingInfo;
    formData.value.socialEmployeeNum = customerRes.socialEmployeeNum;
    formData.value.registeredAddress = customerRes.registeredAddress;
  } 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 onPrintContract = async (id: string) => {
  if (!id) return
  try {
    formLoading.value = true;
    const res = await ContractApi.printContract(id);
  } catch (err) {
  } finally {
    formLoading.value = false;
  }
}

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

const route = useRoute();
//获取字段权限
const getLimit = async () => {
  let data = {
    modelNodeId: route.query.taskDefinitionKey,
    processDefinitionId: route.query.processDefinitionId
  }
  let field = await getLimitForm(data)
  for(let key in formFields.value) {
    
    if(formFields.value.hasOwnProperty(key)) {
      field.fields.map( v => {
        let newKey = v.field
        if(v.field.indexOf('.') > -1) {
          newKey = v.field.split('.')[0] + v.field.split('.')[1]
        }

        if(newKey === key) formFields.value[key] =  v.permission
      })
    }
  }
}

onMounted(async () => {
  isTrue.value = !!route.query.isDetail
  formType.value = props.id || route.query.id

  if (formType.value) await open(formType.value)

  if(route.query.processDefinitionId) getLimit()

  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 获得报价列表
  quotationList.value = await QuotationApi.getSimpleQuotationList()

  //票据
  //  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>
