<template>
  <div class="app-container">
    <el-row :gutter="18">
      <el-col :span="dataRulesVisible ? 12 : 24">
        <el-form ref="searchForm" :model="queryParams" inline label-width="100px">
          <el-form-item v-if="superAdmin && enableTenant===true" :label="$t('ec.user.tenant')" prop="tenantId">
            <ec-tenant v-model="queryParams.tenantId" />
          </el-form-item>
          <el-form-item v-if="superAdmin" :label="$t('ec.app.app')" prop="appId">
            <ec-register-app v-model="queryParams.appId" default-first :tenant-id="queryParams.tenantId" :clearable="false" @hasInit="getResourceData('init')" @change="getResourceData('change')" />
          </el-form-item>
          <el-form-item :label="$t('ec.table.code')" prop="code">
            <el-input v-model="queryParams.code" type="text" :placeholder="$t('ec.table.code')" />
          </el-form-item>
          <el-form-item :label="$t('ec.table.name')" prop="rsrcName">
            <el-input v-model="queryParams.rsrcName" type="text" :placeholder="$t('ec.table.name')" />
          </el-form-item>
          <el-form-item class="searchItem" :label-width="'50px'">
            <el-button type="primary" @click="getResourceData">{{ $t('ec.table.query') }}</el-button>
            <el-button type="default" @click="handleReset">{{ $t('ec.table.reset') }}</el-button>
          </el-form-item>
        </el-form>
        <vxe-virtual-tree
          ref="vxe"
          row-key
          row-id="id"
          show-overflow
          show-header-overflow
          max-height="1000"
          resizable
          border
          highlight-hover-row
          class="vxe-table-element"
          sync-resize
          auto-resize
          :loading="loading"
          :toolbar="tableToolbar"
          :columns="columns"
          :tree-config="{children: 'children'}"
          :data="resourceData"
          :checkbox-config="{ checkStrictly: !checkStrictly, checkField: 'checked', halfField: 'indeterminate'}"
          @checkbox-all="({selection}) => { selections = selection}"
          @checkbox-change="({selection}) => { selections = selection }"
        >
          <template v-slot:rsrc_toolbar_btns>
            <el-button :disabled="resourceData.length === 0" @click="toggleTree">{{ $t('ec.table.expandCollapse') }}</el-button>
            <el-button v-permission="['resource:add']" type="primary" @click="add()">{{ $t('ec.table.add') }}</el-button>
            <el-button v-permission="['resource:edit']" :disabled="banState1" type="warning" @click="edit()">{{ $t('ec.table.edit') }}</el-button>
            <el-button v-permission="['resource:delete']" :disabled="banState2" type="danger" @click="deleteByIds()">
              {{ $t('ec.table.delete') }}
            </el-button>
            <el-button v-if="superAdmin" v-permission="['resource:copy']" type="success" @click="copyRsrc">{{ $t('ec.table.copy') }}</el-button>
            <el-button v-if="superAdmin" v-permission="['resource:sync']" type="primary" @click="rsrcSync">{{ $t('ec.table.sync') }}</el-button>
            <el-button v-if="superAdmin" v-permission="['resource:fixPath']" type="warning" @click="fixAppPath">{{ $t('ec.resource.fixPath') }}</el-button>
            <el-button v-permission="['resource:route']" type="danger" :disabled="banState2" @click="routeChange">{{ $t('ec.resource.routeChange') }}</el-button>
            <!--            <el-button @click="getResourceData">{{ $t('ec.table.refresh') }}</el-button>-->
            <el-button v-permission="['resource:import']" type="primary" @click="importVisible = true">{{ $t('ec.table.import') }}</el-button>
            <el-button v-permission="['resource:export']" type="success" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
          </template>

          <!--使用 bottom 插槽-->
          <template v-slot:bottom>
            <div class="vxe-bottom-container">
              <el-checkbox v-model="checkStrictly">{{ $t('ec.tree.cascade') }}</el-checkbox>
            </div>
          </template>

          <template v-slot:icon_default="{ row }">
            <ec-icon-item v-if="row.rsrcIcon" :icon="row.rsrcIcon" />
            <span v-else>{{ row.rsrcIcon }}</span>
          </template>
          <template v-slot:sort_operation="{ row }">
            <el-input-number v-model="row.sortNm" @change="updateSort(row)" />
          </template>

          <template v-slot:status_operation="{ row }">
            <el-switch
              v-model="row.rsrcStatus"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0"
              @change="updateStatus(row)"
            />
          </template>

          <template v-slot:rsrc_operation="{ row }">
            <el-button type="text" @click="view(row)">{{ $t('ec.table.view') }}</el-button>
            <el-button v-permission="['resource:edit']" type="text" @click="edit(row)">{{ $t('ec.table.edit') }}</el-button>
            <el-button v-permission="['resource:delete']" type="text" @click="deleteByIds(row.id)">{{ $t('ec.table.del') }}</el-button>
            <el-dropdown
              v-permission="['resource:add', 'datarule:view', 'resource:defaultPermission']"
              trigger="click"
              style="padding-left:10px;padding-right:10px;"
              @command="command => dropDownCmd(command, row)"
            >
              <el-button type="text" icon="el-icon-arrow-down" />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-permission="['resource:add']" command="child">{{ $t('ec.tree.addChild') }}</el-dropdown-item>
                <el-dropdown-item v-permission="['datarule:view']" command="datarule">{{ $t('ec.resource.dataRule') }}</el-dropdown-item>
                <el-dropdown-item v-permission="['resource:defaultPermission']" command="permission">{{ $t('ec.resource.defaultPermission') }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </vxe-virtual-tree>
      </el-col>
      <el-col v-show="dataRulesVisible" :span="12">
        <data-rule-view ref="dataruleView" :current-node="currNode" @close="dataRulesVisible = false" />
      </el-col>
    </el-row>

    <rsrc-sync-modal ref="rsrcSyncModal" />

    <copy-modal ref="copyModal" />

    <default-permission ref="defaultPermission" @refreshData="getResourceData" />

    <fix-app-resource ref="fixAppResourceModal" />

    <detail ref="sysrResourceDialog" @refreshData="getResourceData" />

    <ec-import
      :upload-url="importUrl"
      :tpl-url="tplUrl"
      :title="$t('ec.table.importBase')"
      :visible="importVisible"
      :upload-params="{ isNewPk: true, strategy: 'ignore' }"
      @onSuccess="getResourceData"
      @close="importVisible = false"
    >
      <template v-slot:extra_params="{ extraParams }">
        <el-form-item :label="$t('ec.import.isNewPk')">
          <ec-radio-group v-model="extraParams.isNewPk" :ec-data="[ {value: false, label: $t('ec.table.no')}, {value: true, label: $t('ec.table.yes') } ]" />
        </el-form-item>
        <el-form-item :label="$t('ec.import.strategy')">
          <ec-radio-group v-model="extraParams.strategy" :ec-data="[ {value: 'ignore', label: $t('ec.import.ignore')}, {value: 'overwrite', label: $t('ec.import.overwrite') } ]" />
        </el-form-item>
      </template>
    </ec-import>
  </div>
</template>

<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getData, deleteByIds, transRoute, updateSort, updateStatus } from 'ecip-web/api/vue/resource/sysrResourceApi'
import Detail from './components/detail'
import DataRuleView from './components/dataRuleView'
import RsrcSyncModal from './components/rsrcSyncModal'
import DefaultPermission from './components/defaultPermission'
import FixAppResource from './components/fixAppResource'
import CopyModal from 'ecip-web/views/vue/components/copyModal'
import { treeEach } from 'ecip-web/utils/tableUtil'
import { download } from 'ecip-web/utils'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']
export default {
  name: 'VueResourceSysrResourceView',
  components: { RsrcSyncModal, CopyModal, Detail, DataRuleView, DefaultPermission, FixAppResource },
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      expand: false,
      importVisible: false,
      checkStrictly: true,
      dataRulesVisible: false,
      banState1: true, // 工具栏编辑按钮是否禁用，只有当且仅当选择一条记录的时候才可编辑
      banState2: true, //  工具栏删除按钮是否禁用，当选中条数为0的时候禁用
      importUrl: `api/v1/resource/sysrResource/importExcel`,
      tplUrl: `api/v1/resource/sysrResource/excelTemplate`,
      exportUrl: `api/v1/resource/sysrResource/exportExcel`,
      currNode: {},
      // 资源管理
      loading: false,
      resourceData: [],
      selections: [],
      queryParams: {
        tenantId: null,
        appId: null,
        name: '',
        rsrcName: ''
      },
      tableToolbar: {
        id: 'vue.resource.sysrResourceView-toolbar',
        custom: true,
        slots: {
          buttons: 'rsrc_toolbar_btns'
        },
        zoom: true, // 最大化按钮
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      columns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: 'ec.resource.name', field: 'rsrcName', minWidth: 200, fixed: 'left', treeNode: true, showOverflow: true },
        { title: 'ec.route.icons', field: 'rsrcIcon', minWidth: 100, showOverflow: true, slots: { default: 'icon_default' }},
        { title: 'ec.table.code', field: 'code', minWidth: 100, showOverflow: true },
        { title: 'ec.resource.type', field: 'typeSrc', minWidth: 100, showOverflow: true, formatter: ['dict', 'typeSrc'] },
        { title: 'ec.resource.nodeType', field: 'typeNode', minWidth: 100, showOverflow: true, formatter: ['dict', 'typeNode'] },
        { title: 'ec.table.sort', field: 'sortNm', minWidth: 150, showOverflow: true, slots: { default: 'sort_operation' }},
        { title: 'ec.table.status', field: 'rsrcStatus', minWidth: 80, showOverflow: true, slots: { default: 'status_operation' }},
        { title: 'ec.resource.requestUrl', field: 'url', minWidth: 200, showOverflow: true },
        { title: 'ec.resource.permission', field: 'permission', minWidth: 100, showOverflow: true },
        { title: 'AppId', field: 'appId', minWidth: 80, showOverflow: true },
        { title: 'ec.resource.component', field: 'component', minWidth: 200, showOverflow: true },
        { title: 'ec.table.actions', width: 180, fixed: 'right', align: 'center', slots: { default: 'rsrc_operation' }}
      ]
    }
  },
  watch: {
    selections: {
      handler(val) {
        this.banState1 = val.length !== 1
        this.banState2 = val.length === 0
      },
      immediate: true
    }
  },
  created() {
    if (!this.superAdmin) {
      this.getResourceData()
    }
  },
  methods: {
    async updateSort(row) {
      try {
        this.loading = true
        const { message } = await updateSort(row.id, { sortNm: row.sortNm })
        this.$notify.success(message)
        await this.getResourceData()
      } finally {
        this.loading = false
      }
    },
    async updateStatus(row) {
      try {
        this.loading = true
        const { message } = await updateStatus(row.id, { rsrcStatus: row.rsrcStatus })
        this.$notify.success(message)
        await this.getResourceData()
      } finally {
        this.loading = false
      }
    },
    // 资源管理
    async getResourceData(e) {
      this.selections = []
      let expands
      this.$nextTick(() => {
        expands = this.$refs.vxe.getTreeExpandRecords().map(item => item.id)
      })
      try {
        this.loading = true
        const { data } = await getData(this.queryParams)
        this.resourceData = data
        this.$nextTick(() => {
          const result = []
          treeEach(this.resourceData, node => {
            if (expands.includes(node.id)) {
              result.push(node)
            }
          })
          this.$refs.vxe.setTreeExpand(result, true)
        })
      } finally {
        this.loading = false
      }
    },
    dropDownCmd(command, row) {
      switch (command) {
        case 'child':
          this.add(row)
          break
        case 'datarule':
          this.clickDatarule(row)
          break
        case 'permission':
          this.$refs.defaultPermission.init(row)
          break
      }
    },
    add(parent) {
      this.$refs.sysrResourceDialog.init('add', this.queryParams.tenantId, this.queryParams.appId, '', parent)
    },
    edit(row) {
      const item = row || this.selections[0]
      this.$refs.sysrResourceDialog.init('edit', this.queryParams.tenantId, this.queryParams.appId, item)
    },
    view(row) {
      this.$refs.sysrResourceDialog.init('view', this.queryParams.tenantId, this.queryParams.appId, row)
    },
    copyRsrc() {
      const copyUrl = 'api/v1/resource/sysrResource/copyResource'
      this.$refs.copyModal.init(this.$t('ec.resource.copy'), copyUrl)
    },
    rsrcSync() {
      this.$refs.rsrcSyncModal.init()
    },
    fixAppPath() {
      this.$refs.fixAppResourceModal.init()
    },
    async routeChange() {
      const rsrcIds = this.$refs.vxe.getCheckboxRecords().map(item => item.id)
      await transRoute(rsrcIds)
      await this.getResourceData()
      this.$notify.success(this.$t('ec.resource.routeChangeSuccess'))
    },
    clickDatarule(row) {
      if (this.currNode && this.currNode.id !== row.id) {
        this.currNode = row
        this.$refs.dataruleView.init()
      }
      this.dataRulesVisible = true
    },
    deleteByIds(id) {
      this.$confirm(this.$t('ec.message.delConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        const deleteIds = []
        if (id) {
          deleteIds.push(id)
        } else {
          this.$refs.vxe.getCheckboxRecords().forEach(row => {
            const id = row.id
            deleteIds.push(id)
          })
        }
        try {
          this.loading = true
          await deleteByIds(deleteIds)
          await this.getResourceData()
          this.$notify.success(this.$t('ec.message.delSuccess'))
        } finally {
          this.loading = false
        }
      })
    },
    async toggleTree() {
      this.expand = !this.expand
      this.loading = true
      await this.$refs.vxe.setAllTreeExpand(this.expand)
      this.loading = false
    },
    async exportExcel() {
      this.loading = true
      await download({ url: this.exportUrl, method: 'post', data: this.queryParams })
      this.loading = false
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.getResourceData()
    }
  }
}
</script>

<style scoped>

</style>
