
<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <div style="margin-bottom: 20px">
        <el-radio-group v-model="tabselect" size="medium" @change="radioChange">
          <el-radio-button label="0">业务角色</el-radio-button>
          <!-- <el-radio-button label="1">公司角色</el-radio-button> -->
          <el-radio-button label="2">代理商角色</el-radio-button>
          <el-radio-button label="3">系统角色</el-radio-button>
        </el-radio-group>
      </div>
      <!-- <div style="margin-bottom:20px;">
    <div v-if="tabselect==0||tabselect==1">
      选择公司
      <el-select v-model="orgId" placeholder="请选择">
        <el-option
          v-for="item in orgList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
          :disabled="item.disabled">
        </el-option>
      </el-select>
    </div>
    <div v-if="tabselect==2">
      选择代理商
      <el-select v-model="agentId" placeholder="请选择">
        <el-option
          v-for="item in agentList"
          :key="item.id"
          :label="item.agentName"
          :value="item.id"
          :disabled="item.disabled">
        </el-option>
      </el-select>
    </div>
    <div v-if="tabselect==3">
      请选择系统
      <el-select v-model="value" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          >
        </el-option>
      </el-select>
    </div>
  </div> -->
      <el-row :span="24">
        <el-col :xs="24" :sm="24" :md="5" class="user__tree">
          <el-input placeholder="输入关键字进行过滤" v-model="filterText">
          </el-input>
          <div style="overflow: auto; height: 680px">
            <el-tree
              class="filter-tree"
              :data="treeDataList"
              node-key="id"
              :default-select-keys="selectKeys"
              :props="defaultProps1"
              :filter-node-method="filterNode"
              @node-click="nodeClick"
              ref="tree"
            >
            </el-tree>
          </div>
          <!-- <avue-tree
            :option="treeOption"
            :data="treeDataList"
            @node-click="nodeClick"
            >
            <span class="el-tree-node__label" slot-scope="{ node, data }">
              <span>{{node.label}}</span>
            </span>
          </avue-tree> -->
        </el-col>
        <el-col :xs="24" :sm="24" :md="19" class="user__main">
          <div style="margin: 0 0 10px 10px">
            <el-button
              type="primary"
              :disabled="checkRole.length == 0"
              @click="delIds"
              >批量删除</el-button
            >
            <el-button type="primary" @click="addRole">添加</el-button>
          </div>

          <div class="top" style="margin-left: 10px">
            <el-form
              :inline="true"
              :model="searchMsg"
              class="demo-form-inline"
              ref="searchForm"
            >
              <el-form-item label="角色名" prop="roleName">
                <el-input
                  v-model="searchMsg.roleName"
                  placeholder="请输入角色名"
                ></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="lockFlag">
                <el-select v-model="searchMsg.lockFlag" placeholder="请选择">
                  <el-option label="有效" :value="0"></el-option>
                  <el-option label="无效" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button
                  type="primary"
                  @click="$refs.searchForm.resetFields()"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>

          <el-table
            :data="list"
            border
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名字" width="200">
            </el-table-column>
            <el-table-column prop="lockFlag" label="状态" width="200">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.lockFlag === '0' ? 'success' : 'danger'"
                  disable-transitions
                  >{{ scope.row.lockFlag == 0 ? "启用" : "禁用" }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="roleDesc" label="角色描述" width="200">
            </el-table-column>
            <!-- <el-table-column
              prop="dsScope"
              label="数据权限"
              width="200">
            </el-table-column> -->
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  v-if="roleManager_btn_edit"
                  type="text"
                  size="small"
                  icon="el-icon-zoom-in"
                  @click="handleShow(scope.row, true)"
                  >查看
                </el-button>
                <el-button
                  v-if="roleManager_btn_edit"
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                  @click="handleShow(scope.row, false)"
                  >编辑
                </el-button>
                <el-button
                  v-if="roleManager_btn_del"
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  >删除
                </el-button>
                <el-button
                  v-if="roleManager_btn_perm"
                  type="text"
                  size="small"
                  icon="el-icon-plus"
                  @click="handlePermission(scope.row)"
                  >权限
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="text-align: center"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page.sync="page.pageNum"
            :page-size="page.pageSize"
            layout="total,prev, pager, next, jumper"
            :total="page.total"
          >
          </el-pagination>
          <!-- <avue-crud
        ref="crud"
        :option="tableOption"
        :data="list"
        :page.sync="page"
        v-model="form"
        :table-loading="listLoading"
        :before-open="handleOpenBefore"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="update"
        @row-save="create">

        <template slot="menuLeft">
          <el-button
            v-if="roleManager_btn_add"
            class="filter-item"
            type="primary"
            icon="el-icon-edit"
            @click="handleCreate">添加
          </el-button>
        </template>
        <template
              slot="deptIdForm"
              slot-scope="scope">
              <avue-input-tree
                v-model="form.deptId"
                :dic="treeDataList"
                :props="defaultProps1"
                placeholder="请选择所属部门"/>
        </template>
        <template slot="dsScopeForm" slot-scope="scope">
          <div v-if="form.dsType == 1">
            <el-tree
              ref="scopeTree"
              :data="dsScopeData"
              :check-strictly="true"
              :props="defaultProps"
              :default-checked-keys="checkedDsScope"
              class="filter-tree"
              node-key="id"
              highlight-current
              show-checkbox/>
          </div>
        </template> -->

          <!-- </avue-crud> -->
        </el-col>
      </el-row>
    </basic-container>

    <el-dialog
      :title="formTitle"
      :visible.sync="dialogFormVisible"
      @close="resetForm"
    >
      <el-form
        :model="form"
        label-width="120px"
        ref="form"
        :rules="rules"
        :disabled="editFlag"
      >
        <el-form-item label="状态:">
          <el-switch
            v-model="form.lockFlag"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </el-form-item>
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="数据权限:" prop="dsType">
          <!-- <el-input v-model="form.dsType" ></el-input> -->
          <el-select v-model="form.dsType" placeholder="请选择用户类型">
            <el-option label="全部" :value="0"></el-option>
            <el-option label="本人" :value="1"></el-option>
            <el-option label="本部" :value="2"></el-option>
            <el-option label="本公司" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述:" prop="roleDesc">
          <el-input v-model="form.roleDesc" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogPermissionVisible"
      :close-on-click-modal="false"
      title="分配权限"
    >
      <div class="dialog-main-tree">
        <el-tree
          ref="menuTree"
          :data="treeData"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
          :props="defaultProps"
          :filter-node-method="filterNode"
          class="filter-tree"
          node-key="id"
          highlight-current
          show-checkbox
          default-expand-all
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="updatePermession(roleId)"
          >更 新
        </el-button>
        <el-button type="default" size="small" @click="cancal()"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addObj,
  delObj,
  fetchList,
  fetchRoleTree,
  permissionUpd,
  putObj,
} from "@/api/admin/role";
import { tableOption } from "@/const/crud/admin/role";
import { fetchTree } from "@/api/admin/dept";
import { fetchMenuTree } from "@/api/admin/menu";
import { mapGetters } from "vuex";

export default {
  name: "TableRole",
  data() {
    return {
      searchForm: {},
      tabselect: "0",
      agentList: [], //代理商
      orgList: [],
      orgId: "",
      agentId: "",
      selectKeys: [],
      tableOption: tableOption,
      dsScopeData: [],
      treeData: [],
      checkRole: [],
      filterText: "",
      treeDataList: [],
      checkedKeys: [],
      checkedDsScope: [],
      searchMsg: {
        roleName: "",
        lockFlag: "",
      },
      defaultProps: {
        label: "name",
        value: "id",
      },
      formTitle: "新增",
      orgCode: "",
      defaultProps1: {
        label: "name",
        value: "id",
      },
      treeOption: {
        nodeKey: "aid",
        addBtn: false,
        defaultCheckedKeys: [1],
        menu: false,
        props: {
          label: "name",
          value: "aid",
        },
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      menuIds: "",
      list: [],
      listLoading: true,
      dialogFormVisible: false,
      form: {
        roleName: "", //角色名称
        dsType: "", //数据权限
        roleDesc: "", //描述
        orgCode: "", //公司
        lockFlag: "0", //状态
      },
      addFlag: true,
      rules: {
        roleName: [
          { required: true, message: "请填写角色名称", trigger: "blur" },
        ],
        dsType: [
          { required: true, message: "请选择数据权限", trigger: "blur" },
        ],
      },
      editFlag: false,
      roleId: undefined,
      roleCode: undefined,
      rolesOptions: undefined,
      dialogPermissionVisible: false,
      roleManager_btn_add: false,
      roleManager_btn_edit: false,
      roleManager_btn_del: false,
      roleManager_btn_perm: false,
    };
  },
  async created() {
    this.roleManager_btn_add = this.permissions["sys_role_add"];
    this.roleManager_btn_edit = this.permissions["sys_role_edit"];
    this.roleManager_btn_del = this.permissions["sys_role_del"];
    this.roleManager_btn_perm = this.permissions["sys_role_perm"];
    this.findMyOrg();
    // this.getTreeDataList()//获取部门树
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    ...mapGetters(["elements", "permissions"]),
  },
  methods: {
    // 单选框改变
    radioChange(e) {
      // console.log(e)
      if (e == 0 || e == 1) {
        this.findMyOrg();
      }
      if (e == 2) {
        this.findMyAgent();
        // this.getList();
      } else {
        this.treeDataList = [];
        this.getList();
      }
    },
    // 获取代理商
    findMyAgent() {
      this.$api.api
        .findMyAgent({
          orgType: localStorage.getItem("orgType"),
        })
        .then((res) => {
          // console.log(res)
          res.data.map((item) => {
            item.name = item.agentName;
          });
          this.treeDataList = res.data;
          this.orgCode = res.data[0].id;
          // console.log(this.orgCode);
          this.selectKeys = [res.data[0].id];
          this.$nextTick(() => {
            // this.selectKeys=[res.data[0].id]
            this.$refs.tree.setCurrentKey(res.data[0].id);
            this.getList();
          });
        });
    },
    // 获取公司
    findMyOrg() {
      this.$api.api
        .findMyOrg({
          orgType: localStorage.getItem("orgType"),
        })
        .then((res) => {
          // console.log(res)
          this.treeDataList = res.data;
          this.orgCode = res.data[0].orgCode;
          // console.log(this.orgCode);
          this.$nextTick(() => {
            // this.selectKeys=[res.data[0].id]
            this.$refs.tree.setCurrentKey(res.data[0].id);
          });
          this.getList();
        });
    },
    getList() {
      // fetchList(Object.assign({
      //   current: this.page.currentPage,
      //   size: this.page.pageSize,
      //   orgCode:this.orgCode
      // }, params, this.searchForm)).then(response => {
      //   this.list = response.data.records
      //   this.page.total = response.data.total
      // }).catch(() => {
      // })
      let obj = {
        current: this.page.currentPage,
        size: this.page.pageSize,
      };
      if (this.tabselect == 0 || this.tabselect == 1) {
        obj.orgCode = this.orgCode;
      }
      if (this.tabselect == 2) {
        obj.agentId = this.orgCode;
      }
      this.$api.api.rolePage(obj).then((res) => {
        this.list = res.data.records;
        this.page.total = res.data.total;
      });
    },
    getTreeDataList() {
      this.$api.api.userDeptTree().then((res) => {
        this.treeDataList = res.data;
        this.orgCode = res.data[0].orgCode;
        console.log(this.orgCode);
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(0);
        });
        this.getList();
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.getList();
    },
    // 批量删除
    delIds() {
      // console.log(1);
      console.log(this.checkRole);
      console.log(this.checkRole.join(","));
      // return
      this.$api.api
        .roleDelIds({ ids: this.checkRole.join(",") })
        .then((res) => {
          console.log(res);
          if (res.code == 0) {
            this.$message.success("批量删除成功");
            this.getList();
          }
        });
    },
    search() {
      console.log(this.searchMsg, "搜索内容");
      this.getList(this.searchMsg);
    },
    refreshChange() {
      this.getList();
    },
    addRole() {
      // console.log(1);
      this.dialogFormVisible = true;
      this.addFlag = true;
      this.editFlag = false;
      this.formTitle = "添加";
    },
    handleShow(row, flag) {
      // console.log(row);
      this.form = row;
      flag ? (this.formTitle = "查看") : (this.formTitle = "编辑");
      this.editFlag = flag;
      this.dialogFormVisible = true;
      this.addFlag = false;
    },
    add() {
      // this.dialogFormVisible = false
      if (this.editFlag) {
        this.dialogFormVisible = false;
        return;
      }
      this.form.orgCode = this.orgCode;
      console.log(this.form);
      // return
      if (this.addFlag) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            addObj(this.form).then((res) => {
              this.dialogFormVisible = false;
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            putObj(this.form).then((res) => {
              this.dialogFormVisible = false;
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
    filterNode(value, data) {
      // console.log(value,data);
      // return
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(form);
      done();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
    currentChange(current) {
      this.page.currentPage = current;
      this.getList();
    },
    handleCreate() {
      // this.$refs.crud.rowAdd()
    },
    handleOpenBefore(show) {
      fetchTree().then((response) => {
        this.dsScopeData = response.data;
        if (this.form.dsScope) {
          this.checkedDsScope = this.form.dsScope.split(",");
        } else {
          this.checkedDsScope = [];
        }
      });
      show();
    },
    handleUpdate(row, index) {
      // this.$refs.crud.rowEdit(row, index)
      this.update(row, index);
    },
    cancal() {
      this.dialogPermissionVisible = false;
    },
    handlePermission(row) {
      fetchRoleTree(row.roleId)
        .then((response) => {
          this.checkedKeys = response.data;
          return fetchMenuTree();
        })
        .then((response) => {
          this.treeData = response.data;
          // 解析出所有的太监节点
          this.checkedKeys = this.resolveAllEunuchNodeId(
            this.treeData,
            this.checkedKeys,
            []
          );
          this.dialogPermissionVisible = true;
          this.roleId = row.roleId;
          this.roleCode = row.roleCode;
        });
    },
    /**
     * 解析出所有的太监节点id
     * @param json 待解析的json串
     * @param idArr 原始节点数组
     * @param temp 临时存放节点id的数组
     * @return 太监节点id数组
     */
    resolveAllEunuchNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i];
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          this.resolveAllEunuchNodeId(item.children, idArr, temp);
        } else {
          temp.push(idArr.filter((id) => id === item.id));
        }
      }
      return temp;
    },
    // filterNode(value, data) {
    //   if (!value) return true
    //   return data.label.indexOf(value) !== -1
    // },
    getNodeData(data, done) {
      done();
    },
    handleDelete(row, index) {
      this.$confirm(
        '是否确认删除名称为"' + row.roleName + '"' + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delObj(row.roleId);
        })
        .then(() => {
          this.getList();
          this.$notify.success("删除成功");
        });
    },
    create(row, done, loading) {
      if (this.form.dsType === 1) {
        this.form.dsScope = this.$refs.scopeTree.getCheckedKeys().join(",");
      }
      addObj(...this.form, ...{ orgCode: this.orgCode })
        .then(() => {
          this.getList();
          done();
          this.$notify.success("创建成功");
        })
        .catch(() => {
          loading();
        });
    },
    handleSelectionChange(e) {
      this.checkRole = [];
      console.log(e);
      e.map((item) => {
        this.checkRole.push(item.roleId);
      });
    },
    update(row, index, done, loading) {
      if (this.form.dsType === 1) {
        this.form.dsScope = this.$refs.scopeTree.getCheckedKeys().join(",");
      }
      putObj(this.form)
        .then(() => {
          this.getList();
          done();
          this.$notify.success("修改成功");
        })
        .catch(() => {
          // loading()
        });
    },
    nodeClick(data) {
      console.log(data);
      this.page.page = 1;
      if (this.tabselect == 0 || this.tabselect == 1) {
        this.orgCode = data.orgCode;
      }
      if (this.tabselect == 2) {
        this.orgCode = data.id;
      }
      // this.orgCode=data.id
      this.getList(this.page, { orgCode: data.orgCode });
    },
    updatePermession(roleId) {
      this.menuIds = "";
      this.menuIds = this.$refs.menuTree
        .getCheckedKeys()
        .join(",")
        .concat(",")
        .concat(this.$refs.menuTree.getHalfCheckedKeys().join(","));
      permissionUpd(roleId, this.menuIds).then(() => {
        this.dialogPermissionVisible = false;
        this.$notify.success("修改成功");
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  .el-dialog {
    width: 61% !important;
    .dialog-main-tree {
      max-height: 400px;
      overflow-y: auto;
    }
  }
  .el-form-item__label {
    width: 20% !important;
    padding-right: 20px;
  }
  .el-form-item__content {
    margin-left: 20% !important;
  }
}
