<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch">
        <el-card class="mb-[10px]" shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="auto">
            <el-form-item label="专家姓名" prop="expertName">
              <el-input v-model="queryParams.expertName" clearable placeholder="请输入专家姓名" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="queryParams.courseName" clearable placeholder="请输入课程名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button plain type="primary" @click="addAssessment('add', {})" v-hasPermi="['study:studyAssessment:add']">新增</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="PlanList">
            <el-table-column label="序号" type="index" width="50px"></el-table-column>
            <el-table-column
              v-for="{ label, prop, align, minWidth } in headers"
              :key="prop"
              :align="align || 'center'"
              :label="label"
              :min-width="minWidth || '100px'"
              prop="expertName"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                <span v-if="['getLevel', 'diffLevel'].includes(prop)">
                  <el-rate v-model="row[prop]" disabled text-color="#ff9900"></el-rate>
                </span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作">
              <template #default="{ row }">
                <el-button link type="primary" v-hasPermi="['study:studyAssessment:edit']" @click="addAssessment('edit', row)">编辑</el-button>
                <el-divider direction="vertical" v-hasPermi="['study:studyAssessment:edit']" />
                <el-button link type="primary" v-hasPermi="['study:studyAssessment:view']" @click="addAssessment('view', row)">查看</el-button>
                <el-divider direction="vertical" v-hasPermi="['study:studyAssessment:view']" />
                <el-button link type="primary" v-hasPermi="['study:studyAssessment:delete']" @click="deleteAssessment(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" v-model:limit="page.pageSize" v-model:page="page.pageNum" :total="page.total" @pagination="getList" />
        </el-card>
        <el-dialog v-model="showAssessmentDialog" :before-close="closeAssessmentDialog" :title="title" width="600px">
          <el-form
            :disabled="assessmentType === 'view'"
            ref="assessmentFormRef"
            :model="AssessmentDialog.form"
            :rules="AssessmentDialog.rules"
            label-width="120px"
          >
            <el-form-item label="课程名称：" prop="courseId">
              <el-select v-model="AssessmentDialog.form.courseId" filterable>
                <el-option v-for="item in courseList" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="难易程度：" prop="diffLevel">
              <el-rate v-model="AssessmentDialog.form.diffLevel" score-template="{value} 分" show-score text-color="#ff9900"></el-rate>
            </el-form-item>
            <el-form-item label="掌握程度：" prop="getLevel">
              <el-rate v-model="AssessmentDialog.form.getLevel" score-template="{value} 分" show-score text-color="#ff9900"></el-rate>
            </el-form-item>
            <el-form-item label="学习完成日期" prop="finishTime">
              <el-date-picker
                style="flex: 1"
                v-model="AssessmentDialog.form.finishTime"
                placeholder="选择日期"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="学习心得：" prop="remark">
              <el-input
                v-model="AssessmentDialog.form.remark"
                :rows="5"
                maxlength="200"
                placeholder="请输入学习心得"
                resize="none"
                show-word-limit
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span>
              <el-button @click="closeAssessmentDialog">取消</el-button>
              <el-button type="primary" @click="confirmAssessmentDialog" v-if="assessmentType !== 'view'">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import { getAssessmentList, setAssessment, delAssessment, updateAssessment } from '@/api/study/studyAssessment';
import { listLearningCourse } from '@/api/study/lesson';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const PlanList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}

const headers = ref<Header[]>([
  {
    label: '课程名称',
    prop: 'courseName'
  },
  {
    label: '掌握程度',
    prop: 'getLevel'
  },
  {
    label: '难易程度',
    prop: 'diffLevel'
  },
  {
    label: '学习日期',
    prop: 'finishTime'
  },
  {
    label: '专家姓名',
    prop: 'expertName'
  }
]);

const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  expertName: '',
  courseName: ''
});

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  const res = await getAssessmentList({
    ...queryParams.value,
    ...page.value
  });
  PlanList.value = res.rows;
  page.value.total = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  page.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const showAssessmentDialog = ref(false);
const assessmentType = ref('add');
const activeRow = ref(null);
const addAssessment = async (type: 'add' | 'edit' | 'view', row?: any) => {
  assessmentType.value = type;
  activeRow.value = row;
  AssessmentDialog.value.form = {
    ...AssessmentDialog.value.form,
    ...row
  }
  showAssessmentDialog.value = true;
};
const deleteAssessment = (row: any) => {
  activeRow.value = row;
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await delAssessment(row.id);
    if (res.code === 200) {
      ElNotification({
        title: '提示',
        message: '删除成功',
        type: 'success'
      });
      getList();
      return;
    }
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
  });
};

const title = computed(() => {
  return { add: '新增', edit: '编辑', view: '详情' }[assessmentType.value];
});
const courseList = ref([]);
const getCourseList = async () => {
  const res = await listLearningCourse({ pageNum: 1, pageSize: 10000000, status: '2'});
  courseList.value = res.rows.map(item => {
    return {
      label: item.courseName,
      value: item.id
    };
  });
}
const assessmentFormRef = ref(null);
const AssessmentDialog = ref({
  form: {
    courseId: '',
    diffLevel: 0,
    getLevel: 0,
    finishTime: '',
    remark: ''
  },
  rules: {
    courseId: [{ required: true, message: '请选择课程名称', trigger: 'change' }],
    diffLevel: [{ required: true, message: '请选择业务水平分数', trigger: 'change' }],
    getLevel: [{ required: true, message: '请选择工作态度分数', trigger: 'change' }],
    finishTime: [{ required: true, message: '请选择学习完成日期', trigger: 'change' }],
    remark: [{ required: true, message: '请输入专家评语', trigger: 'blur' }]
  }
});
const closeAssessmentDialog = () => {
  assessmentFormRef.value.resetFields();
  AssessmentDialog.value.form = {
    courseId: '',
    diffLevel: 0,
    getLevel: 0,
    finishTime: '',
    remark: ''
  };
  showAssessmentDialog.value = false;
};
const confirmAssessmentDialog = () => {
  assessmentFormRef.value.validate(async (valid) => {
    if (!valid) return;
    const params = {
      ...AssessmentDialog.value.form
    };
    let Api = assessmentType.value === 'add' ? setAssessment : updateAssessment
    let res = await Api(params);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }

    ElNotification({
      title: '提示',
      message: `${title.value}成功`,
      type: 'success'
    });
    getList();
    closeAssessmentDialog();
  });
};
onMounted(() => {
  getList();
  getCourseList();
});
</script>
