<!--
 * @Description: 考核方案管理新建/编辑/详情页面
 * @Author: 李亚光
 * @Date: 2023-09-14
 -->
<script lang="ts" setup name="RuleProgrammeHandler">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import proxyTable from './proxyTable.vue'
import { getDictByCode } from '@/api/system/dict'
import { uploadApi } from '@/api/common'
import { ProxyList, addProgramme, addProxyList, editProgramme, getDeptList, getDetail, getGradeSelectList, updatePlanEnabled } from '@/api/home/rule/programme'
const $route = useRoute()
const $router = useRouter()
// 对话框类型：create,update
const dialogStatus = ref('create')
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
const dept = ref()
// 表单对象
const ruleForm = ref({
  assObject: '', //  考核对象
  createTime: '',
  cycle: '', // 考核周期
  endTime: '',
  fileId: '',
  fileName: '',
  id: '',
  isEnable: '',
  levelId: '',
  planName: '',
  recoRating: '',
  remarks: '',
  ruleDescription: '', // 考核得分规则描述
  score: '',
  startTime: '',
})
const proxyList = ref([])
// 表单验证规则
const rules = ref<FormRules>({
  assObject: [{ required: true, message: '考核对象必选', trigger: ['blur', 'change'] }],
  planName: [{ required: true, message: '考核方案名称必填', trigger: ['blur', 'change'] }],
  cycle: [{ required: true, message: '考核周期必选', trigger: ['blur', 'change'] }],
  levelId: [{ required: true, message: '考核评定等级必选', trigger: ['blur', 'change'] }],
  startTime: [{ required: true, message: '考核填报发送日期必选', trigger: ['blur', 'change'] }],
  endTime: [{ required: true, message: '考核填报截至日期必选', trigger: ['blur', 'change'] }],
  ruleDescription: [{ required: true, message: '考核得分规则必填', trigger: ['blur', 'change'] }],
  isEnable: [{ required: true, message: '是否启用必选', trigger: ['blur', 'change'] }],
})
// 表单实例对象
const ruleFormRef = ref()
// 一级考核指标实例对象
const proxyRef = ref()
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.fileId}` : res.data.fileId
        ruleForm.value.fileName = ruleForm.value.fileName ? `${ruleForm.value.fileName},${res.data.fileName}` : res.data.fileName
        // 重置当前验证
        ruleFormRef.value?.clearValidate('minioFileName')
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        // ElMessage.error(res.message)
        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 objectList = ref<{ id: string; value: string; name: string }[]>()
// 是否禁用下拉列表
const disableList = ref<{ id: string; value: string; name: string }[]>()
// 考核周期下拉框
const cycleList = ref<{ id: string; value: string; name: string }[]>()
// 考核等级下拉框
const levelList = ref<any[]>()
// 获取字典
const fetchSelectList = () => {
  getDictByCode('ass_object').then((res) => {
    objectList.value = res.data
  })
  getDictByCode('is_enable').then((res) => {
    disableList.value = res.data
  })
  getDictByCode('cycle_code').then((res) => {
    cycleList.value = res.data
  })
  // getDictByCode('level_code').then((res) => {
  //   levelList.value = res.data
  // })
  getGradeSelectList().then((res) => {
    levelList.value = res.data
  })
}
fetchSelectList()
const radio = ref('基本信息')
// 获取方案指标列表
const fetchProxyList = () => {
  // if ($route.path.includes('create')) {
  //   return
  // }
  ProxyList({ planId: ruleForm.value.id, limit: 9999, offset: 1 }).then((res) => {
    proxyList.value = res.data.rows.map((item: any) => ({ ...item, id: item.quotaId }))
  })
}
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
    // getDetail({ id: data.id }).then((res) => {
    //   console.log(res.data)
    // })
    fetchProxyList()
  }
})
// 编辑
const update = () => {
  editProgramme({ ...ruleForm.value, depts: undefined, quotaInfos: undefined }).then((res) => {
    addProxyList({
      planId: ruleForm.value.id,
      quotaIds: proxyList.value.map((item: any) => item.id),
    }).then((res) => {
      // if (ruleForm.value.isEnable === '1' && proxyList.value.length) {
      //   updatePlanEnabled({ ...ruleForm.value }).then(() => {
      //     ElMessage.success('操作成功')
      //     $router.go(-1)
      //   })
      // }
      // else {
      ElMessage.success('操作成功')
      $router.go(-1)
      // }
    })
  })
}
// 新增
const create = () => {
  addProgramme({ ...ruleForm.value }).then((response) => {
    addProxyList({
      planId: response.data,
      quotaIds: proxyList.value.map((item: any) => item.id),
    }).then((res) => {
      if (ruleForm.value.isEnable === '1' && proxyList.value.length) {
        updatePlanEnabled({ id: response.data, isEnable: '1' }).then(() => {
          ElMessage.success('操作成功')
          $router.go(-1)
        })
      }
      else {
        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) => {
      proxyList.value = proxyRef.value?.list
      if ($route.path.includes('update')) {
        update()
      }
      else if ($route.path.includes('create')) {
        create()
      }
    })
  })
}
// watch(() => proxyRef.value?.list, (newVal) => {
//   proxyList.value = newVal
// }, {
//   deep: true,
// })
watch(() => ruleForm.value.assObject, (newVal) => {
  console.log(newVal)
  getDeptList({ type: newVal }).then((res) => {
    dept.value = res.data.map((item: any) => item.fullName).join(',')
  })
}, {
  deep: true,
})
</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-radio-group v-model="radio">
        <el-radio-button label="基本信息" />
        <el-radio-button label="一级考核指标" />
      </el-radio-group>
    </detail-block-com>
    <!-- 基本信息 -->
    <detail-block-com v-show="radio === '基本信息'">
      <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="planName">
              <el-input v-model.trim="ruleForm.planName" placeholder="考核方案名称" style="width: 100%;" type="textarea" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核对象" prop="assObject">
              <el-select v-model.trim="ruleForm.assObject" placeholder="指标考核对象" style="width: 100%;">
                <el-option v-for="item in objectList" :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="approvalName" disabled>
              <el-input v-model.trim="dept" type="textarea" placeholder="考核部门" :rows="3" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="考核周期" prop="cycle">
              <el-select v-model.trim="ruleForm.cycle" placeholder="考核周期" style="width: 100%;">
                <el-option v-for="item in cycleList" :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="levelId">
              <el-select v-model.trim="ruleForm.levelId" placeholder="考核等级评定" style="width: 100%;">
                <el-option v-for="item in levelList" :key="item.id" :label="item.levelName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="考核填报发送日期" prop="startTime">
              <el-date-picker
                v-model="ruleForm.startTime"
                style="width: 100%;" type="datetime" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                placeholder="考核填报发送日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核填报截至日期" prop="endTime">
              <el-date-picker
                v-model="ruleForm.endTime"
                style="width: 100%;" type="datetime" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                placeholder="考核填报截至日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="考核得分规则" prop="ruleDescription">
              <el-input v-model.trim="ruleForm.ruleDescription" placeholder="添加考核得分规则" type="textarea" maxlength="200" show-word-limit style="width: 100%;" />
            </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="approvalName">
              <el-switch
                v-model="ruleForm.isEnable"
                size="large"
                active-text="是"
                active-value="1"
                inactive-text="否"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="附件上传" prop="approvalNo">
              <show-photo :minio-file-name="ruleForm.fileName" :minio-file-id="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>
    <!-- 一级考核指标 -->
    <proxy-table v-show="radio === '一级考核指标'" ref="proxyRef" :data="proxyList" />
  </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>
