<template>
    <d2-container>
        <div v-if="isExpend" class="d2-fl d2-tree-view">
            <el-tree
                    ref="tree"
                    highlight-current
                    :data="treeData"
                    default-expand-all
                    :props="defaultProps"
                    @node-click="handleNodeClick"
            >
        <span class="icon-tree" slot-scope="{ node, data }">
          <div v-if="data.alias == 'top'">
          	<i class="fa fa-university"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
          <div v-if="data.alias == 'JG001'">
          	<i class="fa fa-building"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
             <div v-if="data.alias == 'JG002'">
          	<i class="fa fa-building"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
            	<div v-if="data.alias == 'JG003'">
				 		 				<i class="fa fa-users"></i>
				 		 				<span>&nbsp;{{node.label}}</span>
				 		 			</div>
          	<!--<div v-if="data.alias == 'user'">-->
          	<!--<i class="fa fa-users"></i>-->
          	<!--<span>&nbsp;{{node.label}}</span>-->
          <!--</div>-->
        </span>
            </el-tree>
        </div>
        <div
                @click="isExpend = !isExpend"
                :class="[{'angle-view':isExpend},{'angle-view-none':!isExpend}]"
        >
            <i :class="['fa', {'fa-angle-left':isExpend},{'fa-angle-right':!isExpend}]"></i>
        </div>
        <div @click="isExpend = !isExpend" :class="[{'angle-view':isExpend},{'angle-view-none':!isExpend}]">
            <i :class="['fa', {'fa-angle-left':isExpend},{'fa-angle-right':!isExpend}]"></i>
        </div>
        <div :class="[{'d2-fl':isExpend},{'d2-table-view':isExpend},{'d2-table-view-full':!isExpend}]" style="overflow: hidden">
            <div class="d2-table-view-header">
                <el-form size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline" labelPosition="right">
                    <!--<el-form-item label="部门">-->
                        <!--<el-input v-model.trim="filter.userNo" placeholder="部门" clearable/>-->
                    <!--</el-form-item>-->
                    <!--<el-form-item label="设备编号">-->
                        <!--<el-input v-model.trim="filter.readerCode" placeholder="设备编号" clearable/>-->
                    <!--</el-form-item>-->
                    <el-form-item label="人员编号">
                        <el-input v-model.trim="filter.userNo" placeholder="人员编号" clearable/>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <el-input v-model.trim="filter.userNm" placeholder="姓名" clearable/>
                    </el-form-item>
                    <!--<el-form-item label="是否授权">-->
                        <!--<el-select v-model="filter.status" style="width: 100%" clearable>-->
                            <!--<el-option label="已授权" value=1></el-option>-->
                            <!--<el-option label="已撤销" value=2></el-option>-->
                        <!--</el-select>-->
                    <!--</el-form-item>-->
                    <el-form-item>
                        <el-button type="primary" @click="handleList('1')">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="d2-table-view-content">
                <div class="d2-table-view-handle">
                    <!--<el-button  size="small" type="success">导出</el-button>-->
                    <el-button  size="small" type="success" @click="operVisible1=!operVisible1">批量授权</el-button>
                    <el-button  size="small" type="success" @click="onMutilDelClick">批量撤销权限</el-button>
                </div>
                <d2-crud
                        title="人员授权列表"
                        ref="d2Crud"
                        :options="tableOptions"
                        :loading="loading"
                        :columns="columns"
                        :data="data"
                        :rowHandle="rowHandle"
                        @edit="handleRowEdit"
                        @delete="handleRowRemove"
                        selection-row
                        @selection-change="handleSelectionChange"
                >
                </d2-crud>
            </div>
            <div class="d2-table-view-footer">
                <el-pagination
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                        :current-page.sync="currentPage"
                        :page-size="tableOptions.pageList[0]"
                        :page-sizes="tableOptions.pageList"
                        layout="total,sizes, prev, pager, next,jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
        </div>
        <el-dialog
                :title="diaLogName"
                :visible.sync="operVisible"
                @close="clearForm"
                width="40%"
                :close-on-click-modal="false"
        >
            <el-form ref="form" :model="form" label-width="80px" labelPosition="right">
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="人员编号" prop="userNo">
                            <el-input v-model.trim="form.userNo" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="人员姓名" prop="userNm">
                            <el-input v-model.trim="form.userNm" disabled/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div>选择权限</div>
                <el-tree :data="rightsTree"
                         style="width:100%;height: 350px;overflow: auto;"
                         default-expand-all
                         :props="defaultProps"
												  :default-checked-keys="this.paIdList"
                         node-key="id"

                         ref="rightsTree"
                         show-checkbox
                         highlight-current
                >
								 			<span class="icon-tree" slot-scope="{ node, data }">
								 					<div v-if="data.alias == 'top'" @click="isCheckedAllClick">
								 						<i class="fa fa-university"></i>
								 						<span>&nbsp;{{node.label}}</span>
								 					</div>
								 					<div v-if="data.alias == 'pa01'">
								 						<i class="fa fa-building"></i>
								 						<span>&nbsp;{{node.label}}</span>
								 					</div>
								 		</span>
                </el-tree>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <zl-button :loading="staLoading" @click="operInstance()">保存</zl-button>
      </span>
        </el-dialog>
        <el-dialog
                :title="diaLogName1"
                :visible.sync="operVisible1"
                @close="clearForm1"
                width="70%"
                :close-on-click-modal="false">
            <div class="double-tree">
                <div>
                    <div>选择员工</div>
                    <el-tree :data="orgTree"
                             default-expand-all
                             :props="defaultProps"
                             node-key="id"
                             ref="orgTree"
                             style="height: 400px;overflow: auto;padding: 20px"
                             show-checkbox>
									<span class="icon-tree" slot-scope="{ node, data }">
										<div v-if="data.alias == 'top'">
											<i class="fa fa-university"></i>
											<span>&nbsp;{{node.label}}</span>
										</div>
										<div v-if="data.alias == 'JG001'">
											<i class="fa fa-building"></i>
											<span>&nbsp;{{node.label}}</span>
										</div>
										<div v-if="data.alias == 'JG002'">
											<i class="fa fa-users"></i>
											<span>&nbsp;{{node.label}}</span>
										</div>
										 <div v-if="data.alias == 'user'">
												<i class="fa fa-cogs"></i>
												<span>&nbsp;{{node.label}}</span>
										</div>
								</span>
                    </el-tree>
                </div>
                <div>
                    <div>选择权限</div>
                    <el-tree :data="rightsTree"
                             style="width:80%;height: 380px;overflow: auto;padding: 20px;box-sizing: border-box"
                             default-expand-all
                             :props="defaultProps"
                             node-key="id"
                             ref="rightsTree1"
                             show-checkbox>
								 			<span class="icon-tree" slot-scope="{ node, data }">
								 					<div v-if="data.alias == 'top'">
								 						<i class="fa fa-university"></i>
								 						<span>&nbsp;{{node.label}}</span>
								 					</div>
								 					<div v-if="data.alias == 'pa01'">
								 						<i class="fa fa-building"></i>
								 						<span>&nbsp;{{node.label}}</span>
								 					</div>
								 		</span>
                    </el-tree>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
    <zl-button @click="operInstance1()"/>
  </span>
        </el-dialog>
    </d2-container>

</template>

<script>
  import { tableOptions } from '@/assets/options'
  import {treeNodeAll} from '@/api/face/record'
  import {getRightsOption,orgPersonTree,getUserRightsList,giveRightsById,giveRightsSave,deleteRights} from '@/api/face/userRights'
  export default {
    name: 'system-merchant',
    data () {
      let checkUserNo = (rule, value, callback) => {
        let reg = /^\w+$/;
        if (!reg.test(value)) {
          return callback(new Error("请输入由数字或字母组成的正确编号"));
        } else {
          callback();
        }
      };
      return {
        isCheckedAll:false,
        paIdss:'',
        paIds:[],
        multipleSelection:[],
        paIdList:[],
        orgTree:[],
        areaIds:[],
        areaIdss:'',
        staLoading:false,
        rightsTree:[],
        diaLogName:'单个人员授权',
        diaLogName1:"批量人员授权",
        operVisible:false,
        operVisible1:false,
        lanuchs:[],
        time:'',
        falg:true,
        leaveOverId:[],
        selection:[],
        disabled:false,
        isExpend:true,
        currentPage:1,
        tableOptions,
        loading: false,
        filter: {
          userNo: '',
          userNm: '',
          depId:'',
          readerCode:"",
          status:"",
          pageSize: 10,
          pageNum: 1
        },
        form:{
          userIds:"",
          paIds:'',
          status:1
        },
        form1:{
          userIds:"",
          paIds:'',
          status:1
        },
        pagination: {
          total: 0
        },
        columns: [
          {
            title: '人员编号',
            key: 'userNo',
            minWidth: '120'
          },
          {
            title: '人员姓名',
            key: 'userNm',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '所属部门',
            key: 'depNm',
            minWidth: '120',
          },
          {
            title: '身份证',
            key: 'extIdCard',
            minWidth: '180'
          },
          // {
          //   title: '有效截止时间',
          //   key: 'face1',
          //   minWidth: '180',
          // },
          {
            title: '权限组',
            key: 'paName',
            minWidth: '180',
          },
          {
            title: '通行时间',
            key: 'times',
            minWidth: '480'
          },
          {
            title: '权限状态',
            key: 'status',
            minWidth: '90',
            formatter (row, column, cellValue, index) {
              if (cellValue === '1') {
                return '已授权'
              } else{
                return '未授权'
              }
            }
          },
          {
            title: '是否下发',
            key: 'lssued',
            minWidth: '90',
            formatter (row, column, cellValue, index) {
              if (cellValue === '1') {
                return '下发'
              } else if (cellValue === '0') {
                return '未下发'
              }
            }
          },
          {
            title: '创建时间',
            key: 'creTm',
            minWidth: '180'
          },
        ],
        rowHandle: {
          columnHeader: '操作',
          minWidth: '180',
          align: 'center',
          custom: [
            {
              text: '授权',
              type: 'primary',
              size: 'small',
              emit: 'edit'
            },
            {
              text: '撤销',
              type: 'danger',
              size: 'small',
              emit: 'delete'
            }
          ]
        },
        currentParentId:'',
        treeData:[],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        data: [],
        rules:{

        }
      }
    },
    methods: {
      isCheckedAllClick(){
this.isCheckedAll=!this.isCheckedAll
        if(this.isCheckedAll){
          this.$refs.rightsTree.setCheckedKeys(this.rightsTree);
        }else{
          this.$refs.rightsTree.setCheckedKeys([]);
        }
      },
      handleNodeClick(data) {
        if(data.alias !=='top'){
          this.falg = true
          this.filter.depId = data.id
        }else{
          this.falg = false
          this.filter.depId = ''
        }
        this.handleList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleTreeNode () {
        treeNodeAll({
          depType: ''
        }).then(res => {
          this.treeData = JSON.parse(res.msgDat)
          // this.form.orgId = this.treeData[0].id
        })
        this.handleList()
      },

      handleList (val) {
        if(val){this.filter.pageNum=1
          this.currentPage = 1}
        this.loading = true
        getUserRightsList(this.filter).then(res => {
          this.loading = false
          this.data = res.page.list
          this.pagination.total = res.page.total
        }).catch(err => {
          this.loading = false
        })
      },

      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },

      handleSizeChange (val) {
        this.filter.pageNum = 1
        this.filter.pageSize = val
        this.handleList()
      },
      operInstance(){
        let temp = this.$refs.rightsTree.getCheckedKeys()
        let arr = []
        temp.forEach((item,index)=>{
          arr.push(item)
        })
        this.form.paIds = arr.map(item => item).join(',')
        if(this.form.paIds === ''){
          this.$message({
            message: '请选择权限',
            type: 'warning'
          })
          return false
        }
        giveRightsSave (this.form).then(res=>{
          this.operVisible = false
          this.$message({
            message: '授权成功',
            type: 'success'
          })
          this.clearForm()
          setTimeout(()=>{
            this.handleTreeNode()
          },5000)
        })
      },
      operInstance1 () {
        let temp = this.$refs.orgTree.getCheckedKeys()
        let arr = []
        temp.forEach((item,index)=>{
          arr.push(item)
        })
        this.form1.userIds = arr.map(item => item).join(',')
        this.form1.paIds = this.$refs.rightsTree1.getCheckedKeys().map(item => item).join(',')
        // console.log(this.form1.paIds)
        if(this.form1.userIds === '' || this.form1.paIds === ''){
          this.$message({
            message: '请选择员工与权限',
            type: 'warning'
          })
          return false
        }
        giveRightsSave (this.form1).then(res=>{
          this.operVisible1=false
          this.$message({
            message: '批量授权成功',
            type: 'success'
          })
          this.clearForm1()
          setTimeout(()=>{
            this.handleTreeNode()
          },5000)
        })
      },
      handleRowEdit ({index, row}) {
        // if(row.status==1){
        //   this.$message({
        //     message: '已为授权状态',
        //     type: 'warning'
        //   })
        //   return
        // }
        this.diaLogName = '单个人员授权'
        giveRightsById({userId:row.userId}).then(res => {
          // this.form = res.facePassageUser
          this.form.userIds=row.userId
          // this.form.paIds=res.facePassageUser.paIds
          this.form.userNo=res.facePassageUser.userNo
          this.form.userNm=res.facePassageUser.userNm
          if(row.paIds){
            this.paIdList=row.paIds.split(',')
          }
          this.operVisible = true
        })
      },
      onMutilDelClick(){
        if(!this.multipleSelection.length){
          this.$message({
            message: '请选择记录',
            type: 'warning'
          })
        }else{
          this.$confirm(`确认删除选中人员权限?`, '确认操作', {
            confirmButtonText: '确定',
            cancelButtonText: '放弃',
            type: 'warning'
          }).then(() => {
            this.areaIds=[]
            this.paIds=[]
            this.multipleSelection.forEach((item,index)=>{
              this.areaIds.push(item.userId)
              this.paIds.push(item.paIds)
            })
            this.areaIdss=this.areaIds.join(",")
            this.paIdss=this.paIds.join(",")
            deleteRights({userIds:this.areaIdss,paIds:this.paIdss,status:2}).then(res=>{
              this.$message({
                message: '撤销成功',
                type: 'success'
              })
              setTimeout(()=>{
                this.handleTreeNode()
              },5000)
            })
          })
        }
      },
      handleRowRemove ({index, row}) {
        if(row.status!=='1'){
          this.$message({
            message: '已为撤销状态或不能撤销',
            type: 'warning'
          })
          return
        }
        this.$confirm(`确定删除该人员权限?`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          let userIds = row.userId
          let paIds=row.paIds
          let status=2
          deleteRights({
            userIds,paIds,status
          }).then(res=>{
            this.$message({
              message: '撤销成功',
              type: 'success'
            })
            setTimeout(()=>{
              this.handleTreeNode()
            },5000)

          })
        })
      },
      getPaIdOptions(){
        getRightsOption().then(res=>{
          this.rightsTree = JSON.parse(res.msgDat)
        })
      },
      clearForm () {
        if (this.$refs['form']!==undefined) {
          this.$refs['form'].resetFields()
        }
        this.$refs.rightsTree.setCheckedKeys([])
        this.form={
          userIds:"",
            paIds:'',
            status:1
        }
      },
      clearForm1 () {
        if (this.$refs['form1']!==undefined) {
          this.$refs['form1'].resetFields()
        }
        this.form1={
          userIds:"",
            paIds:'',
            status:1
        }
          this.$refs.orgTree.setCheckedKeys([])
        this.$refs.rightsTree1.setCheckedKeys([])
      }
    },
    mounted () {
      this.getPaIdOptions()
      this.tableOptions = this.$calcTableHeight(tableOptions,40)
      this.filter.pageSize = this.tableOptions.pageList[0]
      this.handleTreeNode()
      orgPersonTree({userId:''}).then(res=>{
        this.orgTree = JSON.parse(res.msgDat)
        // this.orgTreeTraverse(this.orgTree[0])
      })
    }
  }
</script>