<template>
  <div class="permFun-com">
    <div class="table">
      <dee-up-table
        ref="funrtable"
        :index-row="{ title: '序号', width: '80' }"
        :data="showTabData"
        :columns="columns"
        :table-option="tableOptions"
        selection-row
        :pagination="pagination"
        @pagination-size-change="changePageSize"
        @pagination-current-change="changePageNum"
      >
        <dee-tools slot="header" :tools="tools" mode="normal" />
      </dee-up-table>
    </div>
    <import-permission :cur-node="curNode" :appid="appid" :dialog-visible="importDialogVisible" @getList="getPermData" @handleClose="handleClose" />
    <dee-dialog
      :visible.sync="showDialog"
      width="580px"
      :before-close="handleClose"
      :destroy-on-close="true"
      :title="dialogTitle"
      center
    >
      <dee-form
        ref="form"
        :form="form"
        :form-data="formData"
        form-btn-position="center"
        :rules="rules"
        :inline="true"
      />
      <div slot="footer" style="text-align:center">
        <el-button
          type="primary"
          @click="addFun"
        >确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </dee-dialog>
  </div>
</template>
<script>

import { savePerm, updatePerm, removePerm, getPermObjids, exportPerm, exportTemplate } from '@/api/mgt/permission.js'
import ImportPermission from '@/views/permission/importPermission'
export default {
  name: 'PermFun',
  components: { ImportPermission },
  props: {
    curNode: {
      type: Object,
      default: () => {
        null
      }
    },
    selectData: {
      type: Array,
      default: () => {
        []
      }
    },
    appid: {
      type: [String, Number],
      default: () => ''
    }
  },
  data() {
    return {
      dialogTitle: '添加功能权限',
      showDialog: false,
      importDialogVisible: false,
      FunData: [],
      tableData: [],
      form: {
        displayName: '',
        name: ''
      },
      formData: [
        {
          split: 1,
          data: [{
            key: 'displayName',
            title: '权限名称',
            component: {
              name: 'el-input'
            }
          }, {
            key: 'name',
            title: '权限代号',
            component: {
              name: 'el-input'
            }
          }, {
            key: 'operationFlag',
            title: '范围',
            component: {
              name: 'el-select',
              options: [{
                label: '数据权限',
                value: false
              }, {
                label: '操作权限',
                value: true
              }]
            }
          }]
        }
      ],
      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        operationFlag: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        displayName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      tableOptions: {
        highlightCurrentRow: true,
        fit: true,
        size: 'mini',
        indent: 0
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50]
      },
      columns: [
        { title: '操作', minWidth: 40, align: 'center', component: {
          render: (h, row, column, $index) => {
            return row.source === '自定义'
              ? <img src ={ require('@/icons/components/new/c-edit.png') }
                title = '编辑'
                style = 'width:16px;height:16px;cursor:pointer;'
                v-on:click= {() => {
                  this.showDialog = true
                  this.form = JSON.parse(JSON.stringify(row))
                  this.dialogTitle = '编辑功能权限'
                }}
              /> : '/'
          }
        }},
        { title: '权限名称', key: 'displayName', minWidth: 120 },
        { title: '权限代号', key: 'name', minWidth: 120 },
        { title: '范围', key: 'operationFlag', minWidth: 120, formatter(row) {
          return row.operationFlag ? '操作权限' : '数据权限'
        } }
      ]
    }
  },
  computed: {
    tools() {
      return [
        {
          type: 'icon',
          name: '新增',
          icon: require('@/icons/designcenter/c-add.png'),
          handler: {
            click: () => {
              this.add()
            }
          }
        },
        {
          type: 'icon',
          name: '删除',
          icon: require('@/icons/designcenter/c-creatbackups.png'),
          handler: {
            click: () => {
              this.removePerm()
            }
          }
        },
        {
          name: '导入',
          icon: '/icons/c-Import.png',
          handler: {
            click: () => {
              // eslint-disable-next-line vue/no-side-effects-in-computed-properties
              this.importDialogVisible = true
            }
          }
        },
        {
          name: '导出',
          icon: '/icons/c-export.png',
          handler: {
            click: () => {
              const rows = this.$refs['funrtable'].$refs['deeTable'].selection
              const params = { 'items': [{ 'fieldName': 'id', 'operator': 'IN', 'value': rows.map(r => r.id) }], 'operator': 'AND' }
              exportPerm(params).then(res => {
                this.$utils.downLoadFile(res)
              }).catch(e => {
                const message = e.data && e.data.message
                this.$utils.showMessageWarning(message || '数据包下载出错:未找到数据包内容的下载链接,请联系管理员排查问题!')
              })
            }
          }
        },
        {
          name: '下载导入模板',
          icon: '/icons/c-download.png',
          handler: {
            click: () => {
              exportTemplate().then(res => {
                this.$utils.downLoadFile(res)
              }).catch(e => {
                const message = e.data && e.data.message
                this.$utils.showMessageWarning(message || '数据包下载出错:未找到数据包内容的下载链接,请联系管理员排查问题!')
              })
            }
          }
        }
      ]
    },
    showTabData() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.FunData.slice(start, end)
    }
  },
  watch: {
    curNode(val) {
      if (val && val.id) {
        this.pagination.currentPage = 1
        this.getPermData()
      }
    }
  },
  methods: {
    getPermData() {
      // const parentIds = this.selectData && this.selectData.length ? 'objIds=' + this.selectData.join('&objIds=') : 'objIds='
      const id = `objIds=${this.curNode && this.curNode.id || this.appid}`
      // const p1 = getPermObjids(parentIds)
      const p2 = getPermObjids(id)
      Promise.all([p2]).then(([{ code: code2, items: items2 }]) => {
        let arr = []
        let count = 0
        if (items2) {
          arr = items2.map(el => {
            // el.source = '自定义'
            return el
          })
          count = items2.length
        }
        // if (items1) {
        //   items1 = items1.map(el => {
        //     el.source = null
        //     return el
        //   })
        //   arr = [...arr, ...items1]
        //   count += items1.length
        // }
        this.$nextTick(() => {
          this.pagination.total = count
          this.FunData = arr.map(row => {
            row.show = true
            return row
          })
        })
      })
    },
    changePageSize(pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.currentPage = 1
    },
    changePageNum(pageNum) {
      this.pagination.currentPage = pageNum
    },
    add() {
      if (this.curNode) {
        this.showDialog = true
        this.dialogTitle = '添加功能权限'
      } else {
        this.$message.warning('请先选择属性节点')
      }
    },
    handleClose() {
      this.showDialog = false
      this.importDialogVisible = false
      this.form = {
        displayName: '',
        name: ''
      }
    },
    removePerm() {
      const rows = this.$refs['funrtable'].$refs['deeTable'].selection
      const delData = rows.filter(el => {
        return el.source !== '自定义'
      })
      if (rows.length === 0) {
        this.$message.warning('请先选择功能权限')
        return
      } else if (delData.length !== 0) {
        this.$message.warning('请选择本节点的数据进行删除')
        return
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removePerm(rows.map(r => r.id)).then(r => {
          this.getPermData()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    addFun() {
      const { name, displayName, id } = this.form
      if (!displayName) {
        this.$message({ message: '权限名称不能为空', type: 'warning' })
        return false
      }
      if (!name) {
        this.$message({ message: '权限代号不能为空', type: 'warning' })
        return false
      }
      if (id) {
        updatePerm(this.form).then(({ code, message }) => {
          this.$message.success('更新成功')
          this.handleClose()
          this.getPermData()
          return
        })
      } else {
        savePerm({
          appId: this.appid,
          appName: this.curNode && this.curNode.name,
          id,
          name: name,
          displayName: displayName,
          objId: (this.curNode && this.curNode.id) || null,
          remark: '',
          source: '自定义',
          operationFlag: this.form.operationFlag
        }).then(r => {
          this.$message.success('添加成功')
          this.handleClose()
          this.getPermData()
        })
      }
    }
  }
}
</script>
<style lang="scss" >
.permFun-com{
  height: 100%;
  .table{
    height:100%;
  }
  .btn-bar {
    margin-bottom: 10px;
  }
}
</style>