<template>
  <ht-sidebar-dialog
    title="分配权限"
    :visible="dialogVisible"
    width="1040px"
    :before-close="handleClose"
    close-on-click-modal
  >
    <el-form :inline="true" :model="modelParams">
      <el-form-item>
        <template v-slot:label>
          <el-tag>接口名称:</el-tag>
        </template>
        <span>{{modelParams.name}}</span>
      </el-form-item>
      <el-form-item>
        <template v-slot:label>
          <el-tag>接口URL:</el-tag>
        </template>
        <span>{{modelParams.requestUrl}}</span>
      </el-form-item>
    </el-form>
    <div class="button-con">
      <el-button type="primary" icon="el-icon-plus" @click="addCustomColumn" size="mini">添加</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="delCustomColumn" size="mini">删除</el-button>
    </div>

    <el-table
      v-if="dialogVisible"
      ref="DataAuthTable"
      border
      :max-height="tabHeight"
      :data="displayFields"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column prop="limits" label="权限范围" width="300">
        <template scope="scope">
          <div style="display:flex;justify-content:space-between;align-item:center">
            <span style="width:80%">{{ rightToDesc(scope.row.limits) }}</span>
            <el-button size="small" @click="setFieldRightDialog(scope.row,1)" icon="el-icon-edit"></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="描述">
        <template scope="scope">
          <el-input v-model="scope.row.desc" placeholder="请输入权限描述" maxlength="100" show-word-limit></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="right" label="权限受控类型" width="120">
        <template scope="scope">
          <span>{{ scope.row.controlType?scope.row.controlType:"无" }}</span>
          <span style="float: right">
            <el-button size="small" @click="setFieldRightDialog(scope.row,2)" icon="el-icon-edit"></el-button>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="memo" label="备注">
        <template scope="scope">
          <el-input v-model="scope.row.memo" placeholder="请输入备注" maxlength="100" show-word-limit></el-input>
        </template>
      </el-table-column>
    </el-table>
    <!-- 选择对话框  -->
    <eip-auth-dialog
      ref="eipAuthDialog"
      name="eipAuthDialog"
      @onConfirm="authDialogOnConfirm"
      append-to-body
    />
    <eip-authkind-dialog
      ref="eipAuthkindDialog"
      name="eipAuthkindDialog"
      @onConfirm="authDialogOnConfirm"
      append-to-body
    />
  </ht-sidebar-dialog>
</template>
<script>
const eipAuthDialog = () => import('@/components/dialog/DataAuthDialog.vue')
const eipAuthkindDialog = () =>
  import('@/components/dialog/DataAuthkindDialog.vue')
import req from '@/request.js'
import portal from '@/api/portal'
import {Message} from 'element-ui'
export default {
  props: {},
  components: {
    eipAuthDialog,
    eipAuthkindDialog,
  },

  data() {
    return {
      dialogVisible: false,
      modelParams: {},
      tabHeight: `${document.documentElement.clientHeight}` - 245,
      displayFields: [],
      multipleSelection: [],
      currentAuthRow: null,
      permissionMap: {},
      rightLab: '',
      permissionList1: [],
      permissionList2: [
        {title: '所有人', type: 'everyone'},
        {title: '用户', type: 'user'},
        {title: '组织', type: 'org'},
        {title: '角色', type: 'role'},
      ],
      arry: [],
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.permissionMap = {
      user: '本人',
      userPlus: '本人及直属下级',
      org: '本组织数据',
      orgPlus: '本组织及以下组织数据',
      everyone: '所有',
      orgs: '指定组织',
      users: '指定用户',
    }

    this.arry = [
      '0',
      'user',
      'userPlus',
      'org',
      'orgPlus',
      'orgs',
      'users',
      'everyone',
    ]
    for (let key in this.permissionMap) {
      this.permissionList1.push({
        type: key,
        title: this.permissionMap[key],
      })
    }
    this.displayFields = [
      {
        id: '1',
        limits: '[{"type":"user"}]',
        desc: '测试假数据',
        right: '[{"type":"everyone"}]',
        memo: '测试假数据',
      },
      {
        id: '2',
        limits:
          '[{"type":"orgs","id":"1366653717851541504,1368845159101501440","name":"子公司,研发部"}]',
        desc: '测试假数据',
        right: '[{"type":"everyone"}]',
        memo: '测试假数据',
      },
    ]
    console.log('this.displayFields', this.displayFields)
  },
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    showDialog(modelParams) {
      this.modelParams = modelParams
      this.dialogVisible = true
      this.loadTable(modelParams.id)
    },
    loadTable(id) {
      this.displayFields = []
      let url =
        '${portal}/uc/DataAccessDefined/v1/queryListDataAccessDefined?interfaceId=' +
        id

      req.get(url).then((response) => {
        for (var i = 0; i < response.data.length; i++) {
          let arryData = {}
          arryData.controlType = response.data[i].type
          arryData.id = response.data[i].id
          let arryId = {}
          arryId.type = this.arry[response.data[i].accessRangeType]
          response.data[i].accessRangeId
            ? (arryId.id = response.data[i].accessRangeId)
            : null
          response.data[i].rangeNameList
            ? (arryId.name = response.data[i].rangeNameList)
            : ''
          arryData.limits = JSON.stringify([arryId])
          this.displayFields.push(arryData)
        }
      })
      this.multipleSelection = [];
    },
    // 添加列
    addCustomColumn() {
      let newData = {
        desc: '',
        memo: '',
        right: '[]',
        limits: '[{"type":"user"}]',
      }
      //   this.displayFields.push(newData)
      this.setFieldRightDialog(newData, 1)
    },
    // 删除列
    delCustomColumn() {
      if(!this.multipleSelection.length){
        this.$message.warning("请选择要删除的数据");
        return;
      }else{
        this.$confirm('是否确定删除选中数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id)
          let param = this.qs.stringify({
            ids: ids.join(',')
          });
          let data = {
            url: '${portal}/uc/DataAccessDefined/v1/deleteDataAccessDefinedByIds',
            data: param,
            method: "delete",
            headers:{
              'Content-type': 'application/x-www-form-urlencoded'
            }
          }
          req
            .request(data)
            .then((response) => {
              if (response.data && response.data.state) {
                console.log()
                Message.success({
                  duration: 1500,
                  message: response.data.message,
                })
                this.loadTable(this.modelParams.id)
              } else {
                Message.error(response.data.message || '失败')
              }
            })
        })
        .catch(() => {
          this.$message({
              type: 'info',
              message: `已取消删除`,
          })
        })
      }
      
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //显示权限信息
    rightToDesc(right) {
      if (right) {
        right = JSON.parse(right)
      } else {
        return '无'
      }
      let desc = ''
      let _this = this
      right.forEach((r) => {
        if (desc) {
          desc += ' 和 '
        }
        var str = _this.permissionMap[r.type]
        if (r.name) {
          str += ':' + r.name
        } else if (r.id) {
          str += ':' + r.id
        }
        desc += str
      })
      return desc
    },
    //打开设置权限
    async setFieldRightDialog(row, flag) {
      console.log('row', row, this.permissionList2)
      this.currentAuthRow = row
      if (flag == 1) {
        let conf = {
          limits: JSON.parse(row.limits), //字符串转成对象
          permissionList: this.permissionList1,
        }
        this.$refs.eipAuthDialog.showDialog(conf)
      } else if (flag == 2) {
        let right = {
          type:"none"
        }
        if(row.controlType=="其他"){
          right.type = "otherAuth"
          let params = {
            accessControlId: row.id
          }
          // 查询受控权限类型
          await portal.getDataAuthControlType(params).then(res=>{
            right.accessControlData = res
          })
        }else if(row.controlType=="所有人"){
          right.type = "everyone"
        }
        let conf = {
          right: right, //字符串转成对象
          permissionList: this.permissionList2,
        }
        this.$refs.eipAuthkindDialog.showDialog(conf)
      }
    },
    //设置权限
    authDialogOnConfirm(data, name, flag) {
      console.log('data11', data, this.currentAuthRow, flag)
      if (this.currentAuthRow) {
        if (flag == 1) {
          let param = {
            accessRangeType: 0,
            interfaceId: this.modelParams.id,
            interfaceName: this.modelParams.name,
            // memo: this.currentAuthRow.memo,
            // desc: this.currentAuthRow.desc,
          }
          this.currentAuthRow.id ? (param.id = this.currentAuthRow.id) : null
          data[0].id ? (param.accessRangeId = data[0].id) : null
          param.accessRangeType =
            data[0].type == 'user'
              ? 1
              : data[0].type == 'userPlus'
              ? 2
              : data[0].type == 'org'
              ? 3
              : data[0].type == 'orgPlus'
              ? 4
              : data[0].type == 'orgs'
              ? 5
              : data[0].type == 'users'
              ? 6
              : data[0].type == 'everyone'
              ? 7
              : null
          console.log('param', param)
          req
            .post(
              '${portal}/uc/DataAccessDefined/v1/saveDataAccessDefined',
              param
            )
            .then((response) => {
              if (response.data && response.data.state) {
                Message.success({
                  duration: 1500,
                  message: response.data.message,
                })
                this.loadTable(this.modelParams.id)
              } else {
                Message.error(response.data.message || '失败')
              }
            })
        } else if (flag == 2) {
          let param = {
            accessControlType: 0,
            accessDefinedId: this.currentAuthRow.id,
          }
          for (var i = 0; i < data.length; i++) {
            param.accessControlType = 2
            if (data[i].type == 'user') {
              param.personList = data[i].id
            } else if (data[i].type == 'org') {
              param.orgList = data[i].id
            } else if (data[i].type == 'role') {
              param.roleList = data[i].id
            } else if (data[i].type == 'everyone') {
              param.accessControlType = 1
            }
          }

          console.log('param', param)
          req
            .post(
              '${portal}/uc/DataAccessControl/v1/saveDataAccessDefined',
              param
            )
            .then((response) => {
              if (response.data && response.data.state) {
                Message.success({
                  duration: 1500,
                  message: response.data.message,
                })
                this.loadTable(this.modelParams.id)
              } else {
                Message.error(response.data.message || '失败')
              }
            })
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/.el-dialog {
  height: 100%;
  .el-dialog__body {
    height: auto;
    padding: 10px 20px;
  }
}
.button-con {
  margin-bottom: 10px;
}
</style>