<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';

// @ts-ignore
import { useVbenDrawer, useVbenModal } from '@vben/common-ui';

import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';

import {
  examCategoryTree,
  // @ts-ignore
} from '#/api/exam/exam/category';
// @ts-ignore
import { addExam, examDetail, updateExam } from '#/api/exam/exam/exam';
import {
  PaperCategoryTree,
  // @ts-ignore
} from '#/api/exam/paper/category';
// @ts-ignore
import { paperList } from '#/api/exam/paper/paper';
// @ts-ignore
import { SelectUsers } from '#/components/selectUsers';

const emit = defineEmits<{ reload: [] }>();

// 抽屉可见性
const drawerVisible = ref(false);

const isUpdateRef = ref<boolean>(false);
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: any) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      let { id, isUpdate, parentId } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const examInfo: any = await examDetail(id);
        if (examInfo) {
          // 不直接替换examForm对象，而是修改其属性以保持响应性
          const executorUsers = examInfo.users
            ? JSON.parse(examInfo.users) || []
            : [];
          Object.assign(examForm, {
            ...examInfo,
            executorUsers,
            executorCount: executorUsers.length || 0,
          });

          // 试卷列表
          const paperListRes: any = await paperList({
            id: examInfo.paperId,
          });
          if (paperListRes?.rows?.length) {
            selectedPapers.value = paperListRes.rows || [];
          }
        }
      } else {
        // 如果父节点是0的话说明是根节点，将本节点id复制给根节点用于侧拉显示根节点。
        if (parentId === 0) {
          parentId = id;
        }
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    // formApi.resetForm();
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;

      // 表单验证
      if (!examForm.examName) {
        ElMessage.error('请输入考试名称');
        return;
      }
      if (!examForm.categoryId) {
        ElMessage.error('请选择考试分类');
        return;
      }
      if (!examForm.passScore) {
        ElMessage.error('请输入及格分');
        return;
      }
      if (examForm.paperId === '') {
        ElMessage.error('请选择试卷');
        return;
      }
      if (!examForm.examStartTime) {
        ElMessage.error('请选择考试开始时间');
        return;
      }
      if (!examForm.examEndTime) {
        ElMessage.error('请选择考试结束时间');
        return;
      }
      if (!examForm.examDuration) {
        ElMessage.error('请输入考试时长');
        return;
      }

      const params: any = {
        categoryId: examForm.categoryId,
        passScore: examForm.passScore,
        paperId: examForm.paperId,
        examName: examForm.examName,
        remark: examForm.remark,
        examStartTime: examForm.examStartTime
          ? dayjs(examForm.examStartTime).format('YYYY-MM-DD HH:mm:ss')
          : '',
        examEndTime: examForm.examEndTime
          ? dayjs(examForm.examEndTime).format('YYYY-MM-DD HH:mm:ss')
          : '',
        examDuration: examForm.examDuration,
        examStatus: 'ongoing',
        isLimit: examForm?.executorUsers?.length > 0 ? 1 : 0,
        users: null,
      };

      if (params.isLimit && examForm.executorUsers.length > 0) {
        params.users = JSON.stringify(
          examForm.executorUsers.map((user: any) => {
            return {
              id: user.id,
              name: user.name,
            };
          }),
        );
      }

      if (isUpdateRef.value && !drawerApi.getData().isCopy) {
        params.id = drawerApi.getData().id;
      }

      await (isUpdateRef.value ? updateExam(params) : addExam(params));

      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});

// 考试设置表单数据
let examForm = reactive({
  examName: '',
  categoryId: '',
  remark: '',
  paperId: '',
  passScore: '',
  examStartTime: '',
  examEndTime: '',
  examDuration: '',
  executorCount: 0, // 模拟已选择23人
  executorUsers: [],
  paperCategoryId: '',
});

// 已选择的试卷
let selectedPapers: any = ref([]);

// 打开抽屉
const openDrawer = () => {
  drawerVisible.value = true;
};

// 选择考试执行人
const selectExecutors = () => {
  executorModalApi.open();
};

// 删除已选择的试卷
const removePaper = () => {
  selectedPapers.value = [];
  examForm.paperId = '';
};

const executorUserIds = computed(() => {
  return examForm.executorUsers.map((o: any) => o.id);
});

const papers: any = ref([]);

const getPapers = async () => {
  const params = {
    categoryId: examForm.paperCategoryId,
  };

  const res: any = await paperList(params);
  if (res?.rows?.length > 0) {
    papers.value = res.rows;
  }
};

const handlePaperCategoryChange = () => {
  getPapers().then();
};

// 监听试卷名称选择变化
const handlePaperNameChange = (values: any) => {
  const paperInfo = papers.value.find((paper: any) => paper.id === values);
  if (paperInfo) {
    examForm.paperId = paperInfo.id;

    selectedPapers.value.push(paperInfo);
  } else {
    selectedPapers.value = [];
  }
};

// 暴露方法给父组件
defineExpose({
  openDrawer,
});

// 获取试卷分类树
const categoryTree = ref([]);
const getCategoryOptions = async () => {
  const res: any = await examCategoryTree();
  categoryTree.value = res.rows || [];
};

const executorRef: any = ref(null);

const [ExecutorModal, executorModalApi] = useVbenModal({
  title: '选择考试执行人',
  width: 1000,
  height: 800,
  showCancelBtn: false,
  onConfirm: async () => {
    const users = await executorRef.value.confirmSelection();
    if (users?.length) {
      examForm.executorCount = users.length;
      examForm.executorUsers = users;
      executorModalApi.close();
    }
  },
});

const paperCategoryTree = ref([]);

const getPaperCategoryOptions = async () => {
  const res: any = await PaperCategoryTree();
  paperCategoryTree.value = res.rows || [];
};

onMounted(async () => {
  getCategoryOptions().then();
  getPaperCategoryOptions().then();
});
</script>

<template>
  <div>
    <!-- 发布考试抽屉 -->
    <Drawer class="w-[800px]">
      <div class="exam-publish-drawer">
        <!-- 第一部分：考试设置 -->
        <div class="exam-setting-section">
          <h3 class="section-title">考试设置</h3>

          <ElForm
            :model="examForm"
            label-position="top"
            class="grid-cols-1 gap-4 md:grid-cols-2"
          >
            <!-- 考试名称 -->
            <ElFormItem label="考试名称" class="form-item-with-border" required>
              <ElInput
                v-model="examForm.examName"
                placeholder="请输入考试名称"
                maxlength="30"
                show-word-limit
              />
            </ElFormItem>

            <!-- 考试分类 -->
            <ElFormItem label="考试分类" class="form-item-with-border" required>
              <!-- <ElSelect
                v-model="examForm.categoryId"
                placeholder="请选择考试分类"
                style="width: 100%"
              >
                <ElOption
                  v-for="option in categoryOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </ElSelect> -->
              <ElTreeSelect
                v-model="examForm.categoryId"
                :data="categoryTree"
                :props="{
                  label: 'name',
                  value: 'id',
                  children: 'children',
                }"
                placeholder="请选择分类"
                class="select"
              />
            </ElFormItem>

            <!-- 考试说明 -->
            <ElFormItem
              label="考试说明"
              class="form-item-with-border md:col-span-2"
            >
              <ElInput
                v-model="examForm.remark"
                type="textarea"
                placeholder="请输入考试说明"
                rows="3"
              />
            </ElFormItem>

            <!-- 考试总分 -->
            <!-- <ElFormItem label="考试总分" class="form-item-with-border">
              <ElInput
                v-model="examForm.totalScore"
                placeholder="请输入考试总分"
                type="number"
                min="1"
              >
                <template #append>分</template>
              </ElInput>
            </ElFormItem> -->

            <!-- 及格分 -->
            <ElFormItem label="及格分" class="form-item-with-border" required>
              <ElInput
                v-model="examForm.passScore"
                placeholder="请输入及格分"
                type="number"
                min="1"
              >
                <template #append>分</template>
              </ElInput>
            </ElFormItem>

            <!-- 答卷时长 -->
            <ElFormItem label="答卷时长" class="form-item-with-border" required>
              <ElInput
                v-model="examForm.examDuration"
                placeholder="请输入答卷时长"
                type="number"
                min="1"
              >
                <template #append>分钟</template>
              </ElInput>
            </ElFormItem>

            <!-- 考试时间 -->
            <ElFormItem
              label="考试时间"
              class="form-item-with-border md:col-span-2"
              required
            >
              <ElDatePicker
                v-model="examForm.examStartTime"
                type="datetime"
                placeholder="开始时间"
                style="width: calc(50% - 15px)"
              />
              <span style="margin: 0 6px">至</span>
              <ElDatePicker
                v-model="examForm.examEndTime"
                type="datetime"
                placeholder="结束时间"
                style="width: calc(50% - 15px)"
              />
            </ElFormItem>

            <!-- 考试执行人 -->
            <ElFormItem
              label="考试执行人"
              class="form-item-with-border md:col-span-2"
            >
              <ElButton @click="selectExecutors"> 选择考试执行人 </ElButton>
              <span
                style="margin-left: 10px; color: #86909c"
                v-if="examForm.executorCount > 0"
              >
                已选择{{ examForm.executorCount }}人
              </span>
              <span style="margin-left: 10px; color: #86909c" v-else>
                未选择执行人，将不限制考试人员
              </span>
            </ElFormItem>
          </ElForm>
        </div>

        <!-- 第二部分：选择试卷 -->
        <div class="select-paper-section">
          <h3 class="section-title">选择试卷</h3>

          <div class="mb-4 grid-cols-1 gap-4 md:grid-cols-2">
            <!-- 选择试卷分类 -->
            <ElFormItem label="选择试卷分类" class="form-item-with-border">
              <ElTreeSelect
                v-model="examForm.paperCategoryId"
                :data="paperCategoryTree"
                @change="handlePaperCategoryChange"
                :props="{
                  label: 'name',
                  value: 'id',
                  children: 'children',
                }"
              />
            </ElFormItem>

            <!-- 选择试卷名称 -->
            <ElFormItem label="选择试卷名称" class="form-item-with-border">
              <ElSelect
                v-model="examForm.paperId"
                filterable
                allow-create
                default-first-option
                placeholder="请选择试卷名称"
                style="width: 100%"
                @change="handlePaperNameChange"
              >
                <ElOption
                  v-for="option in papers"
                  :key="option.id"
                  :label="option.paperName"
                  :value="option.id"
                />
              </ElSelect>
            </ElFormItem>
          </div>

          <!-- 选择的试卷列表 -->
          <div class="selected-papers-list" v-if="selectedPapers.length > 0">
            <ElTable
              :data="selectedPapers"
              style="width: 100%"
              :header-cell-style="{ backgroundColor: '#F7F9FA', color: '#000' }"
            >
              <ElTableColumn
                prop="paperName"
                label="试卷名称"
                min-width="200"
              />
              <ElTableColumn prop="categoryName" label="类别" min-width="120" />
              <ElTableColumn prop="createBy" label="创建人" min-width="120" />
              <ElTableColumn
                prop="totalScore"
                label="试卷总分"
                min-width="100"
              />
              <ElTableColumn
                prop="questionCount"
                label="试题总数"
                min-width="100"
              />
              <ElTableColumn
                prop="updateTime"
                label="更新时间"
                min-width="120"
              />
              <ElTableColumn label="操作" width="80" fixed="right">
                <template #default>
                  <ElButton
                    link
                    type="warning"
                    size="small"
                    @click="removePaper"
                    class="custom-delete-btn"
                  >
                    删除
                  </ElButton>
                </template>
              </ElTableColumn>
            </ElTable>
          </div>
        </div>
      </div>
    </Drawer>

    <ExecutorModal class="w-[700px]">
      <SelectUsers ref="executorRef" :model-value="executorUserIds" />
    </ExecutorModal>
  </div>
</template>

<style lang="scss" scoped>
.exam-publish-drawer {
  padding: 20px;
}

:deep(.el-drawer__header) {
  .el-drawer__title {
    color: #000;
  }
}

.section-title {
  position: relative;
  padding-left: 12px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;

  &::before {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 3px;
    content: '';
    background-color: #409eff;
    border-radius: 2px;
  }
}

:deep(.form-item-with-border) {
  .el-form-item__label {
    position: relative;
    padding-left: 12px;
    font-weight: 500;
    color: #000;
  }
}

.grid-cols-1 {
  display: grid;
  grid-template-columns: 1fr;
}

.md\:grid-cols-2 {
  @media (min-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.md\:col-span-2 {
  @media (min-width: 768px) {
    grid-column: span 2;
  }
}

.gap-4 {
  gap: 1rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
  margin-top: 30px;
}

.selected-papers-list {
  margin-top: 20px;
}

.custom-delete-btn {
  color: #f0864d;
}
</style>
