<template>
  <div class="en-auth-manage-wrap">
    <div class="select-wrap">
      <div class="select">
        <el-cascader
          v-model="users"
          placeholder="请选择用户"
          :options="options"
          :props="props"
          collapse-tags
          :show-all-levels="false"
          :key="modifySelect"
          clearable
          @change="changeSelect"
          filterable
        ></el-cascader>
        <el-button
          type="primary"
          style="margin-left: 20px"
          @click="addAdmins"
          >确 定</el-button
        >
      </div>
      <div class="result-list">
        <div class="result-item" v-for="item in selectList" :key="item.AdminId">
          <span>{{ item.RealName }}</span>
          <i class="el-icon-error" @click="handleDeleteResult(item)"></i>
        </div>
      </div>
    </div>
    <div class="operations-table">
      <div class="table-title">
        <span>英文权限列表</span>
      </div>
      <el-table :data="tableData" border v-loading="isShowloadding">
        <el-table-column
          v-for="item in tableColumns"
          :key="item.label"
          :label="item.label"
          :prop="item.key"
          align="center"
        >
          <template slot-scope="{ row }">
            <span v-if="item.key === 'Enabled'">
              {{ row[item.key] === 0 ? "已禁用" : "已启用" }}
            </span>
            <div v-else-if="item.key === 'RealName'">
              <el-tag
                size="small"
                v-if="row.LabelVal"
                :style="
                  row.LabelVal == 1 || row.LabelVal == 2
                    ? 'color:#fff;background:#409EFF'
                    : 'color:#409EFF;background:#ECF5FF'
                "
                style="position: absolute; left: 10px"
                >{{
                  row.LabelVal == 1
                    ? "超管"
                    : row.LabelVal == 2
                    ? "管理员"
                    : row.LabelVal == 3
                    ? "部门经理"
                    : row.LabelVal == 4
                    ? "组长"
                    : "主管"
                }}</el-tag
              >
              <span style="position: relative">{{ row.RealName }}</span>
            </div>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot="header" slot-scope="{}">
            <span>操作</span>
            <el-tooltip
              effect="dark"
              placement="top-start"
              content="此项删除仅删除该用户的英文销售权限"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <span @click="setAuth(row)"
              style="cursor: pointer; color:#409eff;"
            >设置权限</span>
            <span
              @click="handleDeleteAuth(row)"
              style="cursor: pointer; color: #d1433a"
              >删除</span
            >
          </template>
        </el-table-column>
        <div slot="empty" style="lineheight: 44px; margin: 60px 0; color: #999">
          <img
            src="~@/assets/img/cus_m/nodata.png"
            alt=""
            style="display: block; width: 160px; height: 128px; margin: auto"
          />
          <span>暂无数据</span>
        </div>
      </el-table>
      <el-pagination
        layout="total,prev,pager,next,jumper"
        background
        :current-page="page_no"
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        :total="total"
        style="text-align: end; margin-top: 20px"
      >
      </el-pagination>
    </div>
    <!-- 设置权限弹窗 -->
    <el-dialog 
      v-dialogDrag 
      :append-to-body="false" 
      :modal-append-to-body	="false"
      :visible.sync="setAuthData.show" 
      width="689px" 
      title="设置权限"
    >
      <div class="dialog-content-wrap">
        <div class="user-info">
          <span>姓名：{{setAuthData.RealName}}</span>
          <span>角色：{{setAuthData.RoleName}}</span>
          <span>部门/组织：{{setAuthData.DepartmentGroup}}</span>
        </div>
        <div class="select-list">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="setAuthData.selectList" @change="handleCheckedChange">
              <el-checkbox v-for="auth in authOptions" :label="auth.code" :key="auth.code" >{{auth.label}}</el-checkbox>
            </el-checkbox-group>
        </div>
      </div>
      <div slot="footer" class="foot-container">
        <el-button type="primary" @click="saveChange">确 定</el-button>
        <el-button @click="setAuthData.show=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { departInterence,enAuthInterence } from "@/api/api.js";
export default {
  data() {
    return {
      users: "",
      selectList: [],
      tableColumns: [
        {
          label: "姓名",
          key: "RealName",
        },
        {
          label: "手机号",
          key: "Mobile",
        },
        {
          label: "角色",
          key: "RoleName",
        },
        {
          label: "部门/分组",
          key: "DepartmentGroup",
        },
        {
          label: "状态",
          key: "Enabled",
        },
      ],
      options: [],
      props: {
        value: "AdminId",
        label: "RealName",
        children: "ChildrenList",
        multiple: true,
      },
      modifySelect: 0, //重新渲染级联选择框
      tableData: [],
      search_txt: "",
      page_no: 1,
      pageSize: 10,
      total: 1,
      isShowloadding: false,
      setAuthData:{
        AdminId:0,
        show:false,
        DepartmentGroup:'',
        RealName:'',
        RoleName:'',
        selectList:[]
      },
      authOptions:[
        {
          code:'english_company_admin',
          label:'英文客户列表'
        },{
          code:'english_report_admin',
          label:'英文研报'
        },{
          code:'english_ppt_admin',
          label:'英文PPT'
        },{
          code:'english_day_new_admin',
          label: '每日资讯'
        }],//权限设置页面选项
      isIndeterminate:false,//权限设置 全选样式
      checkAll:true,//权限设置 全选值
    };
  },
  methods: {
    handleCurrentChange(page) {
      this.page_no = page;
      this.getTableData();
    },
    changeSelect() {
      //根据users的值,生成select-list
      //select-list:[index,name],index:在users里的索引值,name:在user里,实际选择的那项的label值:user[0][user[0].length-1].label
      if (this.users.length === 0) {
        this.modifySelect = 0;
        this.selectList = [];
        return;
      }
      const findItem = (ids) => {
        let data = this.options;
        let item = null;
        for (let i = 0; i < ids.length; i++) {
          item = data.find((_item) => _item.AdminId === ids[i]);
          if (item.ChildrenList) {
            data = item.ChildrenList;
          }
        }
        return item;
      };
      this.selectList = [];
      this.users.forEach((item) => {
        const temp = findItem(item);
        this.selectList.push(temp);
      });
    },
    handleDeleteResult(item) {
      //从select-list和users删除这一项
      const userIndex = this.users.findIndex((i) => {
        return i[i.length - 1] === item.AdminId;
      });
      this.users.splice(userIndex, 1);
      this.modifySelect++;
      const selectIndex = this.selectList.findIndex(
        (i) => i.AdminId === item.AdminId
      );
      this.selectList.splice(selectIndex, 1);
    },
    handleDeleteAuth(item) {
      this.$confirm(
          '确定要删除吗',
          '提示',
          {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
          }
        ).then(()=>{
          this.deleteAuth(item.AdminId)
        })
    },
    async deleteAuth(AdminId){
      const res = await enAuthInterence.deleteAuthAdmin({
        AdminId: AdminId,
      });
      if (res.Ret === 200) {
        this.$message.success("删除成功");
        this.page_no = 1
        this.getTableData();
      }
    },
    async addAdmins() {
      if (!this.selectList.length) return;
      const adminArr = [];
      this.selectList.map((item) => {
        adminArr.push(item.AdminId);
      });
      const res = await enAuthInterence.addAuthAdmins({
        AdminIds: adminArr.join(","),
      });
      if (res.Ret === 200) {
        this.$message.success("配置成功");
        this.page_no = 1;
        this.getTableData();
      }
    },
    async getAdminList() {
      const res = await departInterence.getQuestionAdminList();
      if (res.Ret === 200) {
        this.options = res.Data.List;
      }
    },
    async getTableData() {
      this.isShowloadding = true;
      const res = await enAuthInterence.getAuthList({
        PageSize: this.pageSize,
        CurrentIndex: this.page_no,
      });
      if (res.Ret === 200) {
        const { List, Paging } = res.Data;
        this.tableData = List;
        this.page_no = Paging.CurrentIndex;
        this.total = Paging.Totals;
      } else if (res.Ret === 403) {
        //无权查看,清空tableData
        this.tableData = [];
        this.page_no = 1;
        this.total = 0;
      }
      this.isShowloadding = false;
    },
    async setAuth(data){
      this.setAuthData = {
        AdminId:data.AdminId,
        show:true,
        RealName:data.RealName,
        RoleName:data.RoleName,
        DepartmentGroup:data.DepartmentGroup,
        selectList:[]
      }
      const res = await enAuthInterence.getAuthDetail({AdminId:data.AdminId})
      if(res.Ret!==200) return
      //根据data.selectList的值设置全选的样式
      const list = res.Data||[]
      let selectList = []
      list.forEach(item=>{
        if(item.AuthOk){
          selectList.push(item.RoleTypeCode)
        }
      })
      this.setAuthData.selectList = selectList
      this.handleCheckedChange(selectList)
    },
    handleCheckedChange(val){
      let checkedCount = val.length;
      this.checkAll = checkedCount === this.authOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.authOptions.length;
    },
    handleCheckAllChange(val){
      this.setAuthData.selectList = val ? this.authOptions : [];
      this.isIndeterminate = false;
    },
    async saveChange(){
      if(this.setAuthData.selectList.length===0){
        this.$message.warning('至少保留一个权限')
        return
      }
      const {AdminId,selectList} = this.setAuthData
      const res = await enAuthInterence.editAuthAdmin({
        AdminId:AdminId,
        RoleTypeCodes:selectList.join(',')
      })
      if(res.Ret!==200) return
      this.$message.success('设置成功')
      this.setAuthData.show = false
    }
  },
  mounted() {
    this.getAdminList();
    this.getTableData();
  },
};
</script>
<style lang="scss">
.en-auth-manage-wrap {
  .select-wrap {
    .select {
      .el-cascader {
        .el-tag {
          background: #f0f2f5;
          span {
            color: #909399;
          }
          i {
            color: white;
            background: #909399;
            &:hover {
              background: #a5a8af;
            }
          }
        }
      }
    }
  }
  .el-dialog{
    .el-dialog__body{
      padding:0 !important;
    }
  }
}
</style>
<style scoped lang="scss">
.en-auth-manage-wrap {
  padding: 20px 30px;
  background: #fff;
  border: 1px solid #ececec;
  border-radius: 4px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  .select-wrap{
      margin-bottom: 28px;
  }
  .operations-table {
    margin-bottom: 0;
    .table-title {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }
  }
  .result-list {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    .result-item {
      margin: 10px 10px 0 0;
      padding: 5px 10px;
      background-color: #f0f2f5;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      span,
      i {
        color: #909399;
        font-size: 14px;
      }
      span {
        margin-right: 5px;
      }
      i {
        cursor: pointer;
        &:hover {
          color: #a5a8af;
        }
      }
    }
  }
  .dialog-content-wrap{
    padding:40px 100px;
    .user-info{
      padding-bottom: 20px;
      margin-bottom: 20px;
      border-bottom: 1px solid #DCDFE6;
      display: flex;
      justify-content: space-between;
    }
    .select-list{
      background-color: #F0F2F5;
      padding:20px;
      .el-checkbox-group{
        margin-top: 20px;
      }
    }
  }
  .foot-container{
    text-align: center;
  }
}
</style>
