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


    <a-row type="flex">
      <a-col  :flex="$mk.config.ui.searchFlex"> 
        <!-- 搜索区 -->
        <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>
      </a-col>
      <a-col  :flex="$mk.config.ui.toolbarFlex">
        <!-- 工具条 -->
        <mk-toolbar @toolbarClick="toolbarClick"></mk-toolbar>
      </a-col>
    </a-row>



 

    <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 #role="{ row }">
         <div v-if="row && row.user_role" class="roles">
          <a-tag v-for="item in row.user_role" :key="row.id + '_' + item.id">{{item.name}}</a-tag>
         </div>
        </template>
        <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 #op2="{ row }">
          <div class="oplinks2">
            <a-button @click.stop="pageRole(row)">关联角色</a-button>
          </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="showRoleSetting" @confirm="confirmRoleSetting" width="600" show-footer>
      <template #title>
        <span>设置角色</span>
      </template>
      <template #default>
        <vxe-table ref="xRoleTable" show-overflow auto-resize height="300" :checkboxConfig="roleCheckboxConfig"
          :rowConfig="{ isCurrent: true, isHover: true }" :data="roleData">
          <vxe-column type="checkbox" width="50"></vxe-column>
          <vxe-column field="name" title="角色名"></vxe-column>
          <vxe-column field="desc" title="描述"></vxe-column>
        </vxe-table>
      </template>
    </vxe-modal>

    <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: 'uid',
      actions: {
        getList: `${BASE_URL.BASE_URL}/BaseAdmin/v1/list`, 
        delete: `${BASE_URL.BASE_URL}/BaseAdmin/v1/batchDelete`,
        roleList: `${BASE_URL.BASE_URL}/BasePermission/v1/role/list`,
        permissionList: `${BASE_URL.BASE_URL}/BasePermission/v1/service/permission/list`,
        userRoleList: `${BASE_URL.BASE_URL}/BasePermission/v1/user/role/list`,
        userPermissionList: `${BASE_URL.BASE_URL}/BasePermission/v1/user/custom/list`,
        saveRole: `${BASE_URL.BASE_URL}/BasePermission/v1/user/role/batchHandle`,
        savePermission: `${BASE_URL.BASE_URL}/BasePermission/v1/user/custom/batchHandle`,
      },
      roleData: [],
      permissionData: [],

      roleCheckboxConfig: {
        reserve: true,
        highlight: true,
        trigger: 'row'
      },
      showRoleSetting: false,
      showPermission: false,
      currentRow: null,

      start_time: 0,
      end_time: 0,

      //搜索区
      searchFormData: {
        name: '',
        nick_name: '',
      },
      searchRules: [
        { key: "name", mode: "like" },
        { key: "nick_name", mode: "like" }
      ],



      searchFormItems: [
        { field: 'name', title: '名称', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } },
        { field: 'nick_name', 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: 'list', // 配置响应结果列表字段
            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: 'realname', sortable: true, title: '名称' },
          { field: 'nickname', sortable: true, title: '昵称', showHeaderOverflow: true },
          { field: 'email', sortable: true, title: 'email', showHeaderOverflow: true },
          { field: 'mobile', sortable: true, title: '电话', showHeaderOverflow: true },
          { title: '角色', slots: { default: 'role' }, width: 150 },
          { title: '角色设置', slots: { default: 'op2' }, width: 120 },
          { 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.roleDataInit();
    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')
        }
      })
    },
    saveRoleSetting({ adds, removes }) {
      if(!adds.length && !removes.length){
        return;
      }
      let userRoleCreateRequest = [];
      adds.forEach(id => {
        userRoleCreateRequest.push({
          "role_id": id,
          "target_uid": this.currentRow.uid
        });
      })

      this.$mk.post({
        url: this.actions.saveRole,
        data: {
          ids: removes,
          userRoleCreateRequest: userRoleCreateRequest
        }
      }).then(a => {
       this.$mk.success(a.msg);
      }).catch(a=>{
       this.$mk.error(a.data.msg);
      })
    },
    confirmRoleSetting() {
      let rows = this.$refs.xRoleTable.getCheckboxRecords();
      this.$mk.post({
        url: this.actions.userRoleList,
        data: {
          target_uid: this.currentRow.uid
        }
      }).then(a => {
        let roleList = a.data.user_role || [];
        let adds = [];
        let removes = [];
        roleList.forEach(roleItem => {
          if (rows.filter(row => row.id == roleItem.role_id).length == 0) {
            removes.push(roleItem.id);
          }
        });
        rows.forEach(row => {
          if (roleList.filter(roleItem => row.id == roleItem.role_id).length == 0) {
            adds.push(row.id);
          }
        })
        this.saveRoleSetting({ adds, removes });
      });
    },
    
    savePermission({ adds, removes }) {
      if(!adds.length && !removes.length){
        return;
      }
      let userCustomCreateRequest = [];
      adds.forEach(id => {
        userCustomCreateRequest.push({
          "permission_code": id,
          "target_uid": this.currentRow.uid
        });
      })

      this.$mk.post({
        url: this.actions.savePermission,
        data: {
          ids: removes,
          userCustomCreateRequest: userCustomCreateRequest
        }
      }).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.userPermissionList,
        data: {
          target_uid: this.currentRow.uid
        }
      }).then(a => {
        let customList = a.data.UserCustom || [];
        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 }); // 保存权限
      });
    },
    roleDataInit() { // 角色数据初始化
      this.$mk.post({
        url: this.actions.roleList,
        data: {
        }
      }).then(a => {
        this.roleData = a.data.Role;

      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });
    },
    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,
            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);
      });
    },


    pageRole(row) { // 角色设置
      if (!row) {
        this.$mk.msg("请选择行");
        return;
      }
      this.currentRow = row;
      this.$mk.post({
        url: this.actions.userRoleList,
        data: {
          target_uid: row.uid
        }
      }).then(a => {
        this.showRoleSetting = true;
        let rows = [];
        let userRole = a.data.user_role || [];
        this.roleData.forEach(item => {
          if (userRole.filter(roleItem => item.id == roleItem.role_id).length) {
            rows.push(item);
          }
        })

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

      });

    },
    pagePermission(row) { // 权限
      if (!row) {
        this.$mk.msg("请选择行");
        return;
      }
      this.currentRow = row; // 当前行
      this.$mk.post({ // 获取用户权限列表
        url: this.actions.userPermissionList,
        data: {
          target_uid: row.uid
        }
      }).then(a => { // 设置权限列表
        this.showPermission = true;
        let rows = [];
       let uesrCustom = a.data.UserCustom || []; // 用户权限 等于 选中的
        this.permissionData.forEach(item => { // 循环权限列表
          if (uesrCustom.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: {
              Uids: 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;
}
.roles .ant-tag{
  margin-bottom: 4px;
}
</style>