<template>
  <div id="index">
    <list-frame title="教师列表页" @query="search" :total="total" :filter="filFields" :needAdd="true" @add="add()">
      <template #options="{item}">
        <template v-if="item.model == 'gender'">
          <el-option v-for="(item, index) in gender" :key="index" :value="item.label"></el-option>
        </template>
        <template v-if="item.model == 'status'">
          <el-option v-for="(item, index) in lists" :key="index" :label="item.label" :value="item.value"></el-option>
        </template>
      </template>
      <el-row type="flex" align="middle" justify="end" class="btn_bar">
        <!-- <el-col :span="3" style="text-align:right;padding:0 10px;">
          <el-button type="primary" size="mini" @click="printView()">打印预览</el-button>
        </el-col> -->
        <el-col :span="2">
          <el-button type="primary" size="mini" @click="eDialog = true">导出excel</el-button>
        </el-col>
        <el-col :span="3">
          <el-button size="mini" type="primary" @click="downloadTemplate">下载上传教师评分模板</el-button>
        </el-col>
        <el-col :span="2">
          <el-button size="mini" type="primary" @click="selectDisplay">选择显示</el-button>
        </el-col>
        <el-col :span="3">
          <el-upload action="/files/train/score/upload" :show-file-list="false" :on-success="handleSuccess" :on-error="handleError" multiple>
            <el-button size="mini" type="primary">点击上传教师评分</el-button>
          </el-upload>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" size="mini" @click="toIntegral"></el-button>
        </el-col>
      </el-row>
      <data-table :fields="fields" :data="list" :opera="opera" @share="share" @edit="toEdit" @delete="toDelete" @select="toSelect" @star="toStar">
        <template #custom="{item,row}">
          <template v-if="item.prop === 'is_bind'">
            <span :style="{ color: `${row[item.prop] ? '#67C23A' : '#F56C6C'}` }">{{ row[item.prop] ? '已激活' : '未激活' }}</span>
          </template>
        </template>
      </data-table>
    </list-frame>
    <el-dialog :visible.sync="dialog" title="添加教师" @close="toClose" width="50%">
      <data-form :data="form" :fields="tearcherForm" :rules="rules" @save="turnSave"> </data-form>
    </el-dialog>
    <el-dialog :visible.sync="columnDialog" title="显示列" @close="toClose" width="50%">
      <el-row>
        <el-checkbox-group v-model="columnSelect">
          <el-col :span="4" v-for="(i, index) in columns" :key="index">
            <el-checkbox :label="i.prop">{{ i.label }}</el-checkbox>
          </el-col>
        </el-checkbox-group>
        <el-col :span="24">
          <el-button type="primary" @click="changeColumns">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog title="导出" center :visible.sync="eDialog">
      <el-card>
        <template #header>
          <el-row>
            <el-col :span="24">选择导出的字段-教师表(点击字段可以更换顺序)</el-col>
            <el-col :span="24">
              <span v-for="(i, index) in selectModel" :key="`select-${index}`" style="padding-right:15px;zoom:1.1">
                <el-link type="primary" v-if="index === selectIndex && index !== 0" icon="el-icon-back" @click="toChangePos(i, -1)"></el-link>
                <el-link @click="toDisplayPos(index)">{{ i }}</el-link>
                <el-link type="primary" v-if="index === selectIndex && index !== selectModel.length - 1" icon="el-icon-right" @click="toChangePos(i, 1)"></el-link>
              </span>
            </el-col>
          </el-row>
        </template>
        <el-checkbox-group v-model="selectModel">
          <el-row>
            <el-col :span="6" v-for="(i, index) in models.student" :key="`model-${index}`">
              <el-checkbox :label="i.zh" style="word-wrap: break-word">{{ i.zh }}</el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
      </el-card>
      <template #footer>
        <el-row type="flex" justify="space-around" :gutter="10" align="middle">
          <el-col :span="4">
            <el-button type="primary" size="small" @click="toExportExcel">导出</el-button>
          </el-col>
          <el-col :span="4">
            <el-button size="small" @click="eDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
    <el-dialog title="往期评分" center :visible.sync="StarDialog">
      <el-table :data="StarList" border stripe style="width: 100%">
        <el-table-column align="center" prop="name" label="教师名称"> </el-table-column>
        <el-table-column align="center" prop="create_time" label="归档时间"> </el-table-column>
        <el-table-column align="center" prop="xsscore" label="学生评分"> </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: right; margin: 10px 0 0 0;"
        background
        layout="sizes,total, prev, pager, next"
        :page-sizes="[10, 50, 100, 150, 200]"
        :total="StarTotal"
        :page-size="limit"
        :current-page.sync="currentPage"
        @current-change="changePage"
        @size-change="sizeChange"
      >
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash';
import listFrame from '@frame/layout/admin/list-frame';
import dataTable from '@frame/components/data-table';
import dataForm from '@frame/components/form';
import { createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('teacher');
const { mapActions: util } = createNamespacedHelpers('util');
const { mapActions: document } = createNamespacedHelpers('document');
export default {
  name: 'index',
  props: {},
  components: {
    listFrame,
    dataTable,
    dataForm,
  },
  data: () => ({
    gender: [
      { label: '男', value: '男' },
      { label: '女', value: '女' },
    ],
    lists: [
      { label: '注册', value: '0' },
      { label: '确认身份', value: '1' },
      { label: '资料评分', value: '2' },
      { label: '面试评分', value: '3' },
      { label: '确认入库', value: '4' },
    ],
    opera: [
      {
        label: '确认身份',
        icon: 'el-icon-check',
        method: 'share',
        display: item => {
          return item.schid == null && item.status == '0';
        },
      },
      {
        label: '编辑',
        icon: 'el-icon-edit',
        method: 'edit',
      },
      {
        label: '审核',
        icon: 'el-icon-s-order',
        method: 'select',
        display: item => {
          return item.status === '1' || item.status === '2' || item.status === '3';
        },
      },
      {
        label: '往期评分',
        icon: 'el-icon-star-on',
        method: 'star',
      },
    ],
    fields: [],
    list: [],
    filFields: [
      { label: '教师名称', model: 'name' },
      { label: '年龄', model: 'age' },
      {
        label: '状态',
        model: 'status',
        type: 'select',
      },
      {
        label: '性别',
        model: 'gender',
        type: 'select',
      },
    ],
    total: 0,
    // 添加教师
    dialog: false,
    form: {},
    tearcherForm: [
      { label: '教师姓名', required: true, model: 'name' },
      { label: '手机号', required: true, model: 'phone', options: { maxLength: 11, minLength: 11 } },
    ],
    rules: {
      name: [{ required: true, message: '请输入教师姓名' }],
      phone: [
        { required: true, message: '请输入手机号' },
        { min: 11, max: 11, message: '请输入11位手机号 ', trigger: 'blur' },
      ],
    },
    columnSelect: [],
    columnDialog: false,
    columns: [
      { label: '姓名', prop: 'name' },
      { label: '性别', prop: 'gender', options: { width: `80px` } },
      { label: '手机号', prop: 'phone' },
      { label: '账户密码', prop: 'secret' },

      { label: '学校名称', prop: 'schname' },
      { label: '邮箱', prop: 'email' },
      { label: '年龄', prop: 'age', options: { width: `80px` } },

      { label: '专业', prop: 'major' },
      {
        label: '是/否是礼仪老师',
        prop: 'islyteacher',
        format: item => {
          return item === '0' ? '否' : item === '1' ? '是' : '其他';
        },
      },
      { label: '学生评分', prop: 'xsscore', options: { width: `100px` } },
      { label: '资料评分', prop: 'zlscore', options: { width: `100px` } },
      { label: '面试评分', prop: 'msscore', options: { width: `100px` } },
      { label: '是否激活', prop: 'is_bind', custom: true },

      {
        label: '状态',
        prop: 'status',
        format: item => {
          return item === '0'
            ? '注册'
            : item === '1'
            ? '已确定身份'
            : item === '2'
            ? '已上传资料'
            : item === '3'
            ? '已选择面试'
            : item === '4'
            ? '确认入库'
            : '其他';
        },
      },
    ],
    eDialog: false,
    models: {},
    selectModel: [],
    selectIndex: '',
    // 往期评分
    skip: 0,
    limit: 10,
    StarList: [],
    StarTotal: 0,
    StarDialog: false,
    currentPage: 1,
  }),
  created() {
    this.$set(this, `fields`, this.columns);
    this.$set(
      this,
      'columnSelect',
      this.columns.map(i => i.prop)
    );
    this.search();
    this.toFindModel();
  },
  computed: {},
  methods: {
    ...util(['findModel']),
    ...mapActions(['query', 'delete', 'scoreImport', 'status', 'create', 'toExport']),
    ...document({ dCreate: 'create', dQuery: 'queryTeacher' }),
    async search({ skip = 0, limit = 10, ...info } = {}) {
      const res = await this.query({ skip, limit, ...info });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.$set(this, `total`, res.total);
      }
    },
    // 确定按钮
    async share({ data }) {
      let res = await this.status({ status: '1', teachersid: [data._id] });
      if (this.$checkRes(res, `确认身份成功`, res.errmsg || '确认身份失败')) this.search();
    },
    toEdit({ data }) {
      this.$router.push({ path: '/teacher/detail', query: { id: data.id } });
    },

    toSelect({ data }) {
      this.$router.push({ path: '/teacher/verify', query: { id: data.id } });
    },
    async toDelete(data) {
      const res = await this.delete(data.id);
      this.$checkRes(res, '删除成功', '删除失败');
      this.search();
    },
    //上传成功
    async handleSuccess(res, file) {
      if (this.$checkRes(res)) {
        let r = await this.scoreImport(res.uri);
        if (this.$checkRes(r, '上传成功', r.errmsg || '上传失败')) this.search();
      }
    },
    //上传失败
    handleError(err, file) {
      console.log(err, file);
      this.$message.error('请重新上传或联系开发人员');
    },
    downloadTemplate() {
      window.open('/files/teacherScoreTemplate.xlsx');
    },
    // 打印教师
    printView() {
      this.$router.push({ path: '/teacher/printTea', query: {} });
    },
    // 添加教师
    add() {
      this.dialog = true;
    },
    // 提交
    async turnSave({ data }) {
      data.status = '0';
      const res = await this.create(data);
      if (this.$checkRes(res, `创建成功`, res.errmsg || '创建失败')) this.search();
    },
    // 取消
    toClose() {
      this.from = {};
      this.dialog = false;
    },
    // 列显示选择
    selectDisplay() {
      this.columnDialog = true;
    },
    //改变显示列
    changeColumns() {
      const r = this.columns.filter(f => this.columnSelect.find(fc => fc == f.prop));
      this.$set(this, `fields`, r);
      this.columnDialog = false;
    },
    // 导出部分
    async toFindModel() {
      const res = await this.findModel('teacher');
      if (this.$checkRes(res)) {
        const { data } = res;
        if (!(data && _.isObject(data))) return;
        const keys = Object.keys(data);
        let obj = {};
        const arr = [];
        for (const key of keys) {
          const o = data[key];
          const { zh } = o;
          if (zh) {
            const ao = { zh };
            ao['model'] = key;
            arr.push(ao);
          }
        }
        obj['student'] = arr;
        this.$set(this, `models`, obj);
      }
    },
    // 显示已经选择的字段的移动位置按钮
    toDisplayPos(index) {
      this.selectIndex = index;
    },
    // 移动位置,
    toChangePos(data, num) {
      const dup = _.cloneDeep(this.selectModel);
      // 当前元素位置
      const di = dup.findIndex(f => f == data);
      // 要交换的元素位置及数据
      const ci = di + num;
      const c = dup[ci];
      // 交换
      dup[ci] = data;
      dup[di] = c;
      this.$set(this, `selectModel`, dup);
      // 将目标也跟随过去
      this.toDisplayPos(ci);
    },
    async toExportExcel() {
      let model = this.selectModel.map(i => {
        const om = this.models.student.find(f => f.zh == i);
        if (om) return om;
      });
      model = _.compact(model);
      const msg = this.$message({ duration: 0, message: '正在导出,请稍后...' });
      const res = await this.toExport({ model });
      msg.close();
      this.$checkRes(res, '任务已执行,请在 "菜单 - 待办事项" 中查看执行进度');
    },
    // 往期评分
    async toStar({ data }) {
      const res = await this.dQuery({ skip: this.skip, limit: this.limit, teacher: data.id || data._id });
      if (this.$checkRes(res)) {
        this.$set(this, `StarList`, res.data);
        this.$set(this, `StarTotal`, res.total);
        this.$set(this, `StarDialog`, true);
      }
    },
    // 分页
    changePage(page = this.currentPage) {
      this.toStar({ skip: (page - 1) * this.limit, limit: this.limit });
    },
    sizeChange(limit) {
      this.limit = limit;
      this.currentPage = 1;
      this.toStar({ skip: 0, limit: this.limit });
    },
    // 教师积分归档
    toIntegral() {
      this.$confirm('此操作将教师积分清零并且积分归档, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await this.dCreate({});
          this.$checkRes(res, `积分归档成功`, res.errmsg || '积分归档失败');
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
  },
};
</script>

<style lang="less" scoped></style>
