<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<template>
  <div class="v-page classify_page">
    <div style="height: 100%">
      <h2 class="v-title">训练类型</h2>
      <el-cascader
        ref="subjectTypeCascader"
        style="margin: 10px 0"
        :props="{ emitPath: false, value: 'id', label: 'name' }"
        v-model="current_subject_Type"
        @change="subjectTypeChange"
        :options="subject_Type"
      ></el-cascader>
      <SearchTreeMenu
        ref="treeMenuRef"
        title="科目分类列表"
        :tree-data="subject_classify_list"
        @current-change="change"
        @onCreate="toCreateClassify"
        @onDelete="toDeleteclassify"
        @onEdit="toEditClassify"
        v-loading="classify_loading"
      />
    </div>

    <div class="v-ctx" v-loading="subject_list_loading">
      <FormLayout
        ref="formLayoutRef"
        :items="formItems"
        :model="form"
        :rules="rules"
        label-width="70px"
        label-position="right"
        :inline="true"
      >
        <template v-slot:name>
          <QueryInput v-model="form.name" @query="pagingFindList"></QueryInput>
        </template>
        <template v-slot:btns>
          <el-button type="danger" @click="deleteDevices" round
            >删除选中</el-button
          >
          <el-button type="primary" @click="addSubjectHandler" round
            >添加科目</el-button
          >
          <!--  icon="el-icon-plus" -->
        </template>
      </FormLayout>
      <TableLayout
        :column="column"
        :data="table_data"
        :pageInfo="page_info"
        row-key="id"
        @current-change="(e) => pagingChange({ currentPage: e })"
        @size-change="(e) => pagingChange({ pageSize: e })"
        selection
        @selection-change="handleSelectionChange"
      >
        <template v-slot:devices="props">
          {{ props.row.devices.map((item) => item.name).join("、") }}
        </template>
        <template v-slot:status="props">
          <el-switch
            v-model="props.row.status"
            @change="changeStatus(props.row.id, props.row.status)"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
        <template v-slot:action="props">
          <!-- <el-button type="text" icon="el-icon-edit">{{ props.row.type }}</el-button> -->
          <el-button
            type="text"
            icon="i-j-ksap-bianji2"
            @click="editSubject(props.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            icon="i-j-ksap-fuzhi"
            @click="copySubject(props.row)"
            >复制</el-button
          >
          <el-button
            type="text"
            icon="i-j-ksap-shanchu"
            @click="deleteDevices($event, props.row)"
            style="color: #f04343 !important"
            >删除</el-button
          >
        </template>
        <template v-slot:createTime="props">
          <!-- <el-button type="text" icon="el-icon-edit">{{ props.row.type }}</el-button> -->
          {{ new Date(props.row.createTime).format("yyyy-MM-dd") }}
        </template>
        <template v-slot:student="props">
          <!--  icon="el-icon-plus" -->
          <el-switch
            v-if="props.row.creatorId === $store.user.id"
            v-model="props.row.student"
            :active-value="1"
            :inactive-value="0"
            @change="changeItemStatus($event, props.row)"
          >
          </el-switch>
        </template>
      </TableLayout>
    </div>
    <EditorClassify
      v-if="isShowClassifyEditor"
      :subject_Type="subject_Type"
      :form="current_classify"
      v-model="isShowClassifyEditor"
      @successAfter="
        () => {
          isShowClassifyEditor = false;
          findSubjectTrainClassify();
        }
      "
    ></EditorClassify>
  </div>
</template>

<script>
import { SearchTreeMenu, TableLayout, FormLayout } from "@/components/layout";
import QueryInput from "@/components/widget/QueryInput.vue";
import {
  getSubjectClassifyApi,
  deleteSubjectClassifyApi,
  getSubjectTypeApi,
  pagingGetSubjectApi,
  changeSubjectStatusApi,
  deleteSubjectApi,
  copySubjectApi,
} from "@/api/training/subject";
import EditorClassify from "./components/editorClassify.vue";
export default {
  components: {
    SearchTreeMenu,
    TableLayout,
    FormLayout,
    QueryInput,
    EditorClassify,
  },

  data: () => ({
    // 科目类型列表
    subject_Type: [],
    current_subject_Type: null,
    // 科目分类列表
    subject_classify_list: [],
    // 默认分类
    classify_default: [],
    // 科目表数据
    table_data: [],
    // 分页信息
    page_info: { currentPage: 1, pageSize: 10, total: 0 },
    // 当前选中的科目分类信息及ID
    current_classify: {},
    current_classify_id: null,
    // 分类树是否加载中
    classify_loading: false,
    // 科目表加载中
    subject_list_loading: false,
    // 顶部绑定对象
    form: { name: "" },
    // 顶部表单规则
    rules: [],
    // 顶部搜索
    formItems: [],
    // 表格当前选中项
    tableSelectionsList: [],
    isShowClassifyEditor: false,
  }),

  created() {
    this.formItems = [
      { prop: "name" },
      { prop: "btns", model: { class: "gy-btns" } },
      // {
      //   prop: 'desc',
      //   label: '角色描述',
      //   model: { tag: 'el-input', type: 'textarea' }
      // }
    ];
    this.rules = {
      // name: { required: true, message: '请输入角色名称', trigger: 'blur' }
    };
    this.column = [
      {
        prop: "name",
        label: "科目名称",
        width: 300,
        align: "center",
        "show-overflow-tooltip": true,
      },
      {
        prop: "devices",
        label: "所需操作设备",
        align: "center",
        width: 300,
        "show-overflow-tooltip": true,
      },
      {
        prop: "status",
        label: "科目状态",
        width: 100,
        align: "center",
        "show-overflow-tooltip": true,
      },
      {
        prop: "createTime",
        label: "创建时间",
        width: 100,
        align: "center",
        "show-overflow-tooltip": true,
      },
      {
        prop: "action",
        label: "操作",
        width: 200,
        align: "center",
        "show-overflow-tooltip": true,
      },
      {
        prop: "comment",
        label: "科目说明",
        align: "center",
        "show-overflow-tooltip": true,
      },
    ];
    this.getSubjectType();
  },
  async activated() {
    this.pagingFindList();
  },
  mounted() {
    this.getSubjectType();
  },
  methods: {
    /**
     * 获取科目类型列表
     */
    async getSubjectType() {
      const { data } = await getSubjectTypeApi();
      this.subjectTypeMap = data.toTree();
      this.subject_Type = this.subjectTypeMap.tree;
      this.current_subject_Type = this.subject_Type[0]?.children[0].id;
      await this.findSubjectTrainClassify();
      // this.$refs.subjectTypeCascader.handleExpand()
    },
    // 科目类型改变时调用
    subjectTypeChange() {
      this.$refs.treeMenuRef.search = "";
      this.findSubjectTrainClassify();
    },
    changeItemStatus(e, row) {
      this.changeDeviceStudentUse(row, e);
    },
    changeDeviceStudentUse(row, studentCanUse) {
      const form = {
        id: row.id,
        student: studentCanUse,
      };
      studentCanUseApi(form).then((res) => {
        if (res.code !== 0) {
          paperItem.student = studentCanUse === 1 ? 0 : 1;
          this.$message.error("修改失败");
        }
      });
    },
    // 编辑分类
    toEditClassify() {
      this.isShowClassifyEditor = true;
      this.current_classify = JSON.parse(
        JSON.stringify(this.$refs.treeMenuRef.getCurrentNode() || {})
      );
    },
    // 编辑分类状态
    async changeStatus(id, status) {
      await changeSubjectStatusApi({ id, status });
    },
    // 跳转到编辑
    editSubject(row) {
      this.$router.push({
        path: "/train/subject/subject-editor",
        query: { id: row.id },
      });
    },
    addSubjectHandler() {
      this.$router.push({
        path: "/train/subject/subject-editor",
      });
    },
    // 列表选中
    handleSelectionChange(e) {
      this.tableSelectionsList = e;
    },
    async copySubject(data) {
      this.$prompt("请输入新科目名称：", "编辑", {
        inputPattern: /.{1,}/,
        inputErrorMessage: "请输入分类名",
      })
        .then(async ({ value }) => {
          this.subject_list_loading = true;
          let res = await copySubjectApi({ id: data.id, name: value });
          await this.pagingFindList();
          this.subject_list_loading = false;
          console.log(res);
        })
        .catch(() => {});
    },
    /*
      分页变化
    */
    pagingChange(event) {
      if (
        typeof event.currentPage !== "number" &&
        typeof event.pageSize !== "number"
      ) {
        return;
      }

      this.page_info = { ...this.page_info, ...event };

      this.pagingFindList();
    },
    /*
     初始化分页信息
    */
    initPageInfo() {
      this.page_info = {
        currentPage: 1,
        pageSize: this.page_info.pageSize,
        total: 0,
      };
    },
    /*
      分页获取列表
    */
    pagingFindList(e) {
      if (e instanceof PointerEvent) {
        this.initPageInfo();
      }
      if (!this.current_classify_id) {
        this.table_data = [];
        return;
      }
      let classify = this.current_classify_id;
      if (!classify || classify === "system") classify = null;
      this.subject_list_loading = true;

      pagingGetSubjectApi({
        ...this.page_info,
        classify,
        train: this.current_subject_Type,
        ...this.form,
      })
        .then((res) => {
          const { total } = res.data;
          this.table_data = res.data.data;
          // eslint-disable-next-line eqeqeq
          if (this.table_data.length === 0 && this.page_info.currentPage != 1) {
            this.initPageInfo();
            this.pagingFindList();
          }
          this.page_info.total = total;
        })
        .finally((_) => {
          this.subject_list_loading = false;
        });
    },
    /*
      获取所有科目分类
    */
    async findSubjectTrainClassify() {
      const { data } = await getSubjectClassifyApi({
        id: this.current_subject_Type,
      });
      this.classify_default = data;
      this.subjectClassifyMap = {};
      this.subjectClassifyMap = data.toTree();
      this.subject_classify_list = this.subjectClassifyMap.tree;
      this.current_classify_id = this.subject_classify_list[0]?.id || null;
      // 设置选中
      this.$nextTick(() => {
        this.$refs.treeMenuRef.setCurrentKey(
          this.subject_classify_list[0]?.id || null
        );
        this.change(this.subject_classify_list[0] || {});
      });
    },

    async change(classify) {
      this.current_classify_id = classify.id;
      this.pagingFindList();
    },
    /*
      创建分类
    */
    toCreateClassify(node) {
      this.current_classify = {
        name: "",
        pid: node?.id || 0,
        level: node?.level - 1 || 0,
        train: this.current_subject_Type || 0,
      };
      this.isShowClassifyEditor = true;
    },
    // 批量删除、单个删除
    deleteDevices(e, device) {
      if (this.tableSelectionsList.length === 0 && device == null) {
        this.$message.error("请先选择要删除的项目");
      } else {
        let delList = this.tableSelectionsList;
        if (device) {
          delList = [device];
        }
        this.$confirm("确认删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          // eslint-disable-next-line prefer-promise-reject-errors
        }).then((res) => {
          this.subject_list_loading = true;
          deleteSubjectApi(delList.map((_) => _.id)).then((res) => {
            this.pagingFindList();
            this.subject_list_loading = false;
          });
        });
      }
    },
    /*
    删除分类
     */
    toDeleteclassify(classify) {
      if (classify.id === "system") return;
      new Promise((resolve, reject) => {
        this.$confirm(
          "此操作将永久删除此分类，及其子级分类，请确认后删除?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            // eslint-disable-next-line prefer-promise-reject-errors
          }
        ).then((res) => resolve());
      })
        .then((_) => {
          this.classify_loading = true;
          deleteSubjectClassifyApi(classify.id).finally(() => {
            this.findSubjectTrainClassify();
            this.$refs.treeMenuRef.setCurrentKey();
            this.classify_loading = false;
          });
        })
        .catch((_) => {});
    },
  },
};
</script>

<style lang="scss" >
.classify_page .form_layout {
  margin-top: 16px;

  .suf {
    line-height: 1 !important;
  }

  .el-form-item:last-child {
    float: right;
  }
}
</style>
