<template>
  <div class="appRole-container">
    <el-card>
      <el-row>
        <el-form ref="searchForm" :model="queryParams" inline :label-width="'80px'">
          <el-form-item :label="$t('ec.table.name')" prop="roleName">
            <el-input v-model="queryParams.name" type="text" :placeholder="$t('ec.table.name')" />
          </el-form-item>
          <el-form-item v-permission="['report:admin']" :label="$t('ec.user.tenant')" prop="tenantId">
            <ec-tenant-by-pro placeholder="$t('ec.user.tenant')" @getTenant="getTenant" />
          </el-form-item>
          <el-form-item v-permission="['report:admin']" :label="$t('ec.role.creator')" prop="appId">
            <ec-contact v-model="queryParams.creatorId"  valueField='username' />
          </el-form-item>

          <el-form-item class="searchItem" :label-width="'50px'">
            <el-button type="primary" @click="queryData">{{ $t('ec.table.query') }}</el-button>
            <el-button type="default" @click="handleReset">{{ $t('ec.table.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <vxe-grid
            ref="vxe"
            row-key
            show-overflow
            show-header-overflow
            max-height="1000"
            highlight-current-row
            highlight-hover-row
            border
            resizable
            sync-resize
            auto-resize
            class="vxe-table-element"
            :loading="loading"
            :start-index="(page.currentPage - 1) * page.pageSize"
            :pager-config="page"
            :columns="columns"
            :data="roleData"
            :toolbar="tableToolbar"
            @page-change="handlePageChange"
          >
            <template v-slot:role_toolbar_btns>
              <el-button v-permission="['role:add']" type="primary" @click="openWindow('','save')">{{ $t('ec.table.add') }}</el-button>
            </template>

            <template v-slot:role_header>
              <vxe-tooltip :content="$t('ec.role.selectAlert')" enterable>
                <i class="el-icon-question" />
              </vxe-tooltip>
            </template>

            <template v-slot:role_member_operation="{ row }">
              <el-button size="mini" type="primary " @click="openWindow(row,'preview')">{{ $t('ec.reports.preview') }}</el-button>
              <el-button size="mini" type="success" :disabled="!(row.ifCreator || reportAdmin ) || row.reportStatus != 'new'" @click.stop="operationFn(row,'save')">{{ $t('ec.table.publish') }}</el-button>
              <el-button size="mini" type="primary" :disabled="!(row.ifCreator || reportAdmin || row.reportStatus == 'deleted')" @click.stop="openWindow(row,'edit')">{{ $t('ec.table.edit') }}</el-button>
              <el-button size="mini" type="success" :disabled="!(row.ifCreator || reportAdmin) || row.reportStatus != 'deleted'" @click.stop="operationFn(row,'recovery')">{{ $t('ec.table.recovery') }}</el-button>
              <el-button size="mini" type="danger" :disabled="!(row.ifCreator || reportAdmin) || row.reportStatus == 'deleted'" @click.stop="operationFn(row,'del')">{{ $t('ec.table.delete') }}</el-button>
            </template>

            <template v-slot:role-status="{ row }">
              <span class="" :class="{'text-blue-color':row.reportStatus ==='published','text-red-color':row.reportStatus ==='deleted'}">
                {{ row.reportStatus =='new' ?'已创建':row.reportStatus =='published' ?'已发布':'已删除' }}
              </span>
            </template>
          </vxe-grid>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      title="发布报表"
      :visible.sync="dialogVisible"
      width="550px"
    >
      <ec-tenant-by-pro v-model="saveItem.tenantId" style="width: 400px; margin: 0 auto;" />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="btnLoading"    type="primary" @click="publishFn">确 定</el-button>
        <el-button   @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getData, publishReport, recovery, delReport, getId } from 'ecip-web/api/vue/report'
import mixin from 'ecip-web/utils/common-mixin'
import { getToken } from '@/utils/auth'
export default {
  name: 'ReportList',
  mixins: [...mixin],
  data() {
    return {
      loading: false,
      dialogVisible: false,
      tableToolbar: {
        id: 'vue.role.sysrRoleView-toolbar',
        custom: true,
        slots: {
          buttons: 'role_toolbar_btns'
        },
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        align: 'left',
        pageSizes: [10, 20, 50, 100, 200, 500],
        layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
        perfect: true
      },
      columns: [
        { title: 'ec.user.tenant', field: 'tenantName', minWidth: 100, align: 'center', showOverflow: true },
        { title: 'ec.table.name', field: 'name', minWidth: 80, align: 'center', showOverflow: true },
        { title: 'ec.table.status', minWidth: 40, align: 'center', showOverflow: true, slots: { default: 'role-status' }},
        { title: 'ec.role.creator', field: 'createByName', minWidth: 120, align: 'center', showOverflow: true },
        { title: 'ec.table.createTime', field: 'createTime', minWidth: 100, align: 'center', showOverflow: true },
        { title: 'ec.role.modifiedBy', field: 'updateByName', minWidth: 80, align: 'center', showOverflow: true },
        { title: 'ec.table.modifyTime', field: 'updateTime', minWidth: 80, align: 'center', showOverflow: true },
        { title: 'ec.table.actions', minWidth: 320, align: 'center', fixed: 'right', slots: { default: 'role_member_operation' }}
      ],
      roleData: [], // 角色分页查询结果
      queryParams: {
        tenantId: '',
        creatorId: '',
        name: ''
      },
      tenantId: '',
      reportAdmin: false,
      saveItem: '',
      btnLoading: false
    }
  },
  created() {
    this.reportAdmin = this.checkPermission(['report:admin'])
    this.getData()
  },
  mounted() {
  },
  methods: {
    async saveReport(item) {
      this.btnLoading = true
      try {
        await publishReport({ ...item })
        this.$message.success('操作成功')
        this.getData()
        this.dialogVisible = false
      } finally {
        this.btnLoading = false
      }
    },
    getTenant(item) {
      this.queryParams.tenantId = item[0] ? item[0].value : ''
    },
    publishFn() {
      this.$confirm('确认发布？', '提示').then(() => {
        this.saveReport(this.saveItem)
      })
    },
    operationFn(item, name) {
      switch (name) {
        case 'preview': break
        case 'save':
          this.saveItem = item
          this.dialogVisible = true
          break
        case 'edit': break
        case 'del':
          this.$confirm('确定删除所选报表吗', '提示').then(async() => {
            await delReport([item.id])
            this.$message.success('操作成功')
            this.getData()
          })
          break
        case 'recovery':
          this.$confirm('确定恢复所选报表吗', '提示').then(async() => {
            await recovery([item.id])
            this.$message.success('操作成功')
            this.getData()
          })
          break
        case 'add': break
      }
    },
    openWindow(item, name) {
      switch (name) {
        case 'preview':
          window.open(process.env.VUE_APP_REPORT_URL + `/report/jmreport/view/${item.id}?token=${getToken()}`)
          break
        case 'save':
          getId({}, { token: getToken() }).then((res) => {
            if (res.code == 200) {
              window.open(process.env.VUE_APP_REPORT_URL + `/report/jmreport/index/${res.result.id}?token=${getToken()}`)
            }
          })
          break
        case 'edit':
          window.open(process.env.VUE_APP_REPORT_URL + `/report/jmreport/index/${item.id}?token=${getToken()}`)
          break
      }
    },
    async getData() {
      this.loading = true
      try {
        const data = await getData({ ...this.queryParams }, { current: this.page.currentPage, size: this.page.pageSize })
        const records = data.data.records || []
        records.forEach((item) => {
          if (item.tenantId === '-1' && item.reportStatus !== 'new') {
            item.tenantName = '通用'
          }
        })
        this.roleData = records
        this.page.total = data.data.total
      } finally {
        this.loading = false
      }
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.getData()
    },
    queryData() {
      this.page.currentPage = 1
      this.getData()
    },
    handleReset() {
      Object.assign(this.$data.page, this.$options.data().page)
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.queryData()
    }
  }
}
</script>

<style scoped>
.el-alert {
  margin-top: 4px;
  margin-bottom: 10px;
}
.appRole-container{
  width: 100%;
  height: 100%;
}
  .dialog-class {
  }
</style>
