<template>
  <div class="page-body">

    <!-- 工具条 -->
    <mk-toolbar @toolbarClick="toolbarClick"></mk-toolbar>



    <!-- 搜索区 -->
    <!-- <vxe-form :data="searchFormData" :items="searchFormItems" titleColon @submit="onSearch">
      <template #date="{}">
        <a-form-item label="创建时间" :style="{ display: 'inline-block', width: 120 }">
        </a-form-item>
        
        <a-form-item :style="{ display: 'inline-block', width: 'calc(100% - 120px )' }">
          <a-range-picker @change="onDateChange" />
        </a-form-item>

      </template>
    </vxe-form> -->


    <!-- 批量删除工具条 -->
    <vxe-toolbar ref="xToolbar" custom>
      <template #buttons>
        <a-button type="primary" icon="delete" @click="pageDelete()">批量删除</a-button>
      </template>
    </vxe-toolbar>



    <!-- 表格区 -->
    <div class="gridPanel">
      <vxe-grid ref='xGrid' v-bind="gridOptions">
      

        <template #op="{ row }">
            <div class="oplinks">
            <a @click.stop="pageEdit(row)" title="编辑"><a-icon type="edit" /></a>
            <a @click.stop="pageDelete(row)" title="删除"><a-icon type="delete" /></a> 
          </div>
          </template> 
        
        <template #op3="{ row }">
          <div class="oplinks2">
            <a-button @click.stop="pagePermission(row)">权限设置</a-button>
          </div>
        </template>
      </vxe-grid>
    </div>
    <vxe-modal v-model="showPermission" @confirm="confirmPermission" width="900" show-footer>
      <template #title>
        <span>设置权限</span>
      </template>
      <template #default>

        <vxe-table show-overflow auto-resize height="500" row-id="id" ref="xPermissionTable" :data="permissionData"
          :tree-config="{ transform: true, expandAll: true }"
          :checkbox-config="{ reserve: true, highlight: true, trigger: 'row', labelField: 'nodeTitle' }">
          <vxe-column type="checkbox" title="权限" width="400" tree-node></vxe-column>
          <vxe-column field="desc" title="描述"></vxe-column>
        </vxe-table>

      </template>
    </vxe-modal>
  </div>
</template>

<script>
import BASE_URL from '@/services/base/api.js';

let editPage = () => import("./edit");

export default { 
  i18n: require('./i18n'),
  data() {

    // 页面数据变量
    var pageData = {

      keyName: 'id', //主键名称
      actions: {  // 接口地址
        getList: `${BASE_URL.BASE_URL}/BasePermission/v1/role/list`, // 获取列表
        delete: `${BASE_URL.BASE_URL}/BasePermission/v1/role/batchDelete`, // 删除

        permissionList: `${BASE_URL.BASE_URL}/BasePermission/v1/service/permission/list`,  //权限列表
        rolePermissionList: `${BASE_URL.BASE_URL}/BasePermission/v1/role/permission/list`,  //角色权限列表
        savePermission: `${BASE_URL.BASE_URL}/BasePermission/v1/role/permission/batchHandle`, //保存角色权限
      },

      permissionData: [], //权限数据

      showPermission: false, //显示权限设置
      currentRow: null, //当前行

      start_time: 0, //开始时间
      end_time: 0, //结束时间

      //搜索区
      searchFormData: {  // 搜索表单数据
        name: '', //角色名称
      },
      searchRules: [
        { key: "name", mode: "like" },
        { key: "desc", mode: "like" }
      ],



      searchFormItems: [
        {
          title: '左侧',
          span: 20,
          children: [
            { field: 'name', title: '角色名称', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } },
            { field: 'desc', title: '角色描述', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入描述' } } },
            { span: 8, slots: { default: 'date' } },
            { align: 'right', span: 4, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' } }, 
            { props: { type: 'reset', content: '重置' } }] } }
          ]
        }
      ],



      //数据区
      gridOptions: {
        height: '100%',
        id: 'datagrid_1',

        proxyConfig: {
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为 
          props: {
            result: 'Role', // 配置响应结果列表字段
            total: 'total' // 配置响应结果总页数字段
          },
          // 接收Promise
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: (options) => {
              const { page, sorts } = options;
              var params = {};
              params.page = page.currentPage;
              params.limit = page.pageSize;
              params.order_bys = [];
              params.search_rules = this.getSearchParms();
              if (sorts) {
                sorts.forEach((v) => {
                  params.order_bys.push({
                    column: v.property,
                    order: v.order
                  })
                });
              }
              return this.loadData({ params });
            }
          }
        },
        columns: [
          { type: 'checkbox', width: 'auto' },
          { type: 'seq', width: 50 },
          { field: 'name', sortable: true, title: '角色' },
          { field: 'desc', sortable: true, title: '角色描述', showHeaderOverflow: true } ,
          { title: '权限设置', slots: { default: 'op3' }, width: 120 },
          { title: '操作', slots: { default: 'op' },width:120 }
        ]
      }
    };

    pageData.gridOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridOptions);

    return pageData;
  },
  computed: {
    desc() {
      return this.$t('pageDesc')
    }
  },
  created() {
    this.$nextTick(() => {
      // 将表格和工具栏进行关联 
      this.$refs.xGrid.connect(this.$refs.xToolbar)
    });

    this.permissionDataInit();
  },
  // 监听 - 页面每次【加载时】执行 
  onLoad() {

  },
  // 函数
  methods: {
    onDateChange(date) {
      if (date && date.length) {
        this.start_time = parseInt(date[0]._d.getTime() / 1000);
        this.end_time = parseInt(date[1]._d.getTime() / 1000);
      } else {
        this.start_time = 0;
        this.end_time = 0;
      }

    },
    getSearchParms() {
      var rules = [];
      let findMode = k => {
        for (let i in this.searchRules) {
          if (this.searchRules[i].key == k) return this.searchRules[i].mode;
        }
        return "equal";
      };

      for (let key in this.searchFormData) {
        let value = this.searchFormData[key];
        if (value) {
          let mode = findMode(key);
          if (mode == "like") {
            value = "%" + value + "%";
          }
          rules.push({
            column: key,
            mode: mode,
            value: value
          });
        }
      }
      return rules;
    },
    getSelectdRow() {
      let row = this.$refs.xGrid.getCurrentRecord();
      if (!row) {
        let rows = this.$refs.xGrid.getCheckboxRecords();
        if (rows && rows.length) { row = rows[0]; }
      }
      return row;
    },
    loadData({ params }) {

      params.start_time = this.start_time;
      params.end_time = this.end_time;


      return this.$mk.getPagedData({ url: this.actions.getList, data: params });
    },


    //add / log / setting
    toolbarClick(e) {
      if (e.name == "add") {
        this.$mk.dialog.open({
          page: editPage,
          title: "新增角色信息",
          pageMode: "add",
          dataId: 0,
          callback: ({ success }) => {
            success && this.$refs.xGrid.commitProxy('query')
          }
        })
      }
    },


    pageEdit(row) {
      if (!row) {
        this.$mk.msg("请选择行");
        return;
      }
      this.$mk.dialog.open({
        page: editPage,
        title: "编辑角色信息",
        pageMode: "edit",
        dataId: row[this.keyName],
        callback: ({ success }) => {
          success && this.$refs.xGrid.commitProxy('query')
        }
      })
    },

    savePermission({ adds, removes }) {
      if(!adds.length && !removes.length){
        return;
      }
      let rolePermissionCreateRequest = [];
      adds.forEach(id => {
        rolePermissionCreateRequest.push({
          "permission_code": id,
          "role_id": this.currentRow.id
        });
      })

      this.$mk.post({
        url: this.actions.savePermission,
        data: {
          ids: removes,
          rolePermissionCreateRequest: rolePermissionCreateRequest
        }
      }).then(a => {
       this.$mk.success(a.msg);
      }).catch(a=>{
       this.$mk.error(a.data.msg);
      })
    },
    confirmPermission() {  
      let rows = this.$refs.xPermissionTable.getCheckboxRecords();
      rows = rows.filter(row=>row.permission_code);

      this.$mk.post({
        url: this.actions.rolePermissionList,
        data: {
          role_id: this.currentRow.id
        }
      }).then(a => {
        let customList = a.data.RolePermission || [];
        let adds = [];
        let removes = [];
        customList.forEach(customItem => {
          if (rows.filter(row => row.permission_code == customItem.permission_code).length == 0) {
            removes.push(customItem.id);
          }
        });
        rows.forEach(row => {
          if (customList.filter(customItem => row.permission_code == customItem.permission_code).length == 0) {
            adds.push(row.permission_code);
          }
        })
        this.savePermission({ adds, removes });
      });
    },
    permissionDataInit() {

      this.$mk.post({
        url: this.actions.permissionList,
        data: {
        }
      }).then(a => {
        let arr = [];
        a.data.BasePermission.forEach(item => {
          if (arr.filter(a => a.id == "s-" + item.service_id).length) {
            return;
          }
          arr.push({
            id: "s-" + item.service_id,
            parentId: null,
            nodeTitle: item.service
          })
        });
        a.data.BasePermission.forEach(item => {

          arr.push({
            id: item.id,
            desc:item.desc,
            parentId: "s-" + item.service_id,
            nodeTitle: item.title,
            service_id: item.service_id,
            permission_id: item.id,
            permission_code: item.permission_code
          })
        }); 
        this.permissionData = arr;

      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });
    },
    pagePermission(row) {
      if (!row) {
        this.$mk.msg("请选择行");
        return;
      }
      this.currentRow = row;
      this.$mk.post({
        url: this.actions.rolePermissionList,
        data: {
          role_id: row.id
        }
      }).then(a => {
        this.showPermission = true;
        let rows = [];
       let rolePermission = a.data.RolePermission || [];
        this.permissionData.forEach(item => {
          if (rolePermission.filter(customerItem => item.permission_code == customerItem.permission_code).length) {
            rows.push(item);
          }
        })

        setTimeout(() => {
          this.$refs.xPermissionTable.clearCheckboxRow();
          this.$refs.xPermissionTable.setCheckboxRow(rows, true);
        }, 100);

      });


    },
    pageDelete(row) {


      let rows = row ? [row] : this.$refs.xGrid.getCheckboxRecords();
      let ids = [];
      rows.forEach((row) => {
        ids.push(row[this.keyName]);

      });
      console.log(rows);
      if (!ids.length) {
        this.$mk.error("请选择行");
        return;
      }

      this.$mk.confirm('您确定要删除吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: this.actions.delete,
            loading: "删除中...",
            data: {
              ids: ids
            }
          }).then(() => {
            this.$mk.success("删除成功");
            this.onSearch();
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
        }
      });


    },
    onSearch() {
      this.$refs.xGrid.commitProxy('query')
    }
  },
  // 监听属性
  watch: {

  }
};

</script>
<style scoped lang="less">
.page-body {
  padding: 20px 20px;
  background:  @base-bg-color;
}
.gridPanel{ 
  height: calc(100vh - 430px); 
}
</style> 
<style>
.oplinks svg {
  width: 22px;
  height: 22px;
  margin: 0 5px 0 0;
}
</style>