<!--
     人员授权管理-角色视图
    @Author:laiyh
    @Date:  2020-08-03
-->
<template>
  <dg-row gutter="1rem">
    <dg-col :span="12">
      <dg-card shadow="never" header="角色列表">
        <!-- 角色搜索栏 -->
        <search-bar
          :conditionForm="roleConditionForm"
          @submitSearch="receiveRoleSearch"
          @submitCurrentApp="getCurrentApp"
        ></search-bar>
        <!-- 角色列表 -->
        <new-table
          ref="table"
          :tableHeader="roleTableHeader"
          :tableUrl="roleTableUrl"
          :condition="roleCondition"
          @handleRowClick="handleRoleRowClick"
        >
        </new-table>
      </dg-card>
    </dg-col>
    <dg-col :span="12">
      <dg-card shadow="never" header="人员列表">
        <!-- 角色搜索栏 -->
        <search-bar
          :conditionForm="userConditionForm"
          @submitSearch="receiveUserSearch"
          @submitDefaultSearch="receiveUserDefaultCondition"
        ></search-bar>
        <!-- 角色操作栏 -->
        <operate-bar :pageOptList="userOptList" @submitPageOpt="receviceOpt"></operate-bar>
        <!-- 角色列表 -->
        <dg-table
          ref="userTable"
          :condition="userCondition"
          :url="userTableUrl"
          row-key="id"
          border
          @selection-change="handleSelectChange"
          :before-quest="handleBeforeQuest"
          lazyLoad
        >
          <dg-table-column type="selection" reserve-selection width="50"></dg-table-column>
          <!-- <dg-table-column type="index" label="序号" width="70"></dg-table-column> -->
          <dg-table-column prop="name" align="center" width="120" label="姓名"></dg-table-column>
          <dg-table-column prop="idcard" align="center" label="身份证号码"></dg-table-column>
          <!-- <dg-table-column prop="orgName" align="center" label="单位名称"></dg-table-column> -->
          <dg-table-column prop="userType" align="center" label="用户类型" enum='UserTypeEnum'></dg-table-column>

          <dg-table-column prop="policeCategory" align="center" code="T_MD_POLICE_TYPE" label="警种"></dg-table-column>
          <dg-table-column prop="policeBusiness" align="center" label="业务域标签"></dg-table-column>
          <dg-table-column label="权限有效期" width="120" align="center">
            <template slot-scope="scope">
              <a href="javascript:;" @click="handleValidateChoose(scope.row)">{{ scope.row.activeTime }}</a>
            </template>
          </dg-table-column>
        </dg-table>
      </dg-card>
    </dg-col>
  </dg-row>
</template>

<script>
import newTable from '@/components/new-table';
import TermValid from './term-validity';
import * as roleAuthApi from '@/api/role-auth-info';
import searchBar from '@/components/search-bar';
import operateBar from '@/components/operate-bar';
import { searchOpt } from '@/mixins/page-opt';
import { userConditionForm } from './DataConfig';
export default {
  name: 'role-list',
  components: {
    newTable,
    searchBar,
    operateBar
  },
  mixins: [searchOpt],
  // 接收父页面传过来的属性
  props: {},
  // 页面数据绑定
  data() {
    return {
      roleCondition: {},
      roleConditionForm: [
        {
          label: '应用系统名称',
          name: 'appId',
          op: '=',
          value: '',
          component: 'SelectApp',
          apiUrl: roleAuthApi.roleViewApplication,
          valueName: 'id',
          labelName: 'name'
        },
        {
          label: '角色名称',
          name: 'name',
          op: 'like',
          value: '',
          component: 'ElInput',
          attr: {
            style: 'width: 150px'
          }
        }
      ],
      roleTableHeader: [
        { label: '角色名称', prop: 'name' },
        { label: '角色层级', prop: 'roleLevel', code: 'DM_ROLE_LEVEL' },
        { label: '应用系统名称', prop: 'appName' },
        { label: '警种', prop: 'policeCategory', code: 'T_MD_POLICE_TYPE' },
        { label: '业务域标签', prop: 'roleBusiness', code: 'DM_POLICE_BUSINESS' }
      ],
      roleTableUrl: roleAuthApi.getRoleListByAppid,
      userConditionForm: [
        {
          label: '单位名称',
          name: 'orgId',
          op: '=',
          value: '',
          apiName: 'getOrgTree',
          nodeKey: 'id',
          type: 'APP',
          component: 'SelectOrgTree',
          placeholder: '请选择单位名称',
          defaultSelectRoot: true
        },
        {
          label: '姓名',
          name: 'name',
          op: 'like',
          value: '',
          component: 'ElInput',
          attr: {
            style: 'width: 130px'
          }
        }
      ],
      userOptList: ['保存'],
      persionListData: [],
      userCondition: {
        roleId: {
          value: '',
          op: '='
        },
        orgId: {
          value: '',
          op: '='
        },
        name: {
          value: '',
          op: 'like'
        }
      },
      userTableUrl: roleAuthApi.userTableUrl,
      checkUserList: [],
      deleteIds: [],

      // 点击动作object
      saveRoleAuthParams: {
        appId: '', // 应用id
        orgId: '', // 机构id
        roleId: '', // 角色id
        appOrgId: '', // 应用绑定的机构id
        staffList: '',
        staffJson: '',
        delStaffJson: ''
      },
      page: 0,
      size: 10,
      total: 0,
      updateUsers: []
    };
  },
  // 计算属性
  computed: {},
  // 方法
  methods: {
    receviceOpt(opt, row) {
      if (opt == '保存') {
        this.handleSave();
      }
    },
    getCurrentApp(item) {
      this.currentAppItem = item;
    },
    receiveRoleSearch(val) {
      this.roleCondition = val;
      this.handleSearch();
      this.saveRoleAuthParams.appOrgId = this.currentAppItem.appOrgId;
      this.saveRoleAuthParams.appId = this.currentAppItem.id;
    },
    receiveUserDefaultCondition(val) {
      for (const key in val) {
        this.userCondition[key].value = val[key].value;
      }
      this.saveRoleAuthParams.orgId = this.userCondition.orgId.value;
    },
    loadUserTable() {
      this.selectUserList = [];
      this.$refs.userTable.searchForm();
      
    },
    receiveUserSearch(val) {
      for (const key in val) {
        this.userCondition[key].value = val[key].value;
      }
      this.saveRoleAuthParams.orgId = this.userCondition.orgId.value;
      if (!this.handleValid()) return;
      this.loadUserTable();

    },
    async handleRoleRowClick({ id, appId }) {
      this.saveRoleAuthParams.roleId = this.userCondition.roleId.value = id;
      this.saveRoleAuthParams.appId = appId;
      this.$refs.userTable.clearAll();
      await this.getUserChecked();
      this.loadUserTable();
    },

    getUserChecked() {
      return new Promise((resolve) => {
        const { orgId, roleId, appId } = this.saveRoleAuthParams;
        // 获取人员列表选中记录
        const queryCheckedParams = {
          orgId,
          roleId,
          appId,
          type: 'role'
        };
        roleAuthApi.getChecked(queryCheckedParams).then((res) => {
          this.checkUserList = res;
          resolve(res);
        });
      });
    },
    handleValid() {
      if (!this.saveRoleAuthParams.roleId) {
        this.$message.warning('请选择角色!');
        return false;
      }
      if (!this.saveRoleAuthParams.orgId) {
        this.$message.warning('请选择单位名称!');
        return false;
      }
      return true;
    },
    // 用户列表数据渲染前整合数据
    handleBeforeQuest(res) {
      const { content, totalElements } = res.data;
      let _content = content.map((item) => {
        return {
          ...item,
          activeTime: '长期'
        };
      });
      this.currentPageContent = _content;
      if (this.checkUserList.length > 0) {
        let rowKeys = [];
        for (let j = 0; j < _content.length; j++) {
          const cItem = _content[j];
          const index = this.checkUserList.findIndex((item) => item.id == cItem.id);
          if (index > -1) {
            _content[j].activeTime = this.checkUserList[index].activeTime;
            rowKeys.push(this.checkUserList[index].id);
          }
        }
        setTimeout(() => {
          this.$refs.userTable.setCheck(rowKeys);
        }, 500);
      }
      this.Usertotal = totalElements;

      const result = {
        data: {
          content: _content,
          totalElements
        }
      };
      return result;
    },
    handleSelectChange(selection) {
      this.selectUserList = this.$lodash.cloneDeep(selection);
    },
    handleSave() {
      if (!this.handleValid()) return;
      if (this.Usertotal == 0) {
        this.$message.warning("没有可保存的数据！");
        return; 
      }
      const { roleId, orgId } = this.saveRoleAuthParams;

      const delUserIds = this.checkUserList
        .filter((item) => !this.selectUserList.map((sItem) => sItem.id).includes(item.id))
        .map((item) => item.id);

      const addUserIds = this.selectUserList
        .filter((item) => !this.checkUserList.map((cItem) => cItem.id).includes(item.id))
        .map((item) => item.id);

      // 剔除掉被删除的再过滤出修改过的，与check接口比较
      const updateUserIncludeDel = this.updateUsers.filter((item) => !delUserIds.includes(item.id));

      const updateUsers = updateUserIncludeDel
        .filter((item) => {
          const index = this.selectUserList.findIndex((sItem) => sItem.id == item.id);
          if (index > -1) {
            if (item.activeTime !== this.selectUserList[index].activeTime) {
              return item;
            }
          }
        })
        .map((item) => {
          return {
            id: item.id,
            activeTime: item.activeTime
          };
        });

      const saveParams = {
        roleId,
        orgId,
        addUserIds,
        delUserIds,
        updateUsers: updateUsers
      };


      // 保存
      roleAuthApi
        .savePersion(saveParams)
        .then(() => {
          this.$message.success('保存成功');
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 有效期选择
    handleValidateChoose(row) {
      const that = this;
      const layer = that.$dgLayer({
        title: '有效期选择',
        area: ['540px', '300px'],
        shade: [0.4, '#FFF'],
        content: TermValid,
        props: {
          operatorRow: row
        },
        on: {
          success: function (res) {
            layer.closeAll(layer.dialogIndex);
            row.activeTime = res.activeTime;
            const index = that.updateUsers.findIndex((item) => item.id == res.id);
            if (index > -1) {
              that.updateUsers[index] = res;
            } else {
              that.updateUsers.push(res);
            }
          }
        }
      });
    }
  },
  // 创建组件时调用
  created() {}
};
</script>

<style lang="scss" scoped>
@import url('./index.scss');
</style>
