<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="报价单编号" prop="no">
        <el-input v-model="formData.no" placeholder="请输入报价单编号" />
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select v-model="formData.customerId" placeholder="请选择客户">
          <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="选择商机" prop="businessId">
        <el-select v-model="formData.businessId" 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-form-item label="票据模板" prop="invoiceTemplateId">
        <el-select v-model="formData.invoiceTemplateId" placeholder="请选择票据模板">
          <el-option
            v-for="dict in userOptions"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商机负责人" prop="ownerUserId">
        <el-select v-model="formData.ownerUserId" placeholder="请选择商机负责人">
          <el-option
            v-for="dict in userOptions"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="拓展人" prop="expanderUserId">
        <el-select v-model="formData.expanderUserId" placeholder="请选择拓展人">
          <el-option
            v-for="dict in userOptions"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="方案报价人" prop="pricingUserId">
        <el-select v-model="formData.pricingUserId" placeholder="请选择方案报价人">
          <el-option
            v-for="dict in userOptions"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报价签约人" prop="signUserId">
        <el-select v-model="formData.signUserId" placeholder="请选择报价签约人">
          <el-option
            v-for="dict in userOptions"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签约人联系电话" prop="signPhoneNumber">
        <el-input v-model="formData.signPhoneNumber" placeholder="请输入签约人联系电话" />
      </el-form-item>
      <el-form-item label="签约人Email" prop="signEmail">
        <el-input v-model="formData.signEmail" placeholder="请输入签约人Email" />
      </el-form-item>
      <el-form-item label="签约人微信" prop="signWechat">
        <el-input v-model="formData.signWechat" placeholder="请输入签约人微信" />
      </el-form-item>
      <el-form-item label="合同总金额" prop="totalPrice">
        <el-input v-model="formData.totalPrice" placeholder="" disabled="false" />
      </el-form-item>
      <el-form-item label="账期" prop="paymentTerm">
        <el-select v-model="formData.paymentTerm" 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-form-item label="授信方式" prop="creditMethod">
        <el-select v-model="formData.creditMethod" 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-form-item label="授信计算周期" prop="creditCalcCycle">
        <el-select v-model="formData.creditCalcCycle" 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-form-item label="授信额度" prop="creditLimit">
        <el-input v-model="formData.creditLimit" placeholder="请输入授信额度" />
      </el-form-item>
      <el-form-item label="合作主体" prop="partnerCompanyId">
        <el-select v-model="formData.partnerCompanyId" placeholder="请选择合作主体">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="归属部门" prop="deptId">
        <el-tree-select
          v-model="formData.deptId"
          :data="deptTree"
          :props="defaultProps"
          filterable
          check-strictly
          node-key="id"
          placeholder="请选择归属部门"
        />
      </el-form-item>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="报价产品关联" name="quotationProduct">
        <QuotationProductForm ref="quotationProductFormRef" :quotation-id="formData.id" :business-id="formData.businessId" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</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 QuotationProductForm from './components/QuotationProductForm.vue'
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'

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

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

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
})
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' }]
})
const formRef = ref() // 表单 Ref

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

const onBusinessChange = async (businessId: string) => {
  if (!businessId) return
  try {
    const res = await BusinessApi.getBusiness(businessId);
    formData.creditLimit = res.creditLimit; // 保存详情信息
    formData.ownerUserId = res.ownerUserId; // 保存详情信息
    formData.paymentTerm = res.paymentTerm;
    formData.creditMethod = res.creditMethod;
    formData.creditCalcCycle = res.creditCalcCycle;
  } catch (err) {
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await QuotationApi.getQuotation(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()

  businessList.value = await BusinessApi.getSimpleBusinessList()
  // 获得部门树
  deptTree.value = handleTree(await DeptApi.getSimpleDeptList())
}
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 === 'create') {
      await QuotationApi.createQuotation(data)
      message.success(t('common.createSuccess'))
    } else {
      await QuotationApi.updateQuotation(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
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()
}
</script>