<template>
  <div class="add-courseware">
    <save-form
      :inline="true"
      :model="searchForm"
      @submit="search"
      @reset="onReSet"
      ref="searchForm"
      savekey="courseware-config-add-teacher"
    >
      <el-form-item prop="search">
        <el-input
          v-model.trim="searchForm.search"
          clearable
          @keyup.enter.native="
            e => {
              e.target.blur();
              $refs.searchForm.save();
              search();
            }
          "
          placeholder="编号/姓名/手机号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="organId">
        <el-select
          v-model.trim="searchForm.organId"
          filterable
          clearable
          placeholder="请选择分部"
        >
          <el-option
            v-for="item in selects.branchs"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="jobNature">
        <el-select
          v-model.trim="searchForm.jobNature"
          filterable
          clearable
          placeholder="工作类型"
        >
          <el-option
            v-for="item in jobNature"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button native-type="submit" type="primary">搜索</el-button>
        <el-button native-type="reset" type="danger">重置</el-button>
      </el-form-item>
    </save-form>
    <div class="tableWrap">
      <el-table
        :data="tableList"
        ref="multipleSelection"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        @select-all="handleSelectionChange"
        @select="onTableSelect"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          align="center"
          prop="id"
          label="编号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="realName"
          label="姓名"
        ></el-table-column>

        <el-table-column
          align="center"
          label="手机号"
          prop="phone"
        ></el-table-column>
        <el-table-column
          align="center"
          label="分部"
          prop="organName"
        ></el-table-column>
        <el-table-column align="center" label="工作类型" prop="courseNum">
          <template slot-scope="scope">
            <p>{{ scope.row.jobNature | jobNature }}</p>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        sync
        savekey="courseware-config-add-teacher"
        :total.sync="pageInfo.total"
        :page.sync="pageInfo.page"
        :limit.sync="pageInfo.limit"
        :page-sizes="pageInfo.page_size"
        @pagination="getList"
      />
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button
        :disabled="activeChiose.length <= 0"
        @click="onSubmit"
        type="primary"
        >确 定</el-button
      >
    </span>
  </div>
</template>

<script>
import pagination from "@/components/Pagination/index";
import {
  lessonCoursewarePage,
  queryLessonCoursewareId,
  addLessonCourseware
} from "./api";
import { courseEmnuList, jobNature } from "@/utils/searchArray";
import { teacherQueryPage } from "@/api/teacherManager";
import deepClone from "@/helpers/deep-clone/";
export default {
  name: "add-courseware",
  components: { pagination },
  props: ["list"],
  data() {
    return {
      jobNature, // 工作类型
      courseEmnuList,
      tableList: [],
      searchForm: {
        search: null,
        organId: null,
        jobNature: null
      },
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      existIds: [],
      activeChiose: []
    };
  },
  async mounted() {
    this.activeChiose = this.list || [];
    await this.$store.dispatch("setBranchs");
    this.getList();
  },
  methods: {
    search() {
      this.pageInfo.page = 1;
      this.getList();
    },
    onReSet() {
      this.$refs.searchForm.resetFields();
      this.search();
    },
    onFormatSelectData(arr, row) {
      try {
        let currentPageList = [];
        const otherPageList = [];
        this.activeChiose.forEach(item => {
          if (item.currentPage == this.pageInfo.page) {
            currentPageList.push(item);
          } else {
            otherPageList.push(item);
          }
        });

        const lastPage = [];
        if (row?.id) {
          const index = currentPageList.findIndex(child => child.id === row.id);
          if (index === -1) {
            lastPage.push(row);
          } else {
            currentPageList.splice(index, 1);
          }
        } else {
          if (arr.length > 0) {
            arr.forEach(item => {
              const index = currentPageList.findIndex(
                child => child.id === item.id
              );
              if (index === -1) {
                lastPage.push(item);
              }
            });
          } else {
            currentPageList = [];
          }
        }

        this.activeChiose = [
          ...lastPage,
          ...otherPageList,
          ...currentPageList
        ].sort((a, b) => a.id - b.id);
      } catch (e) {}
    },
    onTableSelect(arr, row) {
      console.log(arr, "onTableSelect", row);
      this.onFormatSelectData(arr, row);
    },
    handleSelectionChange(arr) {
      console.log(arr, "val");
      this.onFormatSelectData(arr);
    },
    async getList() {
      //
      try {
        let params = {
          ...this.searchForm,
          page: this.pageInfo.page,
          rows: this.pageInfo.limit
        };
        teacherQueryPage(params).then(res => {
          if (res.code == 200) {
            //  (res)
            console.log(res, "data");
            const rows = res.data.rows || [];
            rows.forEach(row => {
              row.currentPage = this.pageInfo.page;
            });
            this.tableList = rows;
            this.pageInfo.total = res.data.total;

            // 反选对应数据
            const activeChiose = deepClone(this.activeChiose);
            console.log(activeChiose, "this.list");
            this.$nextTick(() => {
              this.tableList.forEach(item => {
                const index = activeChiose.findIndex(
                  child => child.id == item.id
                );
                if (index > -1) {
                  console.log(index, "tableList", item.id);
                  this.activeChiose[index].currentPage = item.currentPage;
                  this.$refs.multipleSelection.toggleRowSelection(item, true);
                }

                //     this.tableList.forEach(course => {
                //   if (idList.indexOf(course.skuStockId) != -1) {
                //     this.$refs.multipleSelection.toggleRowSelection(course, true);
                //   }
                // });
              });
            });
          }
        });
      } catch {
        //
      }
    },
    async onSubmit() {
      const userList = [];
      this.activeChiose.forEach(item => {
        userList.push({
          name: item.realName || item.name,
          id: item.id
        });
      });
      console.log(userList, "this.activeChiose");
      this.$emit("confirm", userList);
      this.$emit("close");
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: block;
  text-align: right;
}
</style>
