<template>
  <ContentWrap class="mt-10px">
    <processForm
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :fields="formFields"
      label-width="120px"
      v-loading="formLoading"
    >
      <template #customerId>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <SelectComponent :customerList="customerList" :disabled="formFields.customerId !== 2 || isTrue" placeholder="请选择客户名称" v-model="formData.customerId"  />
          </el-form-item>
        </el-col>
      </template>
      <template #deptId>
        <el-col :span="8">
          <el-form-item label="所属部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptTree"
              :props="defaultProps"
              :disabled="formFields.deptId !== 2 || isTrue"
              filterable
              check-strictly
              node-key="id"
              placeholder="请选择所属部门"
              @change="getSimpleUserList"
            />
          </el-form-item>
        </el-col>
      </template>
      <template #contactId>
        <el-col :span="8">
          <el-form-item label="反馈联系人" prop="contactId">
            <el-select
              v-model="formData.contactId"
              clearable
              :disabled="formFields.contactId !== 2 || isTrue"
              filterable
              lable-key="name"
              placeholder="请选择反馈人"
              value-key="id"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #mobile>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="mobile">
            <el-input v-model="formData.mobile" :disabled="formFields.mobile !== 2 || isTrue" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </template>
      <template #email>
        <el-col :span="8">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="formData.email" :disabled="formFields.email !== 2 || isTrue" placeholder="请输入电子邮箱" />
          </el-form-item>
        </el-col>
      </template>
      <template #feedbackType>
        <el-col :span="8">
          <el-form-item label="反馈类型" prop="feedbackType">
            <el-select v-model="formData.feedbackType" :disabled="formFields.feedbackType !== 2 || isTrue" placeholder="请选择反馈类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_FEEDBACK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #feedbackLevel>
        <el-col :span="8">
          <el-form-item label="反馈级别" prop="feedbackLevel">
            <el-select v-model="formData.feedbackLevel" :disabled="formFields.feedbackLevel !== 2 || isTrue" filterable clearable placeholder="请选择反馈级别">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_FEEDBACK_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #urgencyLevel>
        <el-col :span="8">
          <el-form-item label="紧急程度" prop="urgencyLevel">
            <el-select v-model="formData.urgencyLevel" :disabled="formFields.urgencyLevel !== 2 || isTrue" filterable clearable placeholder="请选择紧急程度">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_URGENCY_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </template>
      <template #feedbackTime>
        <el-col :span="8">
          <el-form-item label="反馈时间" prop="feedbackTime">
            <el-date-picker
              v-model="formData.feedbackTime"
              type="date"
              :disabled="formFields.feedbackTime !== 2 || isTrue"
              value-format="x"
              style="width: 100%"
              placeholder="选择反馈时间"
            />
          </el-form-item>
        </el-col>
      </template>
      <template #relatedPerson>
        <el-col :span="8">
          <el-form-item label="当事人用户" prop="relatedPerson">
            <el-select
            :disabled="formFields.relatedPerson !== 2 || isTrue"
              v-model="formData.relatedPerson"
              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="customerFeedbackCount">
            <el-input v-model="formData.customerFeedbackCount" oninput = "value=value.replace(/[^\d]/g,'')" placeholder="请输入客户累计计数" />
          </el-form-item>
          </el-col>
        
        <el-col :span="8">
          <el-form-item label="当事人累计计数" prop="relatedPersonFeedbackCount">
            <el-input v-model="formData.relatedPersonFeedbackCount" oninput = "value=value.replace(/[^\d]/g,'')" placeholder="请输入当事人累计计数" />
          </el-form-item>
          </el-col> -->
      </template>
      <template #feedbackCompanyEntity>
        <el-col :span="24">
          <el-form-item label="反馈主体" prop="feedbackCompanyEntity">
            <el-input type="textarea" :disabled="formFields.feedbackCompanyEntity !== 2 || isTrue" :rows="5" v-model="formData.feedbackCompanyEntity" placeholder="请输入反馈主体" />
          </el-form-item>
        </el-col>
      </template>
      <template #feedbackContent>
        <el-col :span="24">
          <el-form-item label="反馈内容" prop="feedbackContent">
            <el-input type="textarea" :disabled="formFields.feedbackContent !== 2 || isTrue" :rows="5" v-model="formData.feedbackContent" placeholder="请输入反馈主体" />
          </el-form-item>
        </el-col>
      </template>
      <template #attachment>
        <el-col :span="24">
          <el-form-item label="附件" prop="attachment">
              <UploadFile v-model="formData.attachment" :disabled="formFields.attachment !== 2 || isTrue" :limit="1" :fileType="['doc','docx']"/>
          </el-form-item>
        </el-col>
      </template>
        
    </processForm>
    <!-- <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, DICT_TYPE } from '@/utils/dict'
import { CustomerFeedbackApi, CustomerFeedbackVO } from '@/api/crm/feedback'
import * as CustomerApi from '@/api/crm/customer'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { getLimitForm } from '@/api/bpm/form'

/** 客户反馈 表单 */
defineOptions({ name: 'CustomerFeedbackForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { proxy }: any = getCurrentInstance();

const isTrue = ref(false)
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const userList = ref([]) //用户列表
const deptTree = ref<Tree[]>([]) // 部门树形结构化
const customerList = ref([]) // 客户列表的数据
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formFields = ref({ 
  customerId: 1,
  deptId: 1,
  contactId: 1,
  mobile: 1,
  email: 1,
  feedbackType: 1,
  feedbackLevel: 1,
  urgencyLevel: 1,
  feedbackTime: 1,
  relatedPerson: 1,
  feedbackCompanyEntity: 1,
  feedbackContent: 1,
  attachment: 1,
})
const formData = ref({
  id: undefined,
  customerId: undefined,
  contactId: undefined,
  mobile: undefined,
  email: undefined,
  feedbackType: undefined,
  feedbackLevel: undefined,
  urgencyLevel: undefined,
  feedbackTime: undefined,
  relatedPerson: undefined,
  deptId: undefined,
  customerFeedbackCount: undefined,
  relatedPersonFeedbackCount: undefined,
  feedbackCompanyEntity: undefined,
  feedbackContent: undefined,
  attachment: undefined,
})
const formRules = reactive({
  customerId: [{ required: true, message: '客户ID不能为空', trigger: 'blur' }],
  contactId: [{ required: true, message: '反馈联系人ID不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  feedbackType: [{ required: true, message: '反馈类型不能为空', trigger: 'change' }],
  feedbackLevel: [{ required: true, message: '反馈级别不能为空', trigger: 'blur' }],
  urgencyLevel: [{ required: true, message: '紧急程度不能为空', trigger: 'blur' }],
  feedbackTime: [{ required: true, message: '反馈时间不能为空', trigger: 'blur' }],
  feedbackCompanyEntity: [{ required: true, message: '反馈主体不能为空', trigger: 'blur' }],
  feedbackContent: [{ required: true, message: '反馈内容不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id?: number) => {
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustomerFeedbackApi.getCustomerFeedback(id)
      getSimpleUserList(formData.value.deptId)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 选择部门后，查询用户列表 */
const getSimpleUserList = async (val) => {
  const feedbackDeptId = val;
  if (feedbackDeptId) {
    // 加载用户
    userList.value = await UserApi.getSimpleUserList(feedbackDeptId);
  } else {
    userList.value = [];
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerFeedbackVO
    if (!formType.value) {
      await CustomerFeedbackApi.createCustomerFeedback(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerFeedbackApi.updateCustomerFeedback(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    goBack()
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const goBack = ()=> {
  proxy.$router.go(-1)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    contactId: undefined,
    mobile: undefined,
    email: undefined,
    feedbackType: undefined,
    feedbackLevel: undefined,
    urgencyLevel: undefined,
    feedbackTime: undefined,
    relatedPerson: undefined,
    deptId: undefined,
    customerFeedbackCount: undefined,
    relatedPersonFeedbackCount: undefined,
    feedbackCompanyEntity: undefined,
    feedbackContent: undefined,
    attachment: undefined,
  }
  formRef.value?.resetFields()
}

//获取字段权限
const getLimit = async () => {
  let data = {
    modelNodeId: route.query.taskDefinitionKey,
    processDefinitionId: route.query.processDefinitionId
  }
  let field = await getLimitForm(data)
  for(let key in formFields.value) {
    
    if(formFields.value.hasOwnProperty(key)) {
      field.fields.map( v => {
        let newKey = v.field
        if(v.field.indexOf('.') > -1) {
          newKey = v.field.split('.')[0] + v.field.split('.')[1]
        }

        if(newKey === key) formFields.value[key] =  v.permission
      })
    }
  }
}

const route = useRoute();
onMounted(async() => {
  isTrue.value = !!route.query.isDetail
  formType.value = route.query.id
  
  if (formType.value) await open(formType.value)

  if(route.query.processDefinitionId) getLimit()
  // 获得客户列表
  customerList.value = await CustomerApi.getSelfCustomerSimpleList()
  const deptData = await DeptApi.getSimpleDeptList()
  deptTree.value = handleTree(deptData) // 转换成树形结构
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
})
</script>