<template>
  <ContentWrap class="mt-10px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="商机名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入商机名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="负责人" prop="ownerUserId">
            <el-select
              v-model="formData.ownerUserId"
              :disabled="formType !== 'create'"
              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>
        <el-col :span="8">
          <el-form-item label="需求提交人" prop="requestorUserId">
            <el-select
              v-model="formData.requestorUserId"
              :disabled="formType !== 'create'"
              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>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              :disabled="formData.customerDefault"
              v-model="formData.customerId"
              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>

        <el-col :span="8">
          <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-col>
        <el-col :span="8">
          <el-form-item label="商机状态组" prop="statusTypeId">
            <el-select
              v-model="formData.statusTypeId"
              placeholder="请选择商机状态组"
              clearable
              class="w-1/1"
              :disabled="formType !== 'create'"
            >
              <el-option
                v-for="item in statusTypeList"
                :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="dealTime">
            <el-date-picker
              v-model="formData.dealTime"
              type="date"
              value-format="x"
              placeholder="选择预计成交日期"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售阶段" prop="saleStage">
            <el-select v-model="formData.saleStage" placeholder="请选择销售阶段">
              <el-option
                v-for="dict in getIntDictOptions('sale_stage')"
                :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="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-col>
        <el-col :span="8">
          <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-col>
        <el-col :span="8">
          <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-col>
        <el-col :span="8">
          <el-form-item label="授信额度" prop="creditLimit">
            <el-input v-model="formData.creditLimit" placeholder="请输入授信额度" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否技术需求支持" prop="techSupport">
            <el-radio-group v-model="formData.techSupport">
              <el-radio
                v-for="dict in getBoolDictOptions('tech_support')"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表的表单 -->
      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="产品清单" name="product">
            <BusinessProductForm
              ref="productFormRef"
              v-model="formData.products"
              :disabled="disabled"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <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-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
  </ContentWrap>

</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE, getBoolDictOptions } from '@/utils/dict'
import * as BusinessApi from '@/api/crm/business'
import * as BusinessStatusApi from '@/api/crm/business/status'
import * as CustomerApi from '@/api/crm/customer'
import * as UserApi from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'
import { useUserStore } from '@/store/modules/user'
import { defaultProps, handleTree } from '@/utils/tree'
import BusinessProductForm from './components/BusinessProductForm.vue'
import { erpPriceMultiply, erpPriceInputFormatter } from '@/utils'
const deptTree = ref() // 部门树形结构
const { proxy }: any = getCurrentInstance();
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  customerId: undefined,
  followUpStatus: undefined,
  contactLastTime: undefined,
  contactNextTime: undefined,
  ownerUserId: undefined,
  deptId: undefined,
  requestorUserId: undefined,
  statusTypeId: undefined,
  statusId: undefined,
  endStatus: undefined,
  dealTime: undefined,
  onlinePrice: undefined,
  offlinePrice: undefined,
  totalProductPrice: undefined,
  totalPrice: undefined,
  saleStage: undefined,
  paymentTerm: undefined,
  creditMethod: undefined,
  creditCalcCycle: undefined,
  creditLimit: undefined,
  techSupport: undefined,
  products: [],
})
const formRules = reactive({
  name: [{ required: true, message: '商机名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  ownerUserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  statusTypeId: [{ required: true, message: '商机状态组不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const statusTypeList = ref([]) // 商机状态类型列表
const customerList = ref([]) // 客户列表的数据

/** 子表的表单 */
const subTabsName = ref('product')
const productFormRef = ref()

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value.products,
  (val) => {
    if (!val) {
      return
    }
    
    const totalOnlinePrice = val.products.reduce((prev, curr) => prev + curr.onlinePrice, 0)
    const totalOfflinePrice = val.products.reduce((prev, curr) => prev + curr.offlinePrice, 0)
    // 赋值
    formData.value.onlinePrice = totalOnlinePrice
    formData.value.offlinePrice = totalOfflinePrice
    formData.value.totalPrice = totalOnlinePrice + totalOfflinePrice
  },
  { deep: true }
)
/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number, contactId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BusinessApi.getBusiness(id)
    } finally {
      formLoading.value = false
    }
  } else {
    if (customerId) {
      formData.value.customerId = customerId
      formData.value.customerDefault = true // 默认客户的选择，不允许变
    }
    // 自动关联 contactId 联系人编号
    if (contactId) {
      formData.value.contactId = contactId
    }
  }

  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.ownerUserId = useUserStore().getUser.id
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 修改前：
  // console.log('%csrc/views/crm/business/BusinessForm.vue:346 productFormRef.value.formData', 'color: #007acc;', productFormRef.value);
  // formData.value.products = productFormRef.value.formData;
  
  // 修改为：
  if (!productFormRef.value) return;
  const valid = await productFormRef.value.validate();
  formData.value.products = valid

  if (!valid) return;
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BusinessApi.BusinessVO
    if (formType.value === 'create') {
      await BusinessApi.createBusiness(data)
      message.success(t('common.createSuccess'))
    } else {
      await BusinessApi.updateBusiness(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    customerId: undefined,
    ownerUserId: undefined,
    statusTypeId: undefined,
    dealTime: undefined,
    totalPrice: undefined,
    products: [],
    contactId: undefined,
    customerDefault: false
  }
  formRef.value?.resetFields()
}
/** 初始化 */
const { params } = useRoute()
onMounted(async () => {
  formType.value = params.id
    // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 加载商机状态类型列表
  statusTypeList.value = await BusinessStatusApi.getBusinessStatusTypeSimpleList()
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
    // 获得部门树
    deptTree.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>
