<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams1" ref="queryForm" size="small" :inline="true" label-width="100px">
        <el-form-item label="角色名称" prop="dutyName">
          <el-input
            v-model="queryParams1.dutyName"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter.native="handleQuery1"
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-select
            v-model="queryParams1.status"
            placeholder="全部"
            clearable
          >
            <el-option label="启用" value="A"></el-option>
            <el-option label="禁用" value="D"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery1">查询</el-button>
        </el-form-item>
      </el-form>

    </el-card>

    <el-card style="margin-top: 20px">

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd1"

          >新增
          </el-button>
        </el-col>
      </el-row>
      <el-table ref="tables"
                v-loading="loading"
                :data="dutyList">
        <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
        <el-table-column label="角色名称" align="center" prop="dutyName" />
<!--        <el-table-column label="角色类型" align="center" prop="dutyType" >-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="scope.row.dutyType=='1'">超级管理员</span>-->
<!--            <span v-if="scope.row.dutyType=='2'">普通管理员</span>-->
<!--            <span v-if="scope.row.dutyType=='3'">用户角色</span>-->
<!--            <span v-if="scope.row.dutyType=='3'">员工角色</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="所属机构" align="center" prop="deptName" />
        <el-table-column label="角色状态" align="center" prop="status" >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="A"
              inactive-value="N"
              @change="handleStatusChangeDuty(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="角色描述" align="center" prop="description" >
          <template slot-scope="scope">
            {{scope.row.description || "--"}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate1(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete1(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <pagination
        v-show="total1>0"
        :total="total1"
        :page.sync="queryParams1.page"
        :limit.sync="queryParams1.pageSize"
        @pagination="getDutyList"
      />
    </el-card>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="openDuty" width="700px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form1.roleName" @input="$forceUpdate()" style="width: 300px" placeholder="请输入角色名称" />
        </el-form-item>
<!--        <el-form-item label="角色类型" prop="roleType">-->
<!--          <el-select-->
<!--            v-model="form1.roleType"-->
<!--            placeholder="角色类型"-->
<!--            @change="changeMenu"-->
<!--            style="width: 300px"-->
<!--          >-->
            <!--            <el-option key="1" label="超级管理员" value="1"/>-->
            <!--            <el-option key="2" label="普通管理员" value="2"/>-->
<!--            <el-option key="3" label="用户角色" value="3"/>-->
<!--            <el-option key="3" label="员工角色" value="3"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="状态">
          <el-radio-group v-model="form1.status">
            <el-radio key="A" label="A" value="A">启用</el-radio>
            <el-radio key="N" label="N" value="N">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form1.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form1.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps1"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form1.description" type="textarea" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {dutyDelete, dutyEdit, dutyList} from "@/api/duty/duty";
import {addRole, getRole, updateRole} from "@/api/system/role";
import {treeselects} from "@/api/system/menu";

export default {
  data(){
    return {
      queryParams1:{
        page:1,
        pageSize:10,
        // 当做机构id使用
        storeId:"",
      },
      title:"",
      total1:0,
      dutyList:[],
      // 遮罩层
      loading: true,
      openDuty:false,
      menuExpand: false,
      menuNodeAll: false,
      // 菜单列表
      menuOptions: [],
      defaultProps1: {
        children: "childrens",
        label: "label"
      },
      form1: { id: '', status: 'A', roleType: '4', description: '' },
      rules1: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        // roleType: [
        //   { required: true, message: "角色类型不能为空", trigger: "blur" }
        // ]
      },
    }
  },
  created() {
    this.getDutyList()
  },
  methods:{

    // 修改角色类型
    changeMenu(){
      console.log(this.form1.roleType)
      if (this.form1.roleType == '4'){
        this.getMenuTreeselect();
      }
      if (this.form1.roleType == '3'){
        this.getMenuTreeselect();
      }
    },
    // 表单重置
    reset1() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.form1 = {
          id: undefined,
          roleName: '',
          roleType: '3',
          status: "A",
          menuIds: [],
          menuCheckStrictly: true,
          description: ''
        };
      this.resetForm("form1");
    },
    // 取消按钮
    cancel1() {
      this.openDuty = false;
      this.reset1();
    },
    submitForm1: function() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if (this.form1.dutyId) {
            this.form1.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form1).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openDuty = false;
              this.getDutyList();
            });
          } else {
            this.form1.storeId = '-1';
            this.form1.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form1).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openDuty = false;
              this.getDutyList();
            });
          }
        }
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form1.menuCheckStrictly = value ? true: false;
      }
    },
    handleAdd1(){
      this.reset1();
      this.getMenuTreeselect();
      this.openDuty = true;
      this.title = "添加角色";
    },
    // 查询菜单树结构
    getMenuTreeselect() {
      return treeselects().then(response => {
        this.menuOptions = response.data;
        return response
      });
    },
    handleDelete1(row){
      const roleIds = row.dutyName;
      this.$modal.confirm('是否确认删除角色名为"' + roleIds + '"的信息？').then(function() {
        return dutyDelete(row.dutyId);
      }).then(() => {
        this.getDutyList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleUpdate1(data){
      this.reset1();
      let val = null;
      if (data.dutyType == '3') val = 1;
      if (data.dutyType == '4') val = 2;
      const roleMenu = this.getMenuTreeselect();
      const roleId = data.dutyId
      getRole(roleId).then(response => {
        this.form1.roleName = response.data.roleInfo.name;
        this.form1.roleType = response.data.roleInfo.type;
        this.form1.status = response.data.roleInfo.status;
        this.form1.dutyId = response.data.roleInfo.id;
        this.form1.description = response.data.roleInfo.description;
        this.openDuty = true;
        this.title = "修改角色";
        let checkedKeys = response.data.checkedKeys

        this.$nextTick(() => {
          roleMenu.then(res => {
            checkedKeys.forEach((v) => {
              this.$nextTick(()=>{
                this.$refs.menu.setChecked(v, true ,false);
              })
            })
          });
        });
      });
    },
    handleStatusChangeDuty(data){
      console.log(data)
      dutyEdit(data).then(res => {
        this.$message.success("修改成功")
        this.getDutyList();
      })
    },
    // 搜索角色信息
    handleQuery1(){
      this.queryParams1.page = 1;
      this.getDutyList();
    },
    getDutyList(){
      this.loading = true;
      dutyList(this.queryParams1).then(res => {
        this.dutyList = res.data.records;
        this.total1 = res.data.total;
        this.loading = false;
      })
    },
  }
}
</script>

<style lang="scss" scoped>
  .app-container{
    width: 100%;
    height: 100%;
    background: #f6f8f9;
  }
</style>
