<template>
  <div>
    <back-box>
      <template slot="title">
        <span>账号管理</span>
      </template>
      <template slot="btns" v-if="role == 'ROLE_JITUAN'">
        <!-- 暂未有接口 -->
        <!-- <el-tooltip effect="dark" content="导入账号" placement="bottom">
          <el-button
            type="primary"
            icon="el-icon-upload2"
            size="mini"
            plain
            circle
            @click="diaUp = true"
          ></el-button>
        </el-tooltip> -->
        <el-tooltip
          effect="dark"
          content="添加账号"
          placement="bottom"
          v-if="!code"
        >
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            plain
            circle
            @click="openAddDia"
          ></el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="账号同步" placement="bottom" v-else>
          <el-button
            v-loading="syncLoading"
            type="primary"
            icon="el-icon-refresh"
            size="mini"
            plain
            circle
            @click="refreshAcc"
          ></el-button>
        </el-tooltip>
      </template>
    </back-box>
    <div class="answer-header">
      <div class="sel-box">
        <el-cascader
          size="small"
          v-if="role == 'ROLE_JITUAN'"
          class="sel"
          clearable
          placeholder="选择学校"
          v-model="query.schoolIds"
          :options="schoolList"
          :props="props"
          :show-all-levels="false"
        ></el-cascader>
        <el-select
          v-else
          class="sel"
          v-model="query.roleId"
          placeholder="选择账号角色"
          @change="(page = 1), _QueryData(1)"
        >
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-select
          class="sel"
          v-model="query.available"
          placeholder="选择账号状态"
          @change="(page = 1), _QueryData(1)"
        >
          <el-option label="正常" :value="0"></el-option>
          <el-option label="禁用" :value="1"></el-option>
        </el-select>
        <el-input
          :placeholder="role != 'ROLE_JITUAN' ? '请输入老师账号' : '请输入账号'"
          v-model="query.loginName"
          class="input-with-select sel"
          type="number"
          clearable
          oninput="if(value.length > 11) value = value.slice(0,11)"
          @keyup.enter.native="(page = 1), _QueryData(2)"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="(page = 1), _QueryData(2)"
          ></el-button>
        </el-input>
        <el-input
          placeholder="请输入老师姓名"
          maxlength="30"
          v-model="query.realName"
          class="input-with-select"
          clearable
          @keyup.enter.native="(page = 1), _QueryData(3)"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="(page = 1), _QueryData(3)"
          ></el-button>
        </el-input>
        <el-button
          v-if="role == 'ROLE_JITUAN'"
          type="primary"
          round
          @click="(page = 1), _QueryData(4)"
          >筛选</el-button
        >
      </div>
    </div>
    <div class="table-box">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column
          prop="loginName"
          label="账号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="realName"
          label="姓名"
          align="center"
        ></el-table-column>
        <el-table-column prop="roleList" label="角色" align="center">
          <template slot-scope="scoped">
            <span v-for="(item, index) in scoped.row.roleList" :key="item.id">{{
              `${item.roleName}${
                index != scoped.row.roleList.length - 1 ? "、" : ""
              }`
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="role == 'ROLE_JITUAN'"
          prop="regionList"
          label="管辖范围"
          align="center"
        >
          <template slot-scope="scoped" v-if="scoped.row.schoolList.length">
            <span v-for="item in scoped.row.schoolList" :key="item.id">{{
              item.schoolName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="available" label="状态" align="center"
          ><template slot-scope="scoped">{{
            `${scoped.row.available == 0 ? "正常" : "禁用"}`
          }}</template></el-table-column
        >
        <el-table-column
          prop="createdTime"
          label="创建时间"
          align="center"
          width="200"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="160" v-if="!code">
          <template slot-scope="scoped">
            <el-tooltip content="修改账号" placement="left">
              <el-button
                class="set-count"
                type="primary"
                circle
                icon="el-icon-edit-outline"
                size="mini"
                @click="setCount(scoped.row)"
              ></el-button>
            </el-tooltip>
            <el-dropdown
              trigger="hover"
              @command="handleDropdownClick($event, scoped.row)"
            >
              <el-button
                type="info"
                size="mini"
                circle
                icon="el-icon-more"
              ></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="0">重置密码</el-dropdown-item>
                <el-dropdown-item :command="1">{{
                  `${scoped.row.available == 0 ? "禁用" : "启用"}`
                }}</el-dropdown-item>
                <el-dropdown-item :command="2">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-box">
        <el-pagination
          layout="total,prev, pager, next"
          :hide-on-single-page="true"
          :total="total"
          @current-change="changePage"
          :current-page="page"
          :page-size="size"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" title="修改账号信息" :visible.sync="diaCount" width="400">
      <el-form
        class="form-box"
        :model="formCount"
        :rules="ruleCount"
        ref="formCount"
        label-width="160px"
      >
        <el-form-item label="手机号码：" prop="loginName">
          <el-col :span="12">
            <el-input
              placeholder="请输入联系电话"
              v-model.trim="formCount.loginName"
              clearable
              maxlength="11"
            >
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="姓名：" prop="realName">
          <el-col :span="12">
            <el-input
              placeholder="请输入教师姓名"
              v-model.trim="formCount.realName"
              clearable
              maxlength="11"
            >
            </el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="saveCount">确 定</el-button>
        <el-button @click="diaCount = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="添加账号" :visible.sync="diaAdd" width="400">
      <el-form
        class="form-box"
        :model="formAddCount"
        :rules="ruleAddCount"
        ref="formAddCount"
        label-width="160px"
      >
        <el-form-item label="手机号码：" prop="phone">
          <el-col :span="12">
            <el-input
              placeholder="请输入联系电话"
              v-model.trim="formAddCount.phone"
              type="number"
              clearable
              oninput="if(value.length > 11) value = value.slice(0,11)"
            >
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-col :span="12">
            <el-input
              placeholder="请输入密码"
              v-model.trim="formAddCount.password"
              clearable
              maxlength="18"
            >
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="姓名：" prop="realName">
          <el-col :span="12">
            <el-input
              placeholder="请输入姓名"
              v-model.trim="formAddCount.realName"
              clearable
              maxlength="30"
            >
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="选择角色：" prop="roleId">
          <el-col :span="12">
            <el-select
              class="sel"
              v-model="formAddCount.roleId"
              placeholder="选择角色"
            >
              <el-option
                v-for="item in tenantRoleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item
          v-if="permissionLevel(formAddCount.roleId) != 6"
          label="选择管辖范围："
          :prop="
            permissionLevel(formAddCount.roleId) == 5 ? 'regionId' : 'schoolId'
          "
        >
          <el-col :span="12">
            <el-select
              v-show="permissionLevel(formAddCount.roleId) == 5"
              class="sel"
              v-model="formAddCount.regionId"
              placeholder="选择管辖范围"
            >
              <el-option
                v-for="item in regionList"
                :key="item.id"
                :label="item.regionName"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              v-show="permissionLevel(formAddCount.roleId) == 4"
              class="sel"
              v-model="formAddCount.schoolId"
              placeholder="选择管辖范围"
            >
              <el-option
                v-for="item in addSelectSchoolList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="saveAddCount">确 定</el-button>
        <el-button @click="diaAdd = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="导入账号名单" :visible.sync="diaUp" width="600">
      <up-load
        id="downTeacher"
        :url="url"
        @upSuccess="upSuccess"
        fileName="教师名单"
      >
        <p class="down-txt" slot="down">
          通过Excel名单导入账号名单，点击
          <el-link type="danger" @click="downExcel">模板下载</el-link> 。
        </p>
      </up-load>
      <div class="dialog-footer" slot="footer">
        <el-button @click="diaUp = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { encryptLoginPassword } from "@/utils";
export default {
  data() {
    return {
      code: "",
      role: "",
      diaUp: false,
      diaAdd: false,
      url: "", //上传地址
      loading: false,
      syncLoading: false,
      diaCount: false,
      tenantRoleList: [],
      regionList: [],
      schoolList: [],
      schoolAll: [],
      props: { multiple: true, checkStrictly: true },
      roleList: [],
      query: {
        schoolIds: [],
        roleId: "",
        available: "",
        loginName: "",
        realName: "",
      },
      tableData: [],
      total: 0,
      page: 1,
      size: 20,
      formCount: {
        userId: "",
        loginName: "",
        realName: "",
      },
      ruleCount: {
        loginName: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请输入教师姓名", trigger: "blur" },
        ],
      },
      formAddCount: {
        phone: "",
        realName: "",
        password: "",
        roleId: "",
        regionId: "",
        schoolId: "",
      },
      addSelectSchoolList: [],
      ruleAddCount: {
        phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
        regionId: [
          { required: true, message: "请选择权限区域", trigger: "blur" },
        ],
        schoolId: [
          { required: true, message: "请选择权限区域", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.code = localStorage.getItem("csCode") || "";
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    if (this.role == "ROLE_JITUAN") {
      this._TenantRoleList();
      this._RegionList();
      this.showSchool();
    } else {
      this._RoleList();
    }
    this._QueryData(4);
  },
  methods: {
    permissionLevel(id) {
      let permissionLevel;
      this.tenantRoleList.map((item) => {
        if (item.id == id) {
          permissionLevel = item.permissionLevel;
        }
      });
      return permissionLevel;
    },
    async refreshAcc() {
      //长水账号同步
      if (this.syncLoading) return;
      this.syncLoading = true;
      const { data, status, info } = await this.$request.syncUser();
      this.syncLoading = false;
      if (status === 0) {
        this.$message.success("同步中，请稍后刷新重试～");
        // this._QueryData(4);
      } else {
        this.$message.error(info);
      }
    },
    upSuccess(res) {
      //导入成功
      this.$message.closeAll();
      this.$message({
        showClose: true,
        message: `成功（${res.data.success}）`,
        type: "success",
        duration: 5000,
      });
      this.diaUp = false;
      this._QueryData(4);
    },
    async downExcel() {
      let data = await this.$request.downDevice();
      if (data && !data.code) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`账号信息.xlsx`, blob);
      } else {
        this.$message.error(data.info);
      }
    },
    openAddDia() {
      //添加账号
      this.formAddCount.phone = "";
      this.formAddCount.realName = "";
      this.formAddCount.password = "";
      this.formAddCount.roleId = "";
      this.formAddCount.regionId = "";
      this.formAddCount.schoolId = "";
      this.diaAdd = true;
    },
    saveAddCount() {
      this.$refs.formAddCount.validate(async (valid) => {
        if (valid) {
          let params = { ...this.formAddCount };
          params.password = encryptLoginPassword(params.password);
          const { data, status, info } = await this.$request.addUser({
            ...params,
          });
          if (status === 0) {
            this.$message.success(info);
            this._QueryData(4);
            this.diaAdd = false;
          } else {
            this.$message.error(info);
          }
        } else {
          this.$message.warning("输入有误请检查！");
          return false;
        }
      });
    },
    setCount(obj) {
      if (this.role != "ROLE_JITUAN") {
        this.formCount.userId = obj.userId;
      } else {
        this.formCount.userId = obj.id;
      }
      this.formCount.loginName = obj.loginName;
      this.formCount.realName = obj.realName;
      this.diaCount = true;
    },
    handleDropdownClick(value, item) {
      console.log(item);
      //更多
      if (value == 2) {
        this.$confirm("确定要删除这条账号信息吗？", "提示", {
          customClass: "del-model",
          cancelButttonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }).then(() => {
          this.updateUser(item, value);
        });
      } else {
        this.updateUser(item, value);
      }
    },
    changePage(page) {
      this.page = page;
      this._QueryData(4);
    },

    saveCount() {
      this.$refs.formCount.validate(async (valid) => {
        if (valid) {
          const { data, status, info } =
            this.role != "ROLE_JITUAN"
              ? await this.$request.updateUser({
                  type: 3,
                  ...this.formCount,
                })
              : await this.$request.tenantUpdateUser({
                  type: 3,
                  ...this.formCount,
                });
          if (status === 0) {
            this.$message.success(info);
            this.diaCount = false;
            this._QueryData(4);
          } else {
            this.$message.error(info);
          }
        } else {
          this.$message.warning("输入有误请检查！");
          return false;
        }
      });
    },
    async showSchool() {
      const { data, status, info } = await this.$request.schoolList();
      if (status === 0) {
        (this.addSelectSchoolList = data.list?.map((item) => {
          return {
            value: item.id,
            label: item.schoolName,
          };
        })),
          (this.schoolAll = [
            {
              value: 0,
              label: "全部",
              children: [...this.addSelectSchoolList],
            },
          ]);
        this.schoolList = [...this.schoolAll, ...this.schoolList];
      } else {
        this.$message.error(info);
      }
    },
    async updateUser(obj, type) {
      let query = {};
      console.log(query);
      if (type == 1) {
        query.available = obj.available == 0 ? 1 : 0;
      }
      const { data, status, info } =
        this.role != "ROLE_JITUAN"
          ? await this.$request.updateUser({
              userId: obj.userId,
              type: type,
              ...query,
            })
          : await this.$request.tenantUpdateUser({
              userId: obj.id,
              type: type,
              ...query,
            });
      if (status === 0) {
        this.$message.success(info);
        this._QueryData(4);
      } else {
        this.$message.error(info);
      }
    },
    async _RoleList() {
      const { data, status, info } = await this.$request.roleList();
      if (status === 0) {
        this.roleList = data.list || [];
      } else {
        this.$message.error(info);
      }
    },
    async _TenantRoleList() {
      //集团-添加账号权限
      const { data, status, info } = await this.$request.tenantRoleList();
      if (status === 0) {
        this.tenantRoleList = data.list || [];
      } else {
        this.$message.error(info);
      }
    },
    async _RegionList() {
      //集团-区域列表
      const { data, status, info } = await this.$request.regionList();
      if (status === 0) {
        this.regionList = [...data.list] || [];
        this.schoolList = data.list?.map((item) => {
          let children = item.schoolList?.map((items) => {
            return {
              value: items.id,
              label: items.schoolName,
            };
          });
          return {
            value: item.id,
            label: item.regionName,
            children: children,
          };
        });
        this.schoolList = [...this.schoolAll, ...this.schoolList];
      } else {
        this.$message.error(info);
      }
    },
    setQuery(type) {
      //整理请求参数
      let query = {};
      if (type == 1) {
        query.roleId = this.query.roleId;
        query.available = this.query.available;
        this.query.loginName = "";
        this.query.realName = "";
      } else if (type == 2) {
        this.query.roleId = "";
        this.query.available = "";
        this.query.schoolIds = [];
        query.loginName = this.query.loginName;
        this.query.realName = "";
      } else if (type == 3) {
        this.query.schoolIds = [];
        this.query.roleId = "";
        this.query.available = "";
        this.query.loginName = "";
        query.realName = this.query.realName;
      } else {
        query = { ...this.query };
      }
      if (this.role == "ROLE_JITUAN") {
        let isAll = false;
        query.schoolIds?.map((item) => {
          if (item.length == 1) {
            isAll = true;
          }
        });
        query.schoolIds = isAll
          ? null
          : query.schoolIds?.map((item) => {
              return item[1];
            });
        delete query.roleId;
      } else {
        delete query.schoolIds;
      }
      return query;
    },
    async _QueryData(type) {
      let query = this.setQuery(type);
      this.loading = true;
      this.tableData = [];
      let userPage =
        this.role != "ROLE_JITUAN"
          ? this.$request.userPage
          : this.$request.tenantUserPage;
      const { data, status, info } = await userPage({
        ...query,
        page: this.page,
        size: this.size,
      });

      this.loading = false;
      if (status === 0) {
        this.tableData = data.list || [];
        this.total = data.count;
      } else {
        this.$message.error(info);
      }
    },
  },
};
</script>
<style  lang="scss">
.del-model {
  .el-message-box__btns button:nth-child(1) {
    color: #667ffd;
  }
}
</style>
<style lang="scss" scoped>
.el-message-box .el-button--default {
  color: red;
}
.set-count {
  margin-right: 12px;
}
.table-box {
  padding: 0 20px;
}
.answer-header {
  .sel-box {
    .sel {
      margin-right: 20px;
    }
  }
  :deep(.el-input-group__append) {
    padding: 0 20px 0 12px;
  }
}
</style>