<template>
  <ContentWrap class="mt-10px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-row>
        

        <el-col :span="8">
          <el-form-item label="选择商机" prop="businessId">
            <el-select v-model="formData.businessId" disabled clearable placeholder="请选择商机" @change="onBusinessChange">
              <el-option
                v-for="dict in businessList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formType">
          <el-form-item label="报价单编号" prop="">
            <el-input v-model="formData.no" disabled placeholder="自动获取" />
          </el-form-item>
        </el-col>
      </el-row>
      <ContentWrap style="border: none; font-weight: 700">风控信息</ContentWrap>
      <el-row>
        <el-col :span="8">
          <el-form-item label="系统授信额度" prop="customerId">
            <el-input v-model="formData.creditAmount" disabled placeholder="自动获取" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="授信额度调整" prop="creditLimitNum">
            <el-input v-model="formData.creditLimitNum" disabled @input="changeNum" clearable placeholder="请输入授信额度调整" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最终授信额度" prop="creditLimit">
            <el-input v-model="formData.creditLimit" disabled placeholder="自动获取" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户" prop="customerId">
            <el-select v-model="formData.customerId" disabled placeholder="请选择客户" clearable @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-select v-model="formData.cooperationType" disabled filterable clearable 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="regType">
            <el-input v-model="formData.regType" disabled clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上市情况" prop="listingStatus">
            <el-input v-model="formData.listingStatus" disabled clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="融资信息" prop="financingInfo">
            <el-input v-model="formData.financingInfo" disabled clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实缴资金" prop="actualCapital">
            <el-input v-model="formData.actualCapital" disabled clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="参保人数" prop="socialEmployeeNum">
            <el-input v-model="formData.socialEmployeeNum" disabled clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="成立日期" prop="startDate">
            <el-input v-model="formData.startDate" disabled clearable  />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="企业类型" prop="enterpriseType">
            <el-input v-model="formData.enterpriseType" clearable  />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="营业状态" prop="serviceStatus">
            <el-input v-model="formData.serviceStatus" disabled  clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="被告记录" prop="defendantRecord">
            <el-radio-group v-model="formData.defendantRecord" disabled>
              <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="abnormalService">
            <el-radio-group v-model="formData.abnormalService" disabled>
              <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="equityPledge">
            <el-radio-group v-model="formData.equityPledge" disabled>
              <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="dishonestyRecord">
            <el-radio-group v-model="formData.dishonestyRecord" disabled>
              <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="financeRecord">
            <el-radio-group v-model="formData.financeRecord" disabled>
              <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="judgmentRecord">
            <el-radio-group v-model="formData.judgmentRecord" disabled>
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <ContentWrap style="border: none; font-weight: 700">需求信息</ContentWrap>

      <el-row>
        <el-col :span="8">
          <el-form-item label="合作主体" prop="partnerCompanyId">
            <el-select v-model="formData.partnerCompanyId" clearable disabled placeholder="请选择合作主体" @change="onPartnerChange">
              <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" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="formData.bankAccount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法人代表" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" disabled />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="营业执照号" prop="bBusinessLicenseNumber">
            <el-input v-model="formData.bBusinessLicenseNumber" disabled />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="营业执照" prop="businessLicense">
            <el-input v-model="formData.businessLicense" disabled />
          </el-form-item>
        </el-col>

      </el-row>
      
      <el-row>
      <el-col :span="8">
        <el-form-item label="归属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
             disabled
            :data="deptTree"
            :props="defaultProps"
            filterable
            check-strictly
            node-key="id"
            placeholder="请选择归属部门"
          />
        </el-form-item>
        
      </el-col>

      <el-col :span="8">
      <el-form-item label="商机负责人" prop="ownerUserId">
        <el-select v-model="formData.ownerUserId" 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="expanderUserId">
        <el-select v-model="formData.expanderUserId" 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="pricingUserId">
        <el-select v-model="formData.pricingUserId" 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="signUserId">
        <el-select v-model="formData.signUserId" 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="signPhoneNumber">
          <el-input v-model="formData.signPhoneNumber" placeholder="请输入签约人联系电话" />
        </el-form-item>
      </el-col>
        <el-col :span="8">
        <el-form-item label="签约人Email" prop="signEmail">
          <el-input v-model="formData.signEmail" placeholder="请输入签约人Email" />
        </el-form-item>
      </el-col>
        <el-col :span="8">
        <el-form-item label="签约人微信" prop="signWechat">
          <el-input v-model="formData.signWechat" 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="creditMethod">
          <el-select v-model="formData.creditMethod" disabled placeholder="请选择授信方式">
            <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-select v-model="formData.creditCalcCycle" disabled placeholder="请选择授信计算周期">
            <el-option
              v-for="dict in getIntDictOptions('credit_calc_cycle')"
              :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="creditLimit">
          <el-input v-model="formData.creditLimit" disabled placeholder="请输入授信额度" />
        </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-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="线上总金额" prop="onlinePrice">
            <el-input
              disabled
              v-model="formData.onlinePrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="线下总金额" prop="offlinePrice">
            <el-input
              disabled
              v-model="formData.offlinePrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总金额" prop="totalPrice">
            <el-input
              disabled
              v-model="formData.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="报价产品关联" name="quotationProduct">
        <QuotationProductForm ref="quotationProductFormRef" :products="formData.products" :quotation-id="formData.id" :business-id="formData.businessId" :billTemplateId="formData.invoiceTemplateId" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</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 QuotationProductForm from './components/QuotationProductDetail.vue'
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 props = defineProps({
  id: propTypes.number.def(undefined),
})
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, // 营业执照
  creditAmount: undefined,
  creditLimitNum: undefined,
})
const formRules = reactive({
  // 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' }],
  // actualCapital: [{ required: true, message: '实缴资金不能为空', trigger: 'blur' }],
  // socialEmployeeNum: [{ required: true, message: '参保人数不能为空', trigger: 'blur' }],
  // defendantRecord: [{ required: true, message: '被告记录不能为空', trigger: 'blur' }],
  // abnormalService: [{ required: true, message: '经营异常不能为空', trigger: 'blur' }],
  // equityPledge: [{ required: true, message: '股权出质不能为空', trigger: 'blur' }],
  // dishonestyRecord: [{ required: true, message: '失信记录不能为空', trigger: 'blur' }],
  // financeRecord: [{ required: true, message: '融资记录不能为空', trigger: 'blur' }],
  // judgmentRecord: [{ required: true, message: '被执行记录不能为空', trigger: 'blur' }],
  // paymentTerm: [{ required: true, message: '账期不能为空', trigger: 'change' }],
  // partnerCompanyId: [{ required: true, message: '合作主体不能为空', trigger: 'change' }],
  // creditMethod: [{ required: true, message: '授信方式不能为空', trigger: 'change' }],
  // creditCalcCycle: [{ required: true, message: '授信计算周期不能为空', 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.actualCapital = customerRes.actualCapital
    formData.value.socialEmployeeNum = customerRes.socialEmployeeNum
    formData.value.startDate = customerRes.startDate
    formData.value.actualCapital = customerRes.actualCapital
    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 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 changeNum = (val) => {
  formData.value.creditLimit = (Number(val) + (formData.value.creditAmount || 0)).toFixed(2)
}
/** 打开弹窗 */
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()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await quotationProductFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'quotationProduct'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as QuotationVO
    // 拼接子表的数据
    data.quotationProducts = quotationProductFormRef.value.getData()
    if (!formType.value) {
      await QuotationApi.createQuotation(data)
      message.success(t('common.createSuccess'))
    } else {
      await QuotationApi.updateQuotation(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 = {
    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/QuotationDetail.vue:651 props.id', 'color: #007acc;', props.id, route.query.id);
  formType.value = props.id ||  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.getSelfSimpleBusinessList()
  // 获得部门树
  deptTree.value = handleTree(await DeptApi.getSimpleDeptList())
  const org = await ContractApi.getOrg({
    pageNo: 1,
    pageSize: 1000
  })
  orgList.value = org.list
});
</script>