<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-row>
      <el-form
        v-show="showSearch"
        ref="queryParams"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item
          label="角色名称"
          prop="name"
          @keyup.enter.native="searchClick"
        >
          <el-input
            v-model.trim="queryParams.name"
            placeholder="请输入名称"
            clearable
            size="small"
          />
        </el-form-item>
        <!-- <el-form-item label="创建人" prop="createName">
          <el-input
            v-model.trim="queryParams.createName"
            placeholder="请输入创建人"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select
            v-model.trim="queryParams.state"
            clearable
            size="small"
            placeholder="请选择状态"
          >
            <el-option value="" label="全部" />
            <el-option
              v-for="item in stateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            @click="searchClick"
          >查询</el-button>
          <el-button
            :loading="loading"
            @click="resetClick('queryParams')"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 新增按钮 -->
    <el-row class="mb-20">
      <span class="list-title">角色列表</span>
      <el-button type="primary" v-if="filterButton('role_add')" @click="addRoles">新增</el-button>
      <!-- <el-button @click="skipTo">跳转到客户端loading页面</el-button> -->
    </el-row>
    <!-- 内容展示区 -->
    <elm-table row-key="id" :table-data="list" :colum-obj="columObj" :loading="loading" @rowOperation="rowOperation" />
    <!-- 分页器 -->
    <el-row v-if="total > 0" class="text-center">
      <el-pagination
        background
        :current-page="queryParams.current"
        :page-sizes="[10, 20, 50, 100, 200]"
        :page-size="queryParams.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      class="role_dialog"
      :class="{ role_editDialog: role_editStyle }"
      :title="dialogType == 'add' ? '新增角色' : '编辑角色'"
      width="540px"
      :visible="dialogShow"
      :close-on-click-modal="false"
      @close="formClose"
    >
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <div>
          <el-form-item key="roleAdd" label="角色名称：" prop="name">
            <el-input :disabled="event=='detail'" v-model.trim="form.name" placeholder="请输入角色名称" />
          </el-form-item>
        </div>
        <!-- <div v-if="dialogType == 'edit'">
          <el-form-item
            key="roleEdit"
            label="角色名称："
            class="form-item-text"
          >
            <span>{{ form.name }}</span>
          </el-form-item>
        </div> -->
        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model.trim="form.remark"
            :disabled="event=='detail'"
            :rows="5"
            resize="none"
            show-word-limit
            maxlength="100"
            type="textarea"
            clearable=""
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="角色授权：" prop="menuIdList">
          <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText">
        </el-input>
          <el-tree
          default-expand-all
          ref="tree"
          node-key="id"
          show-checkbox
           :filter-node-method="filterNode"
          :data="tree"
          :default-expanded-keys="['0']"
          :props="{ label: 'name', children: 'children',disabled:()=>{return event=='detail'?true:false} }"
          @check="getCheckedNodes"
        />

      </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formClose">取消</el-button>
        <el-button
          v-if="event!='detail'"
          :loading="loading"
          type="primary"
          @click="formSave"
        >确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import prompt from '@/utils/prompt'
import lodash from 'lodash'
// import {

//   getRolegroupList,
//   addOneRolegroup,
//   updateOneRolegroup,
//   getPrivilegeListByRoleId,
//   updateMenuListByRoleId,
//   delOneRolegroup,
//   updateUserListByRoleId,
//   disableTrolegroup
// } from '@/api/rolegroup'
import {
  menuTree,
  roleList,
  add,
  edit,
  detail,
  del
} from '@/apiV2/rolemanage'
import {menuChildList} from '@/apiV2/menuManage'
// import { getUserList } from '@/api/user_role_priviege'
// import { getInfo } from '@/api/user'
import ElmTable from '@/components/ElmTable/index.vue'
const defaultForm = {
  name: '',
  remark: '',
  menuIdList:[]
}
export default {
  name: '角色管理',
  components: { ElmTable },
  mixins: [prompt],
  inject: ['reload'],
  data() {
    return {
      // 显示搜索条件
      dialogType: 'add',
      showSearch: true,
      list: [],
      userList: [],
      // 已勾选角色
      userIdsList: [],
      total: 1,
      loading: false,
      title: '新增角色',
      stateText: '启用',
      disabledDialog: false,
      // 新增表单
      dialogShow: false,
      /* 里面的分页功能开始*/
      currentPage2: 1,
      total2: 0, // 数据总条数
      /* 分页功能end*/
      form: lodash.cloneDeep(defaultForm),
      allocatePersonnel: {
        current: 1,
        size: 10,
        nickname: '',
        name: '',
        mobile: '',
        state: ''
      },
      staffAllocation: [],
      // hasRole: [],
      activeUserId: '',
      allocatePersonnelOpen: false,
      // 是否拥有超级管理员角色
      isAdmin: false,
      // 是否在控制超级管理员
      isSuperAdmin: false,
      // 新增、编辑表单验证
      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            pattern: /^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9]){2,50}$/,
            message: '请输入2-50位，支持汉字、数字、字母',
            trigger: 'change'
          }
        ],
        menuIdList:[
          //只是想生成一个*，后面的calidator提供校验
          { required: true,  message:' ', trigger: 'blur'},
          { validator: this.validateArrayNotEmpty, trigger: 'change' }

        ]
      },
      // 搜索表单
      queryParams: {
        name: '',
        // createName: '',
        // state: ''
      },
      // 启用禁用
      status: '0',
      // 分配权限对话框
      setRole: false,
      tree: [],
      rolePrivilege: {
        roleId: '',
        menuIds: []
      },
      multipleSelection: [],
      userIds: [],
      rowId: '',
      // 菜单状态List
      stateList: [
        {
          id: '0',
          name: '禁用'
        },
        {
          id: '1',
          name: '启用'
        }
      ],
      columObj: {
        lazy: 'true',
        hasIndex:true,
        columnData: [
          { text: true, prop: 'name', label: '角色名称', minwidth: '120' },
          // { ownDefined: true, prop: 'userName', label: '已分配人员', minwidth: '120', ownDefinedReturn: row => row.userName.toString() || '--' },
          { ownDefined: true, prop: 'createName', label: '角色类型', minwidth: '140', ownDefinedReturn: row => row.isDefault==0?'自定义':'内置角色'},
        { ownDefined: true, prop: 'createName', label: '创建人', minwidth: '140', ownDefinedReturn: row =>  row.createName || '--'},
          { ownDefined: true, prop: 'createTime', label: '创建时间', minwidth: '140', sortable: true, sortType: 'date', ownDefinedReturn: row => row.createTime || '--' },
         { ownDefined: true, prop: 'remark', label: '备注', minwidth: '180', ownDefinedReturn: row => row.remark || '--' },

          // { ownDefined: true, prop: 'stateBool', label: '状态', minwidth: '60', ownClassName: row => row.state == true ? 'abled' : 'disabled', ownDefinedReturn: row => row.state === true ? '启用' : row.state === false ? '禁用' : '--' },


          {
            isOperation: true, prop: 'operation', label: '操作', minwidth: '160', fixed: 'right', tooltip: false,
            operation: [
              { operation: 'detail', type: 'text', label: '查看',
                isShow:(row) =>this.filterButton('role_detail') },
              { operation: 'edit', type: 'text', label: '编辑',
                isShow:(row) =>this.filterButton('role_edit') },
              // { operation: 'permission', type: 'text', label: '授权', disabled: row => row.state == 0,
              //   isShow: (row) => ((this.filterButton('roleManage_permission') && row.createBy == this.activeUserId) || this.isAdmin) && row.groupid != '0' },
              // { operation: 'distribution', type: 'text', label: '分配人员',
              //   disabled: row => row.state == 0, isShow: (row) => (this.filterButton('roleManage_distribution') && row.createBy == this.activeUserId) || this.isAdmin },
              // { operation: 'disable', type: 'text', label: '启用', labelRow: row => row.state == 1 ? '禁用' : '启用',
              //   isShow: (row) => ((this.filterButton('roleManage_disable') && row.createBy == this.activeUserId) || this.isAdmin) && row.groupid != '0' },
              { operation: 'delete', type: 'text', label: '删除',
                isShow:(row) =>row.isDefault==0&&this.filterButton('role_del') }
            ]
          }
        ]
      },
      filterText:"",
      event:""

    }
  },
  watch:{
    filterText(val) {
        this.$refs.tree.filter(val);
      }

  },
  created() {
    // 获取列表数据及分配人员列表
    this.getList()
    // this.getList2(this.allocatePersonnel)
    // 获取树形数据 - 授权
    menuTree({
      platform:1,
      effect: 1,
      status: 1

    }).then(res => {
      this.tree = [{
        id:0,
        name:"全部",
        children:res.data
      }]
    })
    // 获取当前登录用户的信息
    // getInfo().then(res => {
    //   if (res.success) {
    //     this.activeUserId = res.data.id
    //     this.isAdmin = res.data.isAdmin
    //   }
    // })
  },
  methods: {
    validateArrayNotEmpty(rule, value, callback) {
       console.log("value",this.form.menuIdList)
      setTimeout(()=>{
        value=this.form.menuIdList
        if (value === null || value === undefined || value.length === 0) {
          callback(new Error('请选择'));
        } else {
          callback();
        }
      },500)
        
      },
     filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
    // 时间戳转日期时间
    goTime(val) {
      if (val) {
        var timestamp4 = new Date(val)
        return (
          timestamp4.toLocaleDateString().replace(/\//g, '-') +
          ' ' +
          timestamp4.toTimeString().substr(0, 8)
        )
      } else {
        return
      }
    },
    // 获取页面信息
    getList() {
      this.loading = true
      roleList({...this.queryParams,platform:1})
        .then(res => {
          if (res.success) {
            this.total = res.data.total
            this.list = lodash.cloneDeep(res.data.records)
            this.loading = false
          } else {
            this.loading = false
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取分配人员列表
    // getList2(query) {
    //   this.loading = true
    //   getUserList(query)
    //     .then(res => {
    //       if (res.success) {
    //         this.total2 = res.data.total
    //         this.userList = lodash.cloneDeep(res.data.records)
    //         this.$nextTick(() => {
    //           this.$refs.multipleTable &&
    //             this.$refs.multipleTable.clearSelection()
    //           this.userList.forEach(element => {
    //             if (this.userIdsList.includes(element.id)) {
    //               this.$refs.multipleTable.toggleRowSelection(element, true)
    //             }
    //           })
    //           if (this.allocatePersonnelOpen) {
    //             this.userList.forEach(element => {
    //               if (this.staffAllocation.includes(element.id)) {
    //                 this.$refs.multipleTable.toggleRowSelection(element, true)
    //               } else {
    //                 this.$refs.multipleTable.toggleRowSelection(element, false)
    //               }
    //             })
    //           }
    //         })
    //         this.loading = false
    //       } else {
    //         this.loading = false
    //       }
    //     })
    //     .catch(() => {
    //       this.loading = false
    //     })
    // },
    // 新增/编辑确认
    formSave() {
      if (this.dialogType === 'add') {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            // const arr1 = this.$refs.tree.getCheckedNodes(false, true)
            // const arr2 = []
            // arr1.forEach(ele => {
            //   if (ele.id != 0) {
            //     arr2.push(ele.id)
            //   }
            // })
            add({
              platform:1,
              name:this.form.name,
              remark:this.form.remark,
              menuIdList:this.form.menuIdList,
              companyId:0,
              orgId:0
            })
              .then(res => {
                if (res.success) {
                  this.formClose()
                  this.queryParams.current = 1
                  this.getList()
                } else {
                  this.loading = false
                }
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else if (this.dialogType === 'edit') {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            // const arr1 = this.$refs.tree.getCheckedNodes(false, true)
            // const arr2 = []
            // arr1.forEach(ele => {
            //   if (ele.id != 0) {
            //     arr2.push(ele.id)
            //   }
            // })
            edit({
              ...this.form
            })
              .then(res => {
                if (res.success) {
                  this.formClose()
                  this.getList()
                } else {
                  this.loading = false
                }
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    // 新增按钮
    addRoles() {
      this.dialogType = 'add'
      this.form = lodash.cloneDeep(defaultForm)
      this.$forceUpdate()
      this.dialogShow = true
      this.role_editStyle = false
      this.$nextTick(()=>{
        this.$refs.tree.setCheckedKeys([])

      })

    },
    // 关闭新增编辑对话框
    formClose() {
      this.dialogShow = false
      this.form = lodash.cloneDeep(defaultForm)
      this.loading = false
      this.$refs['form'].resetFields()
    },
    // 编辑
    edit(row) {
      this.dialogType = 'edit'
      //后端需要存储的是带半选节点（父节点的）完整数据
      // 比如，首页下面有查看编辑，后端需要存储的是首页查看编辑这三个id形成的数组
      //前端传的时候也是传的三个
      // 但是前端组件渲染时候要用到是只有查看编辑2个id的数组
      //所以这个接口就是将处理成前端能直接使用的数组
      //获取授权子节点
      menuChildList(row.id).then(res=>{
        this.form = lodash.cloneDeep(row)
        // this.form = {
        //   ...lodash.cloneDeep(row),
        //   menuIdList:res.data.map(item=>item.id)
        // }
         this.dialogShow = true
        this.role_editStyle = true
        this.$nextTick(()=>{
          this.$refs.tree.setCheckedKeys(res.data.map(item=>item.id))

        })
        
       
      }) 
    },
    // 递归
    // setPrivilegeRecursion(obj) {
    //   if (obj) {
    //     obj.forEach(item => {
    //       this.rolePrivilege.menuIds.push(item.id)
    //       if (item.children == null) {
    //         return
    //       } else {
    //         return this.setPrivilegeRecursion(item.children)
    //       }
    //     })
    //   }
    // },
    // 授权
    // setPrivilege(row) {
    //   // 先渲染 dialog
    //   this.setRole = true
    //   this.$nextTick(async() => {
    //     this.rolePrivilege.roleId = row.id
    //     const res1 = await getPrivilegeListByRoleId(row.id)
    //     this.setPrivilegeRecursion(res1.data)
    //     this.$refs.tree.setCheckedKeys(this.rolePrivilege.menuIds)
    //   })
    // },
    // 关闭授权对话框
    closeEvent() {
      this.setRole = false
      this.rolePrivilege.menuIds = []
      this.$refs.tree.setCheckedKeys([])
      this.loading = false
    },
    // 授权提交
    // submitRolePrivilege() {
    //   this.loading = true
    //   const arr1 = this.$refs.tree.getCheckedNodes(false, true)
    //   const arr2 = []
    //   arr1.forEach(ele => {
    //     if (ele.id != 0) {
    //       arr2.push(ele.id)
    //     }
    //   })
    //   this.rolePrivilege.menuIds = lodash.cloneDeep(arr2)
    //   updateMenuListByRoleId(this.rolePrivilege).then(res => {
    //     this.closeEvent()
    //     console.log('updateMenuListByRoleId', res)
    //   })
    // },
    // 点击删除按钮
    handleDelete(row) {
      // if (row.userIds.length === 0) {
        var txt = `<p class="text-center">您确定要删除角色【${
          row.name
        }】吗？</p>`
        this.$confirm(txt, '温馨提示', {
          dangerouslyUseHTMLString: true,
          type: 'none'
        })
          .then(() => {
            del(row.id).then(res => {
              if (res.success) {
                this.loading = false
                this.getList()
                this.form = lodash.cloneDeep(defaultForm)
              } else {
                this.loading = false
              }
            })
          })
          .catch(() => {
            this.form = lodash.cloneDeep(defaultForm)
          })
      // } else {
      //   this.$message({
      //     message: '此角色已关联用户，请先取消关联再进行删除',
      //     offset: 60,
      //     type: 'warning'
      //   })
      // }
    },
    // 禁用按钮
    // stateManage(row) {
    //   if (row.userIds.length > 0) {
    //     this.disabledDialog = false
    //     this.$message({
    //       message: '此角色已关联用户，请先取消关联再进行禁用',
    //       offset: 60,
    //       type: 'warning'
    //     })
    //   } else {
    //     this.form = lodash.cloneDeep(row)
    //     if (row.state) {
    //       this.stateText = '禁用'
    //     } else {
    //       this.stateText = '启用'
    //     }
    //     var txt = `<p class="text-center">您确定要${this.stateText}角色【${
    //       row.name
    //     }】吗？</p>`
    //     this.$confirm(txt, '温馨提示', {
    //       dangerouslyUseHTMLString: true,
    //       type: 'none'
    //     })
    //       .then(() => {
    //         if (row.state) {
    //           this.form.state = '0'
    //         } else {
    //           this.form.state = '1'
    //         }
    //         const params = {
    //           id: this.form.id,
    //           state: this.form.state
    //         }
    //         disableTrolegroup(params).then(res => {
    //           if (res.success) {
    //             this.disabledDialog = false
    //             this.loading = false
    //             this.getList()
    //             this.form = lodash.cloneDeep(defaultForm)
    //           } else {
    //             this.loading = false
    //           }
    //         })
    //       })
    //       .catch(() => {
    //         this.form = lodash.cloneDeep(defaultForm)
    //       })
    //   }
    // },
    // 已禁用用户无法授权
    // disableTree(row) {
    //   if (this.isSuperAdmin) {
    //     if (row.state === '0' || row.id === '1') {
    //       return false
    //     } else {
    //       return true
    //     }
    //   } else {
    //     if (row.state === '0') {
    //       return false
    //     } else {
    //       return true
    //     }
    //   }
    // },
    // 分配人员
    // handleAllocatePersonnel(row) {
    //   if (row.id === '1') {
    //     this.isSuperAdmin = true
    //   } else {
    //     this.isSuperAdmin = false
    //   }
    //   this.staffAllocation = lodash.cloneDeep(row.userIds)
    //   this.userIdsList = lodash.cloneDeep(row.userIds)
    //   this.rowId = row.id
    //   this.getList2()
    //   this.allocatePersonnelOpen = true
    //   this.$nextTick(() => {
    //     this.$refs.multipleTable.clearSelection()
    //     this.userList.forEach(element => {
    //       if (row.userIds.includes(element.id)) {
    //         this.$refs.multipleTable.toggleRowSelection(element, true)
    //       }
    //     })
    //   })
    // },
    // 分配人员关闭事件
    // allocatePersonnelClose() {
    //   this.allocatePersonnelOpen = false
    //   this.userIds = []
    //   this.allocatePersonnel = {
    //     current: 1,
    //     size: 10,
    //     nickname: '',
    //     name: '',
    //     mobile: '',
    //     state: ''
    //   }
    //   this.$refs.multipleTable.clearSelection()
    // },
    // // 分配人员提交按钮
    // allocatePersonnelSubmit() {
    //   this.getList2({
    //     current: 1,
    //     size: 10,
    //     nickname: '',
    //     name: '',
    //     mobile: '',
    //     state: ''
    //   })
    //   updateUserListByRoleId(this.staffAllocation, this.rowId).then(res => {
    //     if (res.success) {
    //       this.allocatePersonnelClose()
    //       this.getList()
    //     } else {
    //       this.loading = false
    //     }
    //   })
    // },
    // 分配人员搜索
    // personSearch() {
    //   this.allocatePersonnel.current = 1
    //   this.getList2(this.allocatePersonnel)
    //   this.loading = true
    // },
    /* 分页功能开始*/
    handleSizeChange2(val) {
      this.allocatePersonnel.size = val
      this.getList2(this.allocatePersonnel)
    },
    handleCurrentChange2(val, row) {
      this.allocatePersonnel.current = val
      this.getList2(this.allocatePersonnel)
    },
    /* 分页功能end*/
    // 点击分配人员多选框的触发事件
    handleSelectionChange(selection, row) {
      // selection - 当前页选中的
      if (this.staffAllocation.includes(row.id)) {
        this.staffAllocation = this.staffAllocation.filter(
          item => item != row.id
        )
      } else {
        this.staffAllocation.push(row.id)
      }
      console.log(this.staffAllocation)
    },
    // 点击分配人员全选的复选框触发的事件
    selectAll(val) {
      if (!val.length) {
        const arr = this.userList.map(item => {
          return item.id
        })
        this.staffAllocation = this.staffAllocation.filter(item => {
          return !arr.includes(item)
        })
      }
      val.forEach(item => {
        if (!this.staffAllocation.includes(item.id)) {
          this.staffAllocation.push(item.id)
        }
      })
    },
    getCheckedNodes() {
      const arr1 = this.$refs.tree.getCheckedNodes(false, true)
      const arr2 = []
      arr1.forEach(ele => {
        if (ele.id != 0) {
          arr2.push(ele.id)
        }
      })
      this.form.menuIdList=arr2
    },
    getRowKey(row) {
      return row.id
    },
    skipTo() {
      const str = 'http://192.168.12.28:9528/#/loadingPage?qiandingtoken=&menuCode='
      window.location.href = str
    },
    rowOperation(row, $index, event) {
      this.event = event
      switch (event) {
        case 'detail':
          //和edit执行一样的操作,只是把框都禁掉
          this.edit(row);
          break;
        case 'edit' :
          this.edit(row)
          break
        // case 'permission' :
        //   this.setPrivilege(row)
        //   break
        // case 'distribution' :
        //   this.handleAllocatePersonnel(row)
        //   break
        // case 'disable' :
        //   this.stateManage(row)
        //   break
        case 'delete' :
          this.handleDelete(row)
          break
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.disabled {
  color: #b9b8b8;
}
.searchItem {
  position: relative;
  .searchBtn {
    position: absolute;
    right: 0;
    bottom: 22.5px;
  }
  /deep/.el-form-item__label {
    padding-right: 12px !important;
  }
}
.disabledNote {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 140px;
}
.role_dialog {
  /deep/.el-dialog__body {
    padding: 22px 20px 0;
  }
}
.role_editDialog {
  /deep/.form-item-text.el-form-item--medium .el-form-item__label,
  /deep/.form-item-text.el-form-item--medium .el-form-item__content {
    line-height: 20px;
  }
  /deep/.el-dialog__body {
    padding: 22px 22px 0;
  }
}
.h290 {
  /deep/.el-dialog__body {
    height: 290px;
  }
}
.allocatePersonnel {
  >>> .el-dialog__body {
    height: 500px;
  }
  /deep/.el-table-column--selection .cell {
    padding-right: 10px;
  }
  /deep/.el-dialog .el-dialog__footer button {
    width: auto;
  }
}
.remark {
  margin-top: 8px;
}
.gray {
  color: #b9b8b8 !important;
}
</style>
