<template>
  <div class="app-container">
    <el-form
      class="box"
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="auto"
    >
      <el-row>
        <el-form-item label="试卷：" prop="paperIdx" style="margin-right: 16px">
          <el-select
            v-model="form.paperIdx"
            style="width: 300px"
            placeholder="请选择"
            filterable
            @change="changePaper"
          >
            <el-option
              v-for="o in paperOptions"
              :key="o.value"
              :label="o.label"
              :value="o.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="作业名称：" prop="name">
          <el-input
            v-model="form.name"
            style="width: 300px"
            maxlength="40"
            placeholder="请输入"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item
          label="开始时间："
          prop="beginTime"
          style="margin-right: 16px"
        >
          <el-date-picker
            v-model="form.beginTime"
            type="datetime"
            placeholder="请选择"
            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 300px"
            @change="changeBeginTime"
          />
        </el-form-item>
        <el-form-item label="截止时间：" prop="submitEndTime">
          <el-date-picker
            v-model="form.submitEndTime"
            type="datetime"
            placeholder="请选择"
            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 300px"
          />
        </el-form-item>
      </el-row>

      <el-form-item label="作业内容：" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="5"
          maxlength="1000"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="发布对象：" prop="publishType">
        <el-radio-group v-model="form.publishType" @change="changeType">
          <!-- <el-radio :value="0">全部</el-radio> -->
          <el-radio :value="1">班级（支持多选）</el-radio>
          <el-radio :value="2">学生（支持多选）</el-radio>
          <el-radio :value="3">参考其他作业</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.publishType === 1"
        label="选择班级："
        prop="classIdList"
      >
        <el-checkbox-group v-model="form.classIdList" @change="changeClass">
          <el-checkbox
            v-for="item in classList"
            :key="item.id"
            :label="item.id"
          >
            {{ item.className }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <template v-if="form.publishType === 2">
        <Filter
          ref="filterRef"
          class="box"
          v-model="filterData"
          :config="filterConfig"
          @handleAction="handleFilterData"
        />
        <table v-if="tableData.length" class="watch-table">
          <tr
            v-for="(item, idx) in Math.ceil(tableData.length / columns)"
            :key="idx"
          >
            <template v-for="i in columns" :key="i">
              <td
                v-if="tableData[idx * columns + i - 1]?.stuName"
                :class="{
                  active: tableSelectionId.includes(
                    tableData[idx * columns + i - 1].stuId
                  ),
                }"
                @click="onSelect(tableData[idx * columns + i - 1])"
              >
                {{ tableData[idx * columns + i - 1]?.className }}
                <br />
                {{ tableData[idx * columns + i - 1]?.stuName }}
              </td>
            </template>
          </tr>
        </table>
        <!-- <el-table
        ref="tableRef"
        :data="tableData"
        border
        style="width: 100%"
        max-height="400"
        row-key="stuId"
        @select="onSelect"
        @select-all="onSelect"
      >
        <el-table-column
          v-if="form.publishType === 2"
          type="selection"
          width="80"
        />
        <el-table-column v-else type="index" width="80" />
        <el-table-column prop="className" label="班级" />
        <el-table-column prop="stuName" label="姓名" />
      </el-table> -->
        <el-pagination
          class="box"
          style="justify-content: end"
          v-model:current-page="page.pageNum"
          v-model:page-size="page.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          :page-sizes="[30, 60, 90, 120]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </template>
      <template v-if="form.publishType === 3">
        <Table ref="tableRef" :xbTable="xbTable" @select="onTableSelect">
        </Table>
      </template>
      <el-form-item class="btns">
        <el-button type="primary" size="large" @click="onSubmit"
          >发布</el-button
        >
        <!-- <el-button size="large">取消</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import Filter from "@/components/Filter/index.vue";
import {
  getSubjectPaperList,
  addJob,
  getClassList,
  getStudentList,
  getJobList,
} from "@/api";
import { nextTick, reactive } from "vue";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
import useUserStore from "@/store/modules/user";
import Table from "@/components/Table/index.vue";

const router = useRouter();
const { proxy } = getCurrentInstance();

const paperOptions = ref([]);
const formRef = ref();
const form = reactive({
  name: "",
  beginTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  submitEndTime: dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
  paperIdx: "",
  content: "",
  publishType: 1,
  classIdList: [],
});
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入作业名称",
      trigger: "blur",
    },
    {
      min: 2,
      max: 90,
      message: "长度在2到90之间",
      trigger: "blur",
    },
  ],
  beginTime: {
    required: true,
    message: "请选择开始时间",
    trigger: "change",
  },
  submitEndTime: {
    required: true,
    message: "请选择截止时间",
    trigger: "change",
  },
  paperIdx: {
    required: true,
    message: "请选择试卷",
    trigger: ["change", "blur"],
  },
  content: {
    required: true,
    message: "请输入作业内容",
    trigger: "blur",
  },
  publishType: {
    required: true,
    message: "请选择发布形式",
    trigger: "change",
  },
  classIdList: [
    {
      required: true,
      message: "请选择班级",
    },
    {
      validator: validateClassIdList,
      trigger: "blur",
    },
  ],
});

function changeBeginTime(val) {
  if (dayjs(val).isAfter(form.submitEndTime)) {
    form.submitEndTime = dayjs(val).endOf("day").format("YYYY-MM-DD HH:mm:ss");
  }
}

function changePaper(val) {
  const { subjectName, knowledgeList } = paperOptions.value[val];
  form.name = `【${subjectName}作业】${dayjs().format("YYYY-MM-DD")}`;
  form.content = knowledgeList.slice(0, 10).join("；");
}

function validateClassIdList(rule, value, callback) {
  if (!value || !value.length) {
    callback(new Error("请选择班级"));
  } else {
    callback();
  }
}

const classList = ref([]);
const filterRef = ref();
const filterData = ref({}); //过滤
const filterConfig = computed(() => {
  return [
    {
      comName: "el-select",
      placeholder: "请选择班级",
      prop: "classId",
      clearable: true,
      options: classList.value,
      selectConfig: {
        label: "className",
        value: "id",
      },
    },
    {
      comName: "el-input",
      label: "",
      prop: "stuName",
      placeholder: "请输入学生姓名",
      clearable: true,
    },
  ];
});

// 查询
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      initStudent();
      break;
  }
}

// 切换发布形式
function changeType(type) {
  filterRef.value?.onClear();
  form.classIdList = [];
  // tableSelection.value = [];
  if (type === 1) {
    initClass();
  }
  initStudent();
}

const loading = ref(false);
const tableData = ref([]);
const tableSelection = ref([]);
const tableSelectionId = computed(() =>
  tableSelection.value.map((i) => i.stuId)
);
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 60,
});
const columns = ref(15);

function handleSizeChange() {
  initStudent();
}
function handleCurrentChange() {
  initStudent(false);
}
let echoing = false;
function onSelect(val) {
  if (tableSelectionId.value.includes(val.stuId)) {
    tableSelection.value = tableSelection.value.filter(
      (i) => i.stuId !== val.stuId
    );
    return;
  }
  // 当前页所有的ID
  const allId = tableData.value.map((i) => i.stuId);
  // 其他页的选中
  const otherSelect = tableSelection.value.filter((i) => !allId.includes(i));
  // 添加当前的选中
  tableSelection.value = [...otherSelect, val];
}

// 选择班级
function changeClass() {
  initStudent();
}

// 选择作业
const userStore = useUserStore();
const tableRef = ref();
const xbTable = ref({
  loading: false,
  columns: [
    { type: "selection", width: 80 },
    { prop: "name", label: "作业名称" },
    { prop: "studentsName", label: "学员" },
    { prop: "createTime", label: "发布时间" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
async function initJob() {
  xbTable.value.loading = true;
  try {
    const res = await getJobList({
      ...xbTable.value.pagination,
      ...filterData.value,
      createUser: userStore.id,
    });
    xbTable.value.tableData = res.rows;
    xbTable.value.loading = false;
  } catch (err) {
    console.log(err);
  } finally {
    xbTable.value.loading = false;
  }
}
const tableSelect = ref({});
function onTableSelect(val, row) {
  const dom = tableRef.value.getRef();
  dom.clearSelection();
  dom.toggleRowSelection(row, true);
  tableSelect.value = row;
}

// 发布作业
const onSubmit = async () => {
  await formRef.value?.validate();
  const { paperId, stagePid, subjectId, autoAuditFlag } =
    paperOptions.value[form.paperIdx];
  const res = await addJob({
    ...form,
    stuIdList: tableSelectionId.value,
    paperId,
    stagePid,
    subjectId,
    autoAuditFlag,
    lastJobId: tableSelect.value.id,
  });
  proxy.$tab.closePage(router.currentRoute.value);
  router.push("/paper/jobRecords");
};

// 初始化
async function init() {
  const res = await getSubjectPaperList({
    category: 4,
    pageNum: 1,
    pageSize: 10000,
  });
  paperOptions.value = res.rows.map((i, index) => ({
    label: i.name,
    value: index,
    paperId: i.id,
    stagePid: i.stagePid,
    subjectId: i.subjectId,
    autoAuditFlag: i.autoAuditFlag,
    subjectName: i.subjectName,
    knowledgeList: i.knowledgeList,
  }));
}

async function initClass() {
  if (classList.value.length) return;
  const res = await getClassList();
  classList.value = res.data;
  form.classIdList = res.data.map((i) => i.id);
}

async function initStudent(reset = true) {
  loading.value = true;
  try {
    if (reset) {
      page.pageNum = 1;
    }
    const res = await getStudentList({
      classIdList:
        form.publishType === 1
          ? form.classIdList
          : filterData.value.classId
          ? [filterData.value.classId]
          : undefined,
      stuName: filterData.value.stuName,
      pageNum: page.pageNum,
      pageSize: page.pageSize,
    });
    page.total = res.total;
    echoing = true;
    tableData.value = res.rows;
    await nextTick();
    // 回显选中
    if (form.publishType === 2) {
      tableSelection.value.forEach((i) => {
        const row = tableData.value.find((row) => row.stuId === i);
        if (row) {
          tableRef.value.toggleRowSelection(row, true);
        }
      });
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  init();
  initClass();
  initStudent();
  initJob();
});
</script>
<style scoped lang="scss">
.app-container {
  .box {
    background: #fff;
    padding: 16px;
    margin-bottom: 16px;
    border-radius: 4px;

    .watch-table {
      tr {
        width: 100%;
        td {
          width: 100px;
          border: 1px solid #ccc;
          text-align: center;
          padding: 12px 0;
          cursor: pointer;

          &.active {
            background: #79bbff;
          }
        }
      }
    }
  }
  position: relative;
  form {
    margin: 0 auto;
  }
}
:deep(.el-form) {
  .el-form-item {
    margin-bottom: 24px;
    .el-input {
      max-width: 300px;
    }
    .el-textarea {
      max-width: 500px;
      textarea {
        resize: none;
      }
    }
  }
  .btns {
    margin-top: 36px;
    .el-form-item__content {
      justify-content: center;
    }
  }
}
:deep(.filter_box) {
  .el-form-item.el-form-item--default.asterisk-left {
    margin-bottom: 0;
  }
  [value="reset"] {
    display: none;
  }
}
:deep(.el-table) {
  thead {
    .el-table-column--selection {
      .cell {
        display: none;
      }
    }
  }
}
</style>
