<template>
  <div class="app-container">
    <el-form ref="searchForm" :model="queryParams" inline label-width="60px">
      <el-form-item v-if="enableTenant"
        :label="$t('ec.user.tenant')"
        prop="tenantId"
      >
        <ec-tenant-by-pro v-model="queryParams.tenantId" />
      </el-form-item>
      <el-form-item
        :label="$t('ec.table.positionType')"
        prop="positionType"
      >
        <ec-select v-model="queryParams.positionType" dict-type="positionType" />
      </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="name"
      >
        <el-input v-model="queryParams.name" type="text" :placeholder="$t('ec.table.name')" />
      </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>

    <vxe-grid
      ref="vxe"
      highlight-hover-row
      border
      resizable
      sync-resize
      auto-resize
      show-overflow
      show-header-overflow
      max-height="1000"
      class="vxe-table-element"
      :loading="loading"
      :start-index="(page.currentPage - 1) * page.pageSize"
      :sort-config="{ trigger: 'cell' }"
      :pager-config="page"
      :columns="columns"
      :data="tableData"
      :toolbar="tableToolbar"
      @sort-change="sortMethod"
      @page-change="handlePageChange"
    >
      <template v-slot:toolbar_buttons>
        <el-button v-permission="['sysrPosition:add']" type="primary" @click="add()">{{ $t('ec.table.add') }}</el-button>
        <el-button v-permission="['sysrPosition:edit']" type="warning" :disabled="!onlyOne" @click="edit()">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['sysrPosition:delete']" type="danger" :disabled="!oneMore" @click="deleteByIds()">{{ $t('ec.table.del') }}</el-button>
        <el-button v-permission="['sysrPosition:remove']" type="warning" :disabled="!oneMore" @click="removeByIds()">
          {{ $t('ec.table.remove') }}
        </el-button>
        <el-button v-permission="['sysrPosition:import']" type="success" @click="importVisible = true">{{ $t('ec.table.import') }}</el-button>
        <el-button v-permission="['sysrPosition:export']" type="primary" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
      </template>

      <template v-slot:tenant="{ row }">
        <ec-tenant :value="row.tenantId" readonly />
      </template>

      <template v-slot:operation="{ row }">
        <el-button type="primary" size="mini" @click="userPosition(row)">{{ $t('ec.position.user') }}</el-button>
        <el-button v-permission="['sysrPosition:edit']" type="primary" size="mini" @click="edit(row)">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['sysrPosition:delete']" type="danger" size="mini" @click="deleteByIds(row.id)">{{ $t('ec.table.del') }}</el-button>
        <el-button v-permission="['sysrPosition:remove']" type="warning" size="mini" @click="removeByIds(row.id)">{{ $t('ec.table.remove') }}</el-button>
      </template>
    </vxe-grid>

    <ec-import
      :upload-url="importUrl"
      :tpl-url="tplUrl"
      :title="$t('ec.table.import')"
      :visible="importVisible"
      @onSuccess="getData"
      @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') }, {value: 'update', label: $t('ec.import.update')} ]" />
        </el-form-item>
      </template>
    </ec-import>

    <detail ref="sysrPositionDialog" @refreshData="getData" />

    <position-user-modal ref="positionUserModal" />
  </div>
</template>
<script>
import permissionMixin from 'ecip-web/utils/permission-mixin'
import { getData, removeByIds, deleteByIds } from 'ecip-web/api/vue/position/sysrPositionApi'
import Detail from './components/detail'
import PositionUserModal from './components/positionUserModal'
import { download } from 'ecip-web/utils'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']
export default {
  name: 'WebPositionSysrPositionView',
  components: { Detail, PositionUserModal },
  mixins: [permissionMixin],
  data() {
    return {
      enableTenant,
      importVisible: false,
      showSearch: false,
      loading: false,
      onlyOne: true, // 工具栏编辑按钮是否禁用，只有当且仅当选择一条记录的时候才可编辑
      oneMore: true, //  工具栏删除按钮是否禁用，当选中条数为0的时候禁用
      importUrl: 'api/v1/position/sysrPosition/importExcel',
      tplUrl: 'api/v1/position/sysrPosition/excelTemplate',
      exportUrl: 'api/v1/position/sysrPosition/exportExcel',
      tableToolbar: {
        id: 'web.position.sysrPositionView-toolbar',
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        },
        zoom: true, // 最大化按钮
        // 列宽操作记录
        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,
        field: 'a.create_date',
        order: 'desc'
      },
      selections: [],
      tableData: [],
      columns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: 'ec.user.tenant', field: 'tenantId', tableField: 'tenant_id', visible: enableTenant, minWidth: 180, slots: { default: 'tenant' }},
        { title: 'ec.table.positionType', field: 'positionType', tableField: 'position_type', minWidth: 180 },
        { title: 'ec.table.code', field: 'code', tableField: 'code', minWidth: 180, sortable: true },
        { title: 'ec.table.name', field: 'name', tableField: 'name', minWidth: 180, sortable: true },
        { title: 'ec.table.sort', field: 'sort', tableField: 'sort', minWidth: 180, sortable: true },
        { title: 'ec.table.remarks', field: 'remarks', tableField: 'remarks', minWidth: 180, sortable: true },
        { title: 'ec.table.actions', minWidth: 320, fixed: 'right', align: 'center', slots: { default: 'operation' }}
      ],
      queryParams: {
        code: '',
        name: '',
        positionType: '',
        tenantId: ''
      }
    }
  },
  mounted() {
    this.$watch(this.$refs.vxe.getCheckboxRecords, (newValue, oldValue) => {
      this.selections = newValue
      this.onlyOne = this.selections.length === 1
      this.oneMore = this.selections.length > 0
    })
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      // 每次查询初始化checkbox selections
      this.selections = []
      this.loading = true
      const { data } = await getData(Object.assign({}, { size: this.page.pageSize, current: this.page.currentPage, field: this.page.field, order: this.page.order }), this.queryParams)
      this.tableData = data.records
      this.page.total = data.total
      this.loading = false
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.getData()
    },
    sortMethod({ column, property, order }) {
      this.page.field = (column.own.tableField && 'a.'.concat(column.own.tableField)) || property
      this.page.order = order
      this.getData()
    },
    add() {
      this.$refs.sysrPositionDialog.init('add')
    },
    edit(row) {
      const record = row || this.selections[0]
      this.$refs.sysrPositionDialog.init('edit', record)
    },
    removeByIds(rowId) {
      this.$confirm(this.$t('ec.message.removeConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'error'
      }).then(async() => {
        const removeIds = []
        if (rowId) {
          removeIds.push(rowId)
        } else {
          removeIds.push(...this.selections.map(row => row.id))
        }
        await removeByIds(removeIds)
        await this.getData()
        this.$notify.success(this.$t('ec.message.removeSuccess'))
      })
    },
    deleteByIds(rowId) {
      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: 'error'
      }).then(async() => {
        const deleteIds = []
        if (rowId) {
          deleteIds.push(rowId)
        } else {
          deleteIds.push(...this.selections.map(row => row.id))
        }
        await deleteByIds(deleteIds)
        await this.getData()
        this.$notify.success(this.$t('ec.message.delSuccess'))
      })
    },
    async exportExcel() {
      this.loading = true
      await download({ url: this.exportUrl, method: 'post', data: this.queryParams })
      this.loading = false
    },
    queryData() {
      Object.assign(this.$data.page, this.$options.data().page)
      this.getData()
    },
    handleReset() {
      Object.assign(this.$data.page, this.$options.data().page)
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.getData()
    },
    userPosition(row) {
      this.$refs.positionUserModal.init(row)
    }
  }
}
</script>

<style scoped>

</style>
