<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="cooperationType">
            <el-select v-model="formData.cooperationType" disabled filterable placeholder="请选择合作类型" class="w-1/1">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_COOPERATION_TYPE)"
                :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="">
            <el-input v-model="formData.regType" disabled placeholder="自动获取" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上市情况" prop="customerId">
            <el-select v-model="formData.customerId" placeholder="请选择上市情况" disabled @change="onCustomerChange">
              <el-option
                    v-for="item in customerList"
                    :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="cooperationType">
            <el-input v-model="formData.cooperationType" disabled />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="融资信息" prop="companyType">
            <el-select v-model="formData.customerId" placeholder="请选择融资信息" disabled @change="onCustomerChange">
              <el-option
                    v-for="item in customerList"
                    :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="paidInCapital">
            <el-input v-model="formData.actualCapital" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="参保人数" prop="insuredCount">
            <el-input v-model="formData.socialEmployeeNum" disabled />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="被告记录" prop="defendantRecord">
            <el-radio-group v-model="formData.defendantRecord" :disabled="true">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="经营异常" prop="abnormalService">
            <el-radio-group v-model="formData.abnormalService" :disabled="true">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="股权出质" prop="equityPledge">
            <el-radio-group v-model="formData.equityPledge" :disabled="true">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="失信记录" prop="dishonestyRecord">
            <el-radio-group v-model="formData.dishonestyRecord" :disabled="true">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="融资记录" prop="financeRecord">
            <el-radio-group v-model="formData.financeRecord" :disabled="true">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="被执行记录" prop="judgmentRecord">
            <el-radio-group v-model="formData.judgmentRecord" :disabled="true">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
       
      <el-col :span="8">
        <el-form-item label="初始额度" prop="signPhoneNumber">
          <el-input v-model="formData.signPhoneNumber" placeholder="请输入初始额度" disabled />
        </el-form-item>
      </el-col>
        <el-col :span="8">
        <el-form-item label="目前额度" prop="beforeAmount">
          <el-input v-model="formData.beforeAmount" placeholder="请输入目前额度" disabled />
        </el-form-item>
      </el-col>
        <el-col :span="8">
        <el-form-item label="签约主体" prop="signWechat">
          <el-select v-model="formData.partnerCompanyId" disabled placeholder="请选择签约主体" @change="onPartnerChange">
              <el-option
                v-for="dict in orgList"
                :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="changeAmount">
          <el-input v-model="formData.changeAmount" :disabled="!!type" placeholder="请输入调整金额（元）" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="最终额度" prop="afterAmount">
          <el-input v-model="formData.afterAmount" :disabled="!!type" placeholder="请输入最终额度" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="调整金额截止日期" prop="establishmentDate">
            <el-date-picker
              v-model="formData.lastPayDate"
              type="date"
               :disabled="!!type"
              value-format="x"
              placeholder="请选择调整金额截止日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      <el-col :span="24">
        <el-form-item label="调额说明" prop="note">
          <el-input v-model="formData.note" type="textarea" :disabled="!!type" :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 props = defineProps({
  type: propTypes.string.def('')
})
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 onPartnerChange = async (id: string) => {
  if (!id) return
  try {
    formLoading.value = true;
    const res = await DeptApi.getDept(id);
    formData.value.bBankName = res.bankName;
    formData.value.bBankAccount = res.bankAccount;
    formData.value.bLegalRepresentative = res.legalRepresentative;
    formData.value.bBusinessLicenseNumber = res.businessLicenseNumber;
    formData.value.bBusinessLicense = res.businessLicense;
  } catch (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 方法，用于打开弹窗


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    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,
    startTime: undefined,
    totalPrice: undefined,
    paymentTerm: undefined,
    creditMethod: undefined,
    creditCalcCycle: undefined,
    creditLimit: undefined,
    partnerCompanyId: undefined,
    deptId: undefined,
    creator: undefined,
    createTime: undefined,
    updater: undefined
  }
  formRef.value?.resetFields()
}

// const route = useRoute();
// onMounted(async () => {
//   console.log('%csrc/views/crm/quotation/QuotationForm.vue:596 route', 'color: #007acc;', route);
//   formType.value = route.query.id;

//   if (formType.value) open(formType.value)

//   // 获得客户列表
//   customerList.value = await CustomerApi.getCustomerSimpleList()
//   // 获得用户列表
//   userOptions.value = await UserApi.getSimpleUserList()
//   //票据
//    const data = await BillTemplateApi.getBillTemplatePage({
//     pageNo: 1,
//     pageSize: 1000,
//   })
//   templateOptions.value = data.list
//   businessList.value = await BusinessApi.getSimpleBusinessList()
//   // 获得部门树
//   deptTree.value = handleTree(await DeptApi.getSimpleDeptList())
//   const org = await ContractApi.getOrg({
//     pageNo: 1,
//     pageSize: 1000
//   })
//   orgList.value = org.list
// });
</script>