<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="status">
            <el-select v-model="formData.status" clearable placeholder="请选择模板状态">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </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"
              :products="formData.products"
              :disabled="disabled"
              @success="setList"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
    </el-form>
    <div style="text-align: right">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="goBack">取 消</el-button>
    </div>
  </ContentWrap>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE, getBoolDictOptions } from '@/utils/dict'
import  { BillTemplateApi, BillTemplateVO } from '@/api/crm/billtemplate'
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/index.vue'
import { erpPriceMultiply, erpPriceInputFormatter } from '@/utils'
const { proxy }: any = getCurrentInstance();
const deptTree = ref() // 部门树形结构

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()

const setList = (newProducts) => {
  formData.value.productItems = newProducts;
};
/** 打开弹窗 */
const open = async (id?: number, customerId?: number) => {
  dialogVisible.value = true
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BillTemplateApi.getBillTemplate(id)
      formData.value.products = formData.value.productItems
    } finally {
      formLoading.value = false
    }
  } else {
    if (customerId) {
      formData.value.customerId = customerId
      formData.value.customerDefault = true // 默认客户的选择，不允许变
    }
    
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // await productFormRef.value.validate()
  // console.log(formData.value,444); // 检查 ref 的值
  await nextTick(() => {
    if (productFormRef.value) {
      productFormRef.value.validate();
    }
  });
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BillTemplateApi.BillTemplateVO
    if (!formType.value) {
      await BillTemplateApi.createBillTemplate(data)
      message.success(t('common.createSuccess'))
    } else {
      await BillTemplateApi.updateBillTemplate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    goBack()

  } finally {
    formLoading.value = false
  }
}

const { push } = useRouter()
const goBack = ()=> {
  push({ name: 'BillTemplate' })
}

/** 重置表单 */
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 route = useRoute();
onMounted(async () => {
  const customerId = route.query.customerId;
  formType.value = route.query.id;

  if (formType.value) open(formType.value, customerId)
});
</script>
