<template>
  <div class="qb permission-adjustment">
    <el-form
      class="search-panel"
      :inline="true"
      label-position="right"
      size="small"
    >
      <el-form-item label="查询对象:">
        <ht-select
          v-model="seachStr.type"
          @change="seachType"
          :options="[
            {key: 'user', value: '用户'},
            {key: 'org', value: '组织'},
            {key: 'post', value: '岗位'},
            {key: 'role', value: '角色'}
          ]"
        />
      </el-form-item>
      <el-input
        v-if="seachStr.type == 'user'"
        size="small"
        clearable
        style="width: 300px;"
        placeholder="请选择用户"
        prefix-icon="el-icon-search"
        v-model="seachStr.typeValue.fullname"
        :disabled="true"
      >
        <el-button
          slot="append"
          @click="selectUser('select')"
          type="primary"
          size="mini"
          >选择</el-button
        >
      </el-input>
      <el-input
        v-if="seachStr.type == 'org'"
        size="small"
        clearable
        style="width: 300px;"
        placeholder="请选择所属组织"
        prefix-icon="el-icon-search"
        v-model="seachStr.typeValue.name"
        :disabled="true"
      >
        <el-button
          slot="append"
          @click="selectOrg('select')"
          type="primary"
          size="mini"
          >选择</el-button
        >
      </el-input>
      <el-input
        v-if="seachStr.type == 'post'"
        size="small"
        clearable
        style="width: 300px;"
        placeholder="请选择所属岗位"
        prefix-icon="el-icon-search"
        v-model="seachStr.typeValue.name"
        :disabled="true"
      >
        <el-button
          slot="append"
          @click="selectPost('select')"
          type="primary"
          size="mini"
          >选择</el-button
        >
      </el-input>
      <el-input
        v-if="seachStr.type == 'role'"
        size="small"
        clearable
        style="width: 300px;"
        placeholder="请选择所属角色"
        prefix-icon="el-icon-search"
        v-model="seachStr.typeValue.name"
        :disabled="true"
      >
        <el-button
          slot="append"
          @click="selectRole('select')"
          type="primary"
          size="mini"
          >选择</el-button
        >
      </el-input>
    </el-form>
    <el-tabs
      v-model="activeName"
      v-if="seachStr.type"
      type="card"
      @tab-click="handleTabClick"
    >
      <el-tab-pane
        label="所属组织岗位"
        v-if="
          seachStr.type == 'user' && JSON.stringify(seachStr.typeValue) != '{}'
        "
        name="1"
      >
        <userOrgPostList :data="seachStr.typeValue" v-if="activeName == '1'" />
      </el-tab-pane>
      <el-tab-pane
        label="所属角色"
        v-if="
          seachStr.type == 'user' && JSON.stringify(seachStr.typeValue) != '{}'
        "
        name="2"
      >
        <userRoleList :data="seachStr.typeValue" v-if="activeName == '2'" />
      </el-tab-pane>
      <el-tab-pane
        label="待办信息"
        v-if="JSON.stringify(seachStr.typeValue) != '{}'"
        name="3"
      >
        <todo :data="seachStr" v-if="activeName == '3'" />
      </el-tab-pane>
      <el-tab-pane
        label="已办信息"
        v-if="
          seachStr.type == 'user' && JSON.stringify(seachStr.typeValue) != '{}'
        "
        name="4"
      >
        <done :data="seachStr" v-if="activeName == '4'" />
      </el-tab-pane>
      <el-tab-pane
        label="流程权限信息"
        name="5"
        v-if="JSON.stringify(seachStr.typeValue) != '{}'"
      >
        <defAuthorizePage :data="seachStr" v-if="activeName == '5'" />
      </el-tab-pane>
      <el-tab-pane
        label="流程配置信息"
        name="6"
        v-if="JSON.stringify(seachStr.typeValue) != '{}'"
      >
        <defSetting :data="seachStr" v-if="activeName == '6'" />
      </el-tab-pane>
      <template v-if="JSON.stringify(seachStr.typeValue) != '{}'">
        <el-tab-pane label="表单列表" name="formTable"> </el-tab-pane>
        <el-tab-pane label="数据列表" name="dataTable"> </el-tab-pane>
      </template>
    </el-tabs>
    <div class="el-tree__empty-block" v-else>
      <el-image :src="noDataImg"></el-image>
      <p class="no-data-text">请选择一个查询对象进行操作~</p>
    </div>
    <ht-table
      class="authorize-table"
      v-if="['formTable', 'dataTable'].includes(activeName)"
      ref="htTable"
      :data="tableData"
      :pageResult="pageResult"
      quick-search-props="NAME_,ALIAS_"
      :show-export="false"
      :is-load-table="false"
      :selection="true"
      :showCustomColumn="false"
      @load="loadData"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:toolbar>
        <el-button
          size="small"
          icon="icon-zhuanyi"
          type="primary"
          :disabled="isDisabled"
          @click="handleTransfer"
          >转移</el-button
        >
        <el-button
          size="small"
          icon="icon-copy"
          :disabled="isDisabled"
          @click="handleCopy"
          >复制</el-button
        >

        <el-popover placement="bottom" v-model="visible">
          <span
            ><i
              class="el-icon-question"
              style="color:rgb(255, 153, 0);margin-right:5px"
            ></i
            >确定删除？</span
          >
          <div class="bottom-btn" style="text-align:right">
            <el-button size="mini" type="text" @click="handleCancel"
              >取消</el-button
            >
            <el-button size="mini" type="primary" @click="batchDelete()"
              >确认</el-button
            >
          </div>
          <el-button
            slot="reference"
            style="marginLeft:10px"
            icon="icon-application-delete"
            :disabled="isDisabled"
            >删除</el-button
          >
        </el-popover>
      </template>
      <template>
        <ht-table-column type="index" width="50" align="center" label="序号" />
        <ht-table-column
          prop="NAME_"
          label="列表名称"
          :show-overflow-tooltip="true"
        />
        <ht-table-column prop="ALIAS_" label="列表别名" />
        <ht-table-column
          prop="VIEW_NAME_"
          label="视图名称"
          v-if="activeName === 'dataTable'"
        />
        <ht-table-column label="授权类型" :sortable="true">
          <template v-slot="{row}">
            <span v-if="activeName === 'dataTable'">数据权限</span>
            <span v-else>{{
              row.AUTH_TYPE_ === 1 ? '数据权限' : '按钮权限'
            }}</span>
          </template>
        </ht-table-column>
        <ht-table-column prop="detail" label="授权明细" align="left">
          <template v-slot="{row}">
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">{{ tooltipContent(row) }}</div>
              <div class="btn-wrap">
                <span
                  class="btn-item"
                  v-for="(item, index) in getAuthorizedDetail(row)"
                  :key="index"
                  >{{
                    (row.AUTH_TYPE_ === 1 || activeName === 'dataTable'
                      ? item.name
                      : item.desc) || '-'
                  }}</span
                >
              </div>
            </el-tooltip>
          </template>
        </ht-table-column>
      </template>
    </ht-table>
    <!--用户选择对话框  -->
    <ht-user-dialog
      ref="eipUserDialog"
      @on-confirm="eipUserDialogOk"
      :currentSelectUsers="currentSelectUsers"
      :config="{account: 'account'}"
      single
      append-to-body
    />
    <!-- 组织选择对话框  -->
    <ht-org-post-dialog
      ref="eipOrgDialog"
      @on-confirm="eipOrgDialogOk"
      :currentSelectOrgs="currentSelectOrgs"
      :config="{code: 'orgCode'}"
      single
      append-to-body
    />
    <!-- 岗位选择对话框  -->
    <ht-post-dialog
      ref="eipPostDialog"
      @on-confirm="eipPostDialogOk"
      :currentSelectPost="currentSelectPost"
      :config="{code: 'postCode'}"
      single
      append-to-body
    />
    <!-- 角色选择对话框  -->
    <ht-role-dialog
      ref="eipRoleDialog"
      @on-confirm="eipRoleDialogOk"
      :currentSelectRole="currentSelectRole"
      :config="{code: 'roleCode'}"
      single
      append-to-body
    />
  </div>
</template>

<script>
const userOrgPostList = () =>
  import('@/views/flow/permissionAdjustment/UserOrgPostList.vue')
const userRoleList = () =>
  import('@/views/flow/permissionAdjustment/UserRoleList.vue')
const todo = () => import('@/views/flow/permissionAdjustment/Todo.vue')
const done = () => import('@/views/flow/permissionAdjustment/Done.vue')
const defAuthorizePage = () =>
  import('@/views/flow/permissionAdjustment/DefAuthorizePage.vue')
const defSetting = () =>
  import('@/views/flow/permissionAdjustment/DefSetting.vue')
import form from '@/api/form.js'
import {validArray} from '@/utils'
export default {
  name: 'permissionAdjustmentManage',
  components: {
    userOrgPostList,
    userRoleList,
    todo,
    done,
    defAuthorizePage,
    defSetting
  },
  data() {
    return {
      activeName: '',
      account: '',
      orgCode: '',
      postCode: '',
      roleCode: '',
      seachStr: {
        type: '',
        typeValue: {}
      }, //查询条件
      noDataImg: require('@/assets/nodata_images/no-data.png'),
      tableData: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
        showTotal: true
      },
      isDisabled: true,
      selectedList: [],
      isSingle: true,
      currentSelectData: [],
      currentDialogKey: 'dialog',
      isFormOrDataOperate: false,
      currentOperateType: 'transfer',
      currentSelectUsers: null,
      currentSelectRole: null,
      currentSelectPost: null,
      currentSelectOrgs: null,
      visible: false
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    },
    'seachStr.typeValue.id'(val) {
      if (val && ['formTable', 'dataTable'].includes(this.activeName)) {
        this.$refs.htTable.load()
      }
    }
  },
  methods: {
    handleCancel() {
      this.visible = false
    },
    loadData(params, cb) {
      const {getDataTemplate, getQueryView} = form
      const urlMap = {
        formTable: getDataTemplate,
        dataTable: getQueryView
      }
      const param = {
        pageBean: this.pageResult,
        ...params,
        params: {id: this.seachStr.typeValue.id}
      }
      urlMap[this.activeName](param)
        .then(({data}) => {
          if (data) {
            const {rows, page, pageSize, total} = data
            this.tableData = rows
            this.pageResult = {
              page,
              pageSize,
              total
            }
          }
        })
        .finally(() => {
          cb()
        })
    },
    openCurrentDialog() {
      this.isSingle = false
      this.isFormOrDataOperate = true
      const selectorMap = {
        user: 'selectUser',
        org: 'selectOrg',
        post: 'selectPost',
        role: 'selectRole'
      }
      this[selectorMap[this.seachStr.type]]('transferDialog')
    },
    handleTransfer() {
      this.currentDialogKey = 'transferDialog'
      this.currentOperateType = 'transfer'
      this.openCurrentDialog()
    },
    filterParams(selectData) {
      let data = []
      if (selectData.length > 0 || this.currentOperateType === 'delete') {
        data = this.selectedList.map(it => {
          let currentObj = {}
          const keyMap = {
            1: 'FILTER_FIELD_',
            2: 'MANAGE_FIELD_'
          }
          const authorizeData = this.getAuthorizedFieldList(it)
          let itData = []
          if (authorizeData && authorizeData.length > 0) {
            itData = authorizeData.map(item => {
              const rightData = validArray(this.getRightData(selectData, item))
              return {
                ...item,
                right:
                  this.activeName === 'dataTable'
                    ? rightData
                    : JSON.stringify(rightData)
              }
            })
          }
          if (this.activeName === 'formTable') {
            currentObj = {
              ALIAS_: it.ALIAS_,
              [keyMap[it.AUTH_TYPE_]]: JSON.stringify(itData)
            }
          } else if (this.activeName === 'dataTable') {
            currentObj = {
              VIEW_ALIAS_: it.VIEW_ALIAS_,
              FILTER_: JSON.stringify(itData)
            }
          }
          return currentObj
        })
      }
      return data
    },
    getRightData(selectData, item) {
      const jurisdiction =
        typeof item.right === 'string' ? JSON.parse(item.right) : item.right
      const right = jurisdiction.map(right => {
        let currentRightData = {
          ...right,
          ...this.getCurrentRightItem(right, selectData)
        }
        if (
          this.currentOperateType === 'delete' &&
          right &&
          right.id &&
          right.id.split(',').includes(this.seachStr.typeValue.id)
        ) {
          if (jurisdiction.length === 1) {
            if (right.id.split(',').length > 1) {
              const {type} = this.seachStr
              currentRightData = {
                ...right,
                id: this.getCurrentDataByType(right, 'id'),
                name: this.getCurrentDataByType(
                  right,
                  type === 'user' ? 'fullname' : 'name'
                )
              }
            } else {
              if (this.activeName === 'formTable') {
                currentRightData = {
                  type: 'none',
                  title: '无',
                  checked: true
                }
              } else if (this.activeName === 'dataTable') {
                currentRightData = {
                  type: 'everyone',
                  title: '所有人',
                  checked: true
                }
              }
            }
          } else {
            currentRightData = ''
          }
        }
        return currentRightData
      })
      return right
    },
    getCurrentDataByType(data, type) {
      const {typeValue} = this.seachStr
      return data[type === 'fullname' ? 'name' : type]
        .split(',')
        .filter(item => item !== typeValue[type])
        .join(',')
    },
    getCurrentRightItem(right, selectData) {
      let currentObj = {
        ...right
      }
      const selectIds = selectData.map(item => item.id)
      const {type, typeValue} = this.seachStr
      const selectNames = selectData.map(item =>
        type === 'user' ? item.fullname : item.name
      )

      if (right) {
        if (type == right.type || (type === 'post' && right.type === 'pos')) {
          const ids = right.id ? right.id.split(',') : []
          const names = right.name ? right.name.split(',') : []
          const copyData = {
            id: this.uniqueArray([...ids, ...selectIds]).join(','),
            name: this.uniqueArray([...names, ...selectNames]).join(',')
          }
          const currentName =
            type === 'user' ? typeValue.fullname : typeValue.name
          const idAndNameObj = {
            id: this.uniqueArray([...ids, ...selectIds])
              .filter(id => id !== typeValue.id)
              .join(','),
            name: this.uniqueArray([...names, ...selectNames])
              .filter(name => name !== currentName)
              .join(',')
          }
          const transData = right.type === 'everyone' ? {} : idAndNameObj
          const typeMap = {
            transfer: transData,
            copy: copyData
          }
          currentObj = {
            ...right,
            ...typeMap[this.currentOperateType]
          }
        }
      }
      return currentObj
    },
    uniqueArray(arr) {
      return Array.from(new Set(arr))
    },
    handleCopy() {
      this.currentDialogKey = 'copyDialog'
      this.currentOperateType = 'copy'
      this.openCurrentDialog()
    },
    batchDelete() {
      this.visible = false
      this.currentOperateType = 'delete'
      this.handleSubmitTransferAuth([])
    },
    getAuthorizedFieldList(row) {
      let detailData = []
      if (this.activeName === 'formTable') {
        const manageField = row.MANAGE_FIELD_ && JSON.parse(row.MANAGE_FIELD_)
        const filterField = row.FILTER_FIELD_ && JSON.parse(row.FILTER_FIELD_)
        detailData = row.AUTH_TYPE_ === 2 ? manageField : filterField
      } else if (this.activeName === 'dataTable') {
        detailData = row.FILTER_ && JSON.parse(row.FILTER_)
      }
      return detailData
    },
    //获取授权详情
    getAuthorizedDetail(row) {
      let currentData = []
      const detailData = this.getAuthorizedFieldList(row)
      if (detailData && detailData.length > 0) {
        currentData = detailData.filter(item => {
          const jurisdiction =
            typeof item.right === 'string' ? JSON.parse(item.right) : item.right
          let jurisdictionList = []
          if (validArray(jurisdiction).length > 0) {
            jurisdictionList = jurisdiction.some(
              it =>
                it.id && it.id.split(',').includes(this.seachStr.typeValue.id)
            )
          }
          return jurisdictionList
        })
      }
      return currentData
    },
    tooltipContent(row) {
      const data = this.getAuthorizedDetail(row).map(item =>
        row.AUTH_TYPE_ === 1 || this.activeName === 'dataTable'
          ? item.name
          : item.desc
      )
      return data && data.length > 0 && data.join(',')
    },
    handleTabClick() {
      if (['formTable', 'dataTable'].includes(this.activeName)) {
        this.$nextTick(() => {
          this.$refs.htTable.load()
        })
      }
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    //选择查询对象后
    seachType() {
      if (this.seachStr.type == 'user') {
        this.activeName = '1'
      } else {
        this.activeName = '3'
      }
      this.seachStr.typeValue = {}
      this.selectedList = []
      this.currentDialogKey = 'dialog'
    },
    //点击选择按钮时设置对应选择器配置
    setCurrentSelectorConfig(type) {
      if (type === 'select') {
        this.currentDialogKey = 'dialog'
        this.isSingle = true
        this.isFormOrDataOperate = false
      }
    },
    //选择所属用户
    selectUser(type) {
      this.setCurrentSelectorConfig(type)
      this.$nextTick(() => {
        this.$refs['eipUserDialog'].showDialog()
      })
    },
    //选择所属组织
    selectOrg(type) {
      this.setCurrentSelectorConfig(type)
      this.$nextTick(() => {
        this.$refs['eipOrgDialog'].showDialog()
      })
    },
    //选择所属岗位
    selectPost(type) {
      this.setCurrentSelectorConfig(type)
      this.$nextTick(() => {
        this.$refs['eipPostDialog'].showDialog()
      })
    },
    //选择所属角色
    selectRole(type) {
      this.setCurrentSelectorConfig(type)
      this.$nextTick(() => {
        this.$refs['eipRoleDialog'].showDialog()
      })
    },
    //提交转移、复制、删除权限
    handleSubmitTransferAuth(data) {
      const {copeOrTransferAuth, queryViewCopeOrTransferAuth} = form
      const urlMap = {
        formTable: copeOrTransferAuth,
        dataTable: queryViewCopeOrTransferAuth
      }
      urlMap[this.activeName](this.filterParams(data)).then(({data}) => {
        const tipMsgMap = {
          transfer: '转移',
          copy: '复制',
          delete: '删除'
        }
        if (data.state) {
          this.$message.success(`${tipMsgMap[this.currentOperateType]}成功`)
          this.isFormOrDataOperate = false
          this.$refs.htTable.load()
        } else {
          this.$message.error(`${tipMsgMap[this.currentOperateType]}失败`)
        }
      })
    },
    //选择用户确认事件
    eipUserDialogOk(data) {
      this.currentSelectUsers = data
      if (this.isFormOrDataOperate) {
        this.handleSubmitTransferAuth(data)
      } else {
        if (data[0]) {
          this.seachStr.typeValue = data[0]
        } else {
          this.seachStr.typeValue = {}
        }
      }
    },
    //选择所属组织确认事件
    eipOrgDialogOk(data) {
      this.currentSelectOrgs = data
      if (this.isFormOrDataOperate) {
        this.handleSubmitTransferAuth(data)
      } else {
        if (data[0]) {
          this.seachStr.typeValue = data[0]
        } else {
          this.seachStr.typeValue = {}
        }
      }
    },
    //选择所属岗位确认事件
    eipPostDialogOk(data) {
      this.currentSelectPost = data
      if (this.isFormOrDataOperate) {
        this.handleSubmitTransferAuth(data)
      } else {
        if (data[0]) {
          this.seachStr.typeValue = data[0]
        } else {
          this.seachStr.typeValue = {}
        }
      }
    },
    //选择所属角色确认事件
    eipRoleDialogOk(data) {
      this.currentSelectRole = data
      if (this.isFormOrDataOperate) {
        this.handleSubmitTransferAuth(data)
      } else {
        if (data[0]) {
          this.seachStr.typeValue = data[0]
        } else {
          this.seachStr.typeValue = {}
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.permission-adjustment {
  height: 100%;
  ::v-deep {
    .el-input-group__append {
      background-color: $--color-primary;
      color: #fff;
    }
    .el-tabs--card {
      padding: 0;
    }
  }
  .authorize-table {
    height: calc(100% - 106px);
    .btn-wrap {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  .btn-item {
    display: inline-block;
    background: #f3f3f3;
    padding: 4px 8px;
    margin-right: 8px;
  }
}
.ht-select {
  .el-input__inner {
    border: 1px solid #dcdee0;
  }
}
.el-main {
  display: block;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  -ms-flex-preferred-size: auto;
  flex-basis: auto;
  overflow: auto;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 0px !important;

 
}
::v-deep .el-main {
  position: relative;
  .toolbar-panel {
    position: absolute;
    right: 0;
  }
}
.el-footer {
  padding: 0px !important;
  padding-top: 5px !important;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  float: left;
}
.syh {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}
.i_s {
  font-size: 20px;
}
.e_t {
  width: 100%;
  padding: 0 !important;
}
.elTable {
  width: 100%;
}
</style>
