<template>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="终止日期" prop="terminationDate">
            <el-date-picker
              v-model="formData.terminationDate"
              type="date"
               :disabled="!!type"
              value-format="YYYY-MM-DD"
              placeholder="请选择终止日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终止原因" prop="terminationReason">
            <el-radio-group v-model="formData.terminationReason" :disabled="!!type">
              <el-radio :label="1">合同到期</el-radio>
              <el-radio :label="2">甲方违反协议</el-radio>
              <el-radio :label="3">乙方不可抗力</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
      <el-col :span="24">
        <el-form-item label="终止说明" prop="note">
          <el-input v-model="formData.note" :disabled="!!type" type="textarea" :row="5" placeholder="必须确保账款已全部回收" />
        </el-form-item>
      </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
   
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { QuotationApi, QuotationVO } from '@/api/crm/quotation'
import { defaultProps, handleTree } from '@/utils/tree'
import { BillTemplateApi, BillTemplateVO } from '@/api/crm/billtemplate'
import * as ContractApi from '@/api/crm/contract'
import * as CustomerApi from '@/api/crm/customer'
import * as UserApi from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'
import * as BusinessApi from '@/api/crm/business'
import { propTypes } from '@/utils/propTypes'

/** CRM 方案报价 表单 */
defineOptions({ name: 'QuotationForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const customerList = ref([]) // 客户列表的数据
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const templateOptions = ref([]) 
const businessList = ref([]) 
const deptTree = ref() // 部门树形结构
const deptList = ref() // 部门
const orgList = ref([])

const invoiceTemplateList = ref([]) 
const { proxy }: any = getCurrentInstance();

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  no: undefined,
  customerId: undefined,
  businessId: undefined,
  invoiceTemplateId: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  ownerUserId: undefined,
  expanderUserId: undefined,
  pricingUserId: undefined,
  signUserId: undefined,
  signPhoneNumber: undefined,
  signEmail: undefined,
  signWechat: undefined,
  paymentTerm: undefined,
  creditMethod: undefined,
  creditCalcCycle: undefined,
  creditLimit: undefined,
  partnerCompanyId: undefined,
  deptId: undefined,
  creator: undefined,
  createTime: undefined,
  updater: undefined,
  onlinePrice: undefined,
  offlinePrice: undefined,
  totalPrice: undefined,
  cooperationType: undefined, // 合作类型
  companyType: undefined, // 公司类型
  listingStatus: undefined, // 上市情况
  financingInfo: undefined, // 融资信息
  paidInCapital: undefined, // 实缴资金
  insuredCount: undefined, // 参保人数
  establishmentDate: undefined, // 成立日期
  enterpriseType: undefined, // 企业类型
  businessStatus: undefined, // 营业状态
  defendantRecord: undefined, // 被告记录
  businessAbnormal: undefined, // 经营异常
  equityPledge: undefined, // 股权出质
  dishonestRecord: undefined, // 失信记录
  financingRecord: undefined, // 融资记录
  enforcementRecord: undefined, // 被执行记录
  bBankName: undefined, // 开户行
  bBankAccount: undefined, // 银行账号
  bLegalRepresentative: undefined, // 法人代表
  bBusinessLicenseNumber: undefined, // 营业执照号
  bBusinessLicense: undefined // 营业执照
})
const formRules = reactive({
  // cooperationType: [{ required: true, message: '合作类型不能为空', trigger: 'change' }],
  // no: [{ required: true, message: '报价单编号不能为空', trigger: 'blur' }],
  // customerId: [{ required: true, message: '客户id不能为空', trigger: 'change' }],
  // businessId: [{ required: true, message: '商机编号不能为空', trigger: 'change' }],
  // invoiceTemplateId: [{ required: true, message: '票据模板Id不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('quotationProduct')
const quotationProductFormRef = ref()

const onBusinessChange = async (businessId: string) => {
  if (!businessId) return
  try {
    formLoading.value = true;
    const res = await BusinessApi.getBusiness(businessId);
    formData.value.customerId = res.customerId; 
    formData.value.creditLimit = res.creditLimit; // 保存详情信息
    formData.value.ownerUserId = res.ownerUserId; // 保存详情信息
    formData.value.paymentTerm = res.paymentTerm;
    formData.value.creditMethod = res.creditMethod;
    formData.value.creditCalcCycle = res.creditCalcCycle;
    formData.value.deptId = res.deptId;
    formData.value.offlinePrice = res.offlinePrice; 
    formData.value.onlinePrice = res.onlinePrice; 
    formData.value.totalPrice = res.totalPrice;
     // 🔁 自动加载客户详情
     await onCustomerChange(res.customerId);
  } catch (err) {
  } finally {
    formLoading.value = false;
  }
}

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.businessStatus = customerRes.businessStatus;
    formData.value.defendantRecord = customerRes.defendantRecord;
    formData.value.businessAbnormal = customerRes.businessAbnormal;
    formData.value.equityPledge = customerRes.equityPledge;
    formData.value.dishonestRecord = customerRes.dishonestRecord;
    formData.value.financingRecord = customerRes.financingRecord;
    formData.value.enforcementRecord = customerRes.enforcementRecord;
  } catch (err) {
    console.error('获取客户详情失败:', err);
  } finally {
    formLoading.value = false;
  }
}


/** 打开弹窗 */
const open = async (type: string) => {
  formType.value = type
  // 修改时，设置数据
  if (type) {
    formLoading.value = true
    try {
      formData.value = await QuotationApi.getQuotation(type)
    } finally {
      formLoading.value = false
    }
  }
  
  deptList.value = await DeptApi.getSimpleDeptList()
  // 获得用户列表
  invoiceTemplateList.value = await BillTemplateApi.getSimpleList()
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

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

</script>