<!--
 * @Description: 考核指标管理新建/编辑/详情页面
 * @Author: 李亚光
 * @Date: 2023-09-14
 -->
<script lang="ts" setup name="RuleProxyHandler">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import { getDictByCode } from '@/api/system/dict'
import { uploadApi } from '@/api/common'
import { addProxy, editProxy } from '@/api/home/rule/proxy'
const $route = useRoute()
const $router = useRouter()
// 对话框类型：create,update
const dialogStatus = ref('create')
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 表单实例对象
const ruleFormRef = ref()
// 表单对象
const ruleForm = ref({
  quotaType: '', // 考核指标类型
  quotaProject: '', // 考核指标项目
  quotaNo: '', // 编号
  priIndicators: '', // 一级考核指标
  assDept: '', // 指标考核责任人
  dataSource: '', // 数据来源
  score: '', // 考核分值
  valType: '1', // 指标值类型
  remarks: '', // 备注
  fileId: '', // 上传文件
  id: '',
  ruleDesc: '',
})
// 表单验证规则
const rules = ref<FormRules>({
  quotaProject: [{ required: true, message: '考核指标项目必选', trigger: ['blur', 'change'] }],
  quotaType: [{ required: true, message: '考核指标类型必选', trigger: ['blur', 'change'] }],
  priIndicators: [{ required: true, message: '一级考核指标必填', trigger: ['blur', 'change'] }],
  assDept: [{ required: true, message: '指标责任考核单位必填', trigger: ['blur', 'change'] }],
  dataSource: [{ required: true, message: '数据来源必选', trigger: ['blur', 'change'] }],
  valType: [{ required: true, message: '指标值类型必选', trigger: ['blur', 'change'] }],
  score: [{ required: true, message: '考核分值必填', trigger: ['blur', 'change'] }],
  ruleDesc: [{ required: true, message: '指标计算规则必填', trigger: ['blur', 'change'] }],
})
// 考核分值区间
const score1 = ref()
const score2 = ref()
watch([score1, score2], (newVal) => {
  if (newVal[0] && newVal[1]) {
    ruleFormRef.value?.clearValidate('score')
    ruleForm.value.score = `${score1.value}-${score2.value}`
  }
})
watch(() => ruleForm.value.valType, (newVal) => {
  if (newVal === '1' && !ruleForm.value.score.includes('-')) {
    ruleForm.value.score = ''
  }
  else if ((newVal === '2' || newVal === '3') && ruleForm.value.score.includes('-')) {
    score1.value = ''
    score2.value = ''
    ruleForm.value.score = ''
  }
})
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('file', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        ruleForm.value.fileId = ruleForm.value.fileId ? `${ruleForm.value.fileId},${res.data.fileName}` : res.data.fileName
        // 重置当前验证
        ruleFormRef.value?.clearValidate('fileId')
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        loading.close()
      }
    }).catch(() => {
      loading.close()
    })
  }
}
// 上传
const upload = () => {
  fileRef.value.click()
}
// 删除上传的文件
const deleteFile = (fileName: string) => {
  const data = ruleForm.value.fileId.split(',')
  const filterData = data.filter(item => item !== fileName)
  ruleForm.value.fileId = filterData.length ? filterData.join(',') : ''
}
// 编辑
const update = () => {
  editProxy({ ...ruleForm.value }).then((res) => {
    ElMessage.success('操作成功')
    $router.go(-1)
  })
}
// 新增
const create = () => {
  addProxy({ ...ruleForm.value }).then((res) => {
    ElMessage.success('操作成功')
    $router.go(-1)
  })
}
// 保存
const saveData = (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  formEl.validate().then((res) => {
    ElMessageBox.confirm(
      '确认保存吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then((res) => {
      if ($route.path.includes('update')) {
        update()
      }
      else if ($route.path.includes('create')) {
        create()
      }
    })
  })
}
onMounted(() => {
  dialogStatus.value = $route.params.type as string
  if (!$route.path.includes('create')) {
    const data = JSON.parse($route.query.row as string)
    for (const i in data) {
      data[i] = String(data[i])
    }
    ruleForm.value = data
    // 区间范围
    if (ruleForm.value.valType === '1') {
      const score = ruleForm.value.score.split('-')
      score1.value = score[0]
      score2.value = score[1]
    }
  }
})
// 指标项目下拉列表
const projectList = ref<{ id: string; value: string; name: string }[]>()
// 指标类型下拉列表
const typeList = ref<{ id: string; value: string; name: string }[]>()
// 数据来源下拉列表
const sourceList = ref<{ id: string; value: string; name: string }[]>()
// 指标值下拉列表
const valueList = ref<{ id: string; value: string; name: string }[]>()
// 获取字典
const fetchSelectList = () => {
  getDictByCode('quota_project').then((res) => {
    projectList.value = res.data
  })
  getDictByCode('quota_type').then((res) => {
    typeList.value = res.data
  })
  getDictByCode('data_source').then((res) => {
    sourceList.value = res.data
  })
  getDictByCode('val_type').then((res) => {
    valueList.value = res.data
  })
}
fetchSelectList()
// 加载组织机构树形下拉
const deptTreeList = ref([])
const fetchDeptTree = () => {
  getDeptTreeList().then((res) => {
    if (res.data) { // 将列表转树结构
      deptTreeList.value = toTreeList(res.data, '0', true)
    }
  })
}
fetchDeptTree()
</script>

<template>
  <app-container style="overflow: hidden;">
    <detail-page class="base-info-device" :title="`考核指标-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="!$route.path.includes('detail')" type="primary" @click="saveData(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="$router.go(-1)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form
        ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="140px" class="form"
        :class="[$route.path.includes('detail') ? 'isDetail' : '']" :disabled="$route.path.includes('detail')"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="考核指标项目" prop="quotaProject">
              <el-select v-model.trim="ruleForm.quotaProject" placeholder="考核指标项目" style="width: 100%;">
                <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核指标类型" prop="quotaType">
              <el-select v-model.trim="ruleForm.quotaType" placeholder="考核指标类型" style="width: 100%;">
                <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="考核指标编号" prop="quotaNo">
              <el-input v-model.trim="ruleForm.quotaNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一级考核指标" prop="priIndicators">
              <el-input v-model.trim="ruleForm.priIndicators" placeholder="一级考核指标" maxlength="30" show-word-limit style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="指标责任考核单位" prop="assDept">
              <!-- <el-input v-model.trim="ruleForm.assDept" placeholder="指标责任考核单位" /> -->
              <dept-select v-model="ruleForm.assDept" :data="deptTreeList" placeholder="指标责任考核单位" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据来源" prop="dataSource">
              <el-select v-model.trim="ruleForm.dataSource" placeholder="数据来源" style="width: 100%;">
                <el-option v-for="item in sourceList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="指标计算规则" prop="ruleDesc">
              <el-input v-model.trim="ruleForm.ruleDesc" type="textarea" placeholder="指标计算规则" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="指标值类型" prop="valType">
              <el-radio-group v-model="ruleForm.valType" class="ml-4">
                <el-radio v-for="item in valueList" :key="item.id" :label="item.value" size="large">
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核分值" prop="score">
              <div v-if="ruleForm.valType === '1'">
                <el-input v-model.trim="score1" placeholder="" style="width: 100px;" />
                ——
                <el-input v-model.trim="score2" placeholder="" style="width: 100px;" />
              </div>
              <!-- 区间 -->
              <!-- 加分 -->
              <el-input
                v-if="ruleForm.valType === '2'" v-model.trim="ruleForm.score" placeholder="考核分值"
              />
              <!-- 减分 -->
              <el-input
                v-if="ruleForm.valType === '3'" v-model.trim="ruleForm.score" placeholder="考核分值"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model.trim="ruleForm.remarks" type="textarea" placeholder="备注" :rows="4" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="附件上传" prop="fileId">
              <show-photo :minio-file-name="ruleForm.fileId" @delete="deleteFile" />
              <input ref="fileRef" style="display: none;" type="file" accept="application/msword,application/pdf" @change="onFileChange">
              <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload">
                上传
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
  </app-container>
</template>

 <style lang="scss" scoped>
    .isDetail {
      ::v-deep {
        .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
        .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
          content: "";
          display: none;
        }
      }
    }
 </style>
