<template>
  <Div v-model="show1" style="margin-left: 10px;">
    <Card>
      <template #title>
      <p style="height: 25px;"><Icon type="md-contacts" />数据权限设置
        <Button type="text" size="small" :loading="saveLoading" @click="ok" style="float: right">保存</Button>
      </p>
      </template>
      <RadioGroup v-model="dataPermission.permissionType" @on-change="permissionChange" >
        <Radio :label="1" border>
          <span>区域范围</span>
        </Radio>
        <Radio :label="2" border>
          <span>单位范围</span>
        </Radio>
        <Radio :label="3" border disabled>
          <span>机构范围</span>
        </Radio>
        <Radio :label="4" border disabled>
          <span>用户范围</span>
        </Radio>
        <Radio :label="5" border>
          <span>自定义</span>
        </Radio>
        <Radio :label="6" border>
          <span>未定义</span>
        </Radio>
      </RadioGroup>
      <Row v-show="dataPermission.permissionType<5" style="margin-top: 20px;">
      <col>
        <Col span="2">
          <p style="text-align: center;margin-top: 6px;">范围: </p>
        </col>
        <Col span="16">
          <Select v-model="dataPermission.scopeType" style="width: 243px">
            <Option :value="1" :key="1">全部</Option>
            <Option :value="2" :key="2">本身</Option>
          </Select>
        </col>
      </Row>
      <Row v-show="dataPermission.permissionType===5" type="flex" class="area-tree-row" style="margin-top: 20px;">
        <Input placeholder="请输入关键字搜索..." id="actdKeyword" name="actdKeyword" ></Input>
        <div class="area-tree-div" style="height: 300px;width:100%;overflow: auto">
          <ul id="areaCompanyTreeDiv" class="ztree"></ul>
        </div>
      </Row>


    </Card>
  </Div>
</template>

<script>
  import { addDataPermission,editDataPermission,getDataPermission } from '../../../../api/rbac/data-permission-api'
  import { getAreaCompanyTreeAsyncConfig,getAsyncTree } from '../../../../api/base/company-api'
  import 'ztree/js/jquery.ztree.exhide'
  import {fuzzySearch} from '../../../bc-libs/ztreeSearch.js'

  export default {
    name: "dataPermissionPart",
    props : {
      nowObj: Object,  //组件间交互的参数  当前选择的角色对象
    },
    data () {
      return{
        show1:true,//此组件展示状态
        saveLoading: false,//保存特效展示状态
        dataPermission: {},//数据源
        initDataPermission: {permissionType: 6, scopeType: 1, },//数据源
        scopeValue: [],
        treeObj:null,
        setting: {//ztree树初始化设置
          view: {
            showLine: false,
            selectedMulti: false,
            // showIcon: false
          },
          data: {
            simpleData: {
              enable: true,
              idKey: "id",
              pIdKey: "pid",
              rootPId: null
            }
          },
          async: getAreaCompanyTreeAsyncConfig(),
          check:{
            enable: true,
            chkboxType: { "Y": "ps", "N": "ps" }
          },
          callback: {
            onCheck: this.checkNode,
            onAsyncSuccess: this.selectHasPermission
          }
        },
      }
    },
    methods: {
      permissionChange (){

      },
      ok () {//确认保存
        if (this.dataPermission.permissionType<5){
          this.save();//范围控制保存
        }else if (this.dataPermission.permissionType===5){
          this.dataPermission.scopeType = 3//如果是自定义,那范围的类型就是3
          this.saveCustomize();//自定义控制保存
        }else{
          return false;//理应删除现有的数据权限
        }
      },
      saveCustomize (params){//自定义控制保存
        //获得勾选的节点
        this.treeObj = $.fn.zTree.getZTreeObj("areaCompanyTreeDiv");
        //let nodes = this.treeObj.getCheckedNodes(true);//所有已勾选节点

        //判断是否勾选
        if(this.scopeValue.areaIds.length===0 && this.scopeValue.companyIds.length===0
          && this.scopeValue.orgIds.length===0 && this.scopeValue.userIds.length===0){
          this.$Message.warning("通过树操作至少保存一项权限");
          return;
        }
        //整理ids参数
        //let scopeValue = {areaIds: areaIds, companyIds: companyIds, orgIds: orgIds, userIds: userIds, };//所有级别的权限指定id全部存到一起
        this.dataPermission.scopeValue = JSON.stringify(this.scopeValue)//转成字符串
        this.save();
      },
      save(){//实际保存数据权限的方法
        this.saveLoading = true;//按钮进入操作中状态
        delete this.dataPermission['createTime']
        delete this.dataPermission['modifyTime']
        let fn = this.dataPermission.id?editDataPermission:addDataPermission
        fn(this.dataPermission).then(res => {
          this.$Message.success( "操作成功！");
          //关闭弹窗
          this.saveLoading = false;
          //重载表格
          this.$emit('reload-table-data');
        }).catch(err =>{
          this.$Message.error( "操作失败！");
          this.saveLoading = false;
          console.log(err);
        })
      },
      selectHasPermission(event, treeId, treeNode, msg) {
        if(this.dataPermission.permissionType===5){
          //加载完后,初始化选择框,有权限的勾上
          let nodes = treeNode.children;
          this.selectHasPermissionNode(nodes);
        }
      },
      selectHasPermissionNode (nodes) {//选中有权限的节点
        if (!this.dataPermission.scopeValue || this.dataPermission.scopeValue.length===0)return false
        //将当前权限对象的范围id集合全部拿出来,由于id唯一,所以不需要管是区域还是单位
        if(!this.dataPermission.allIds){
          this.dataPermission.allIds = this.initAllIds();
        }
        //异步加载的子节点
        nodes.forEach(node => {
          if (this.dataPermission.allIds.indexOf(node.id) > -1) {
            this.treeObj.checkNode(node, true, false);
          }
          /*if (node.children && node.children.length>0){
            this.selectHasPermissionNode(node.children);
          }*/
        })
      },
      initAllIds () {
        let allIds = [];
        this.scopeValue = JSON.parse(this.dataPermission.scopeValue);
        allIds = allIds.concat(this.scopeValue.areaIds);
        allIds = allIds.concat(this.scopeValue.companyIds);
        allIds = allIds.concat(this.scopeValue.orgIds);
        allIds = allIds.concat(this.scopeValue.userIds);
        return allIds;
      },
      initData () {//初始化
        if (!this.nowObj.id){
          this.permissionType = 6;
          return false;
        }
        //查询当前对象的数据权限
        getDataPermission(this.nowObj.id).then(res => {
          if (!res.data.result){
            this.dataPermission = JSON.parse(JSON.stringify(this.initDataPermission))
            this.dataPermission.objId = this.nowObj.id
            this.dataPermission.objName = this.nowObj.name
            this.dataPermission.type = 1;
          }else {
            this.dataPermission = res.data.result;
          }
          //this.$forceUpdate();
        })
        //初始化区域-单位树
        getAsyncTree().then(res => {
          this.treeObj = $.fn.zTree.init($("#areaCompanyTreeDiv"), this.setting, res.data.result);
          fuzzySearch('areaCompanyTreeDiv','actdKeyword',null,false);//搜索功能
          //加载完后,初始化选择框
          let nodes = this.treeObj.getNodes();
          this.selectHasPermissionNode(nodes);
        })
      },
      checkNode (event, treeId, treeNode){
        if (treeNode.checked){
          if (treeNode.type === 'area'){
            this.scopeValue.areaIds.push(treeNode.id);
          }else if (treeNode.type === 'company'){
            this.scopeValue.companyIds.push(treeNode.id);
          }else if (treeNode.type === 'org'){
            this.scopeValue.orgIds.push(treeNode.id);
          }else if (treeNode.type === 'user'){
            this.scopeValue.userIds.push(treeNode.id);
          }
        }else {
          if (treeNode.type === 'area'){
            this.scopeValue.areaIds.splice(this.scopeValue.areaIds.indexOf(treeNode.id),1);
          }else if (treeNode.type === 'company'){
            this.scopeValue.companyIds.splice(this.scopeValue.areaIds.indexOf(treeNode.id),1);
          }else if (treeNode.type === 'org'){
            this.scopeValue.orgIds.splice(this.scopeValue.areaIds.indexOf(treeNode.id),1);
          }else if (treeNode.type === 'user'){
            this.scopeValue.userIds.splice(this.scopeValue.areaIds.indexOf(treeNode.id),1);
          }
        }
      },
    },
    watch:{
      nowObj:{//父组件的交互参数
        immediate:true,
        handler:function(){
          //赋值
          this.initData();//初始化数据
        }
      }
    }
  }
</script>

<style scoped>
  .ivu-form-item-search {
    margin-bottom: 3px;
  }
</style>
