<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      学校账号管理
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
        ref="saveForm"
      >
        <el-form-item prop="keyword">
          <el-input
            v-model.trim="searchForm.keyword"
            class="seachInput"
            clearable
            @keyup.enter.native="
              (e) => {
                e.target.blur();
                $refs.saveForm.save();
                search();
              }
            "
            placeholder="老师姓名/编号/手机号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            style="width: 180px !important"
            class="multiple"
            v-model.trim="searchForm.organId"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="schoolId">
          <el-select
            v-model.trim="searchForm.schoolId"
            :disabled="!searchForm.organId"
            filterable
            clearable
            placeholder="请选择合作单位"
          >
            <el-option
              v-for="(item, index) in cooperationList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></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
          style="width: 100%"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="tableList"
        >
          <el-table-column
            align="center"
            prop="userId"
            label="用户编号"
          ></el-table-column>
          <el-table-column align="center" prop="organName" label="分部"></el-table-column>
          <el-table-column
            align="center"
            prop="schoolName"
            label="合作单位"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="username"
            label="老师姓名"
          ></el-table-column>
          <el-table-column align="center" prop="userType" label="账号类型">
            <template slot-scope="scope">
              <div>{{ scope.row.userType | schoolUserType }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status" label="账号状态">
            <template slot-scope="scope">
              <div>{{ scope.row.status | schoolUserStatus }}</div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="mobile"
            label="联系电话"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="createTime"
            label="注册日期"
          ></el-table-column>
          <el-table-column align="center" prop="studentId" label="操作">
            <template slot-scope="scope">
              <div>
                <auth auths="schoolStaff/update">
                  <el-button
                    type="text"
                    v-if="scope.row.status == 1"
                    @click="updateStatus(scope.row)"
                    >冻结</el-button
                  >
                  <el-button
                    type="text"
                    v-if="scope.row.status == 9"
                    @click="updateStatus(scope.row)"
                    >启用</el-button
                  >
                </auth>
                <auth auths="schoolStaff/updateAccount">
                  <el-button type="text" @click="resetCount(scope.row)">修改</el-button>
                </auth>
                <auth auths="schoolStaff/remove">
                  <el-button
                    type="text"
                    v-if="scope.row.status == 9"
                    @click="removeTeacherCount(scope.row)"
                    >删除</el-button
                  ></auth
                >
                <auth auths="schoolStaff/resetPassword">
                  <el-button type="text" @click="resetPwd(scope.row)"
                    >重置密码</el-button
                  ></auth
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          sync
          :total.sync="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>

    <el-dialog title="修改" width="450px" :visible.sync="dialogFormVisible">
      <updateAccountModels
        :activeRow="activeRow"
        ref="updateAccountModelsRef"
        v-if="dialogFormVisible"
        @close="
          () => {
            dialogFormVisible = false;
            getList();
          }
        "
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button @click="submitMessage" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import load from "@/utils/loading";
import { getTimes } from "@/utils";
import { queryByOrganId } from "@/api/systemManage";
import { courseType, courseListType } from "@/utils/searchArray";
import {
  getSchoolStaff,
  schoolStaffUpdate,
  schoolStaffRemove,
  schoolStaffResetPwd,
} from "./api";
import updateAccountModels from "./modals/updateAccountModels";
export default {
  components: { pagination, updateAccountModels },
  data() {
    return {
      searchForm: {
        keyword: null,
        organId: null,
        schoolId: null,
      },
      courseType,
      tableList: [],
      organList: [],
      cooperationList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      dialogFormVisible: false,
      activeRow: null,
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 获取分部
    this.$store.dispatch("setBranchs");
    this.init();
  },
  methods: {
    init() {
      this.getList();
    },
    async getList() {
      try {
        let { timer, ...rest } = this.searchForm;
        let params = {
          ...rest,
          page: this.rules.page,
          rows: this.rules.limit,
          ...getTimes(timer, ["startTime", "endTime"]),
        };
        const res = await getSchoolStaff({
          ...params,
          page: this.rules.page,
          rows: this.rules.limit,
        });
        this.tableList = res.data.rows;
        this.rules.total = res.data.total;
      } catch (e) {
        console.log(e);
      }
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.$nextTick(() => {
        this.getList();
      });
    },
    resetCount(row) {
      this.activeRow = row;
      this.dialogFormVisible = true;
      console.log(row);
    },
    async updateStatus(row) {
      let str = "";
      let status = "";
      if (row.status == 1) {
        // 冻结
        str = `是否冻结"${row.username}"该老师账号`;
        status = "9";
      } else {
        // 启用
        str = `是否启用"${row.username}"该老师账号`;
        status = "1";
      }
      this.$confirm(str, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await schoolStaffUpdate({ id: row.id, status });
            if (row.status == 1) {
              this.$message.success("冻结成功");
            } else {
              this.$message.success("启用成功");
            }

            this.getList();
          } catch (e) {
            console.log(e);
          }
        })
        .catch((e) => {
          console.log(e);
        });
      console.log(row);
    },
    async removeTeacherCount(row) {
      try {
        await this.$confirm(`是否删除"${row.username}"该老师`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const res = await schoolStaffRemove({ id: row.id });
        this.$message.success("删除成功");
        this.getList();
      } catch (e) {
        console.log(e);
      }
    },
    async resetPwd(row) {
      try {
        await this.$confirm(
          `是否将"${row.username}"该老师的密码重置为gym+手机号后4位`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
        const res = await schoolStaffResetPwd({ userId: row.userId });
        this.$message.success("重置成功");
        this.getList();
      } catch (error) {
        console.log(error);
      }
    },
    submitMessage() {
      this.$refs.updateAccountModelsRef.submit();
    },
  },
  watch: {
    "searchForm.organId"(val) {
      if (val) {
        queryByOrganId({ organId: val, enable: false }).then((res) => {
          if (res.code == 200) {
            this.cooperationList = res.data;
          }
        });
      }
    },
    // "searchForm.cooperationId"(val) {
    //   if (val) {
    //     getMusicGroup({ cooperationId: val }).then((res) => {
    //       this.musicList = res.data;
    //     });
    //   }
    // },
  },
};
</script>
<style lang="scss">
.seachInput {
  .el-input__inner {
    width: 200px !important;
  }
}
</style>
