<template>
  <div class="app-container dict-data-page">
    <el-page-header @back="goBack" :content="pageHeaderTitle" class="page-header-bar mb16" />

    <el-card shadow="never" class="mb16 filter-card" v-show="showSearch">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" label-width="72px">
      <el-form-item v-if="!isTenantMode" label="字典名称" prop="dictType">
        <el-select v-model="queryParams.dictType" size="small">
          <el-option v-for="item in typeOptions" :key="item.dictId" :label="item.dictName" :value="item.dictType" />
        </el-select>
      </el-form-item>
      <el-form-item label="字典标签" prop="dictLabel">
        <el-input v-model="queryParams.dictLabel" placeholder="请输入字典标签" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>

    <el-row :gutter="10" class="mb8 toolbar-row">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="addPermi">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="editPermi">修改</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="removePermi">删除</el-button></el-col>
      <el-col :span="1.5" v-if="!isTenantMode">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['system:dict:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="dataList" border size="small" class="dict-table" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编码" align="center" prop="dictCode" width="90" />
      <el-table-column label="字典标签" align="center" prop="dictLabel">
        <template slot-scope="scope">
          <span v-if="!scope.row.listClass || scope.row.listClass === 'default'">{{ scope.row.dictLabel }}</span>
          <el-tag v-else :type="scope.row.listClass === 'primary' ? '' : scope.row.listClass">{{ scope.row.dictLabel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="字典键值" align="center" prop="dictValue" />
      <el-table-column label="字典排序" align="center" prop="dictSort" width="80" />
      <el-table-column v-if="isTenantMode" label="来源" align="center" width="80">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.dictSource === 'platform' ? 'warning' : 'success'">
            {{ scope.row.dictSource === 'platform' ? '平台' : '租户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="isTenantMode" label="平台管控" align="center" width="90">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.isPlatformManaged === 1 ? 'danger' : 'info'">{{ scope.row.isPlatformManaged === 1 ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope"><dict-tag :options="statusOptions" :value="scope.row.status"/></template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope"><span>{{ parseTime(scope.row.createTime) }}</span></template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="130" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="editPermi">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" style="color:#f5222d" @click="handleDelete(scope.row)" v-hasPermi="removePermi">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="520px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型"><el-input v-model="form.dictType" disabled /></el-form-item>
        <el-form-item label="数据标签" prop="dictLabel"><el-input v-model="form.dictLabel" /></el-form-item>
        <el-form-item label="数据键值" prop="dictValue"><el-input v-model="form.dictValue" :disabled="form.dictCode != null" /></el-form-item>
        <el-form-item label="样式属性" prop="cssClass"><el-input v-model="form.cssClass" /></el-form-item>
        <el-form-item label="显示排序" prop="dictSort"><el-input-number v-model="form.dictSort" controls-position="right" :min="0" /></el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option v-for="item in listClassOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注"><el-input v-model="form.remark" type="textarea" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listData, getData, delData, addData, updateData, exportData } from '@/api/system/dict/data'
import { listType, getType } from '@/api/system/dict/type'
import {
  listTenantDictData, getTenantDictData, addTenantDictData,
  updateTenantDictData, delTenantDictData, getTenantDictType
} from '@/api/tenant/dict'

export default {
  name: 'Data',
  data() {
    return {
      tenantId: null,
      loading: true,
      exportLoading: false,
      ids: [],
      selectedRows: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      dataList: [],
      defaultDictType: '',
      title: '',
      open: false,
      listClassOptions: [
        { value: 'default', label: '默认' }, { value: 'primary', label: '主要' },
        { value: 'success', label: '成功' }, { value: 'info', label: '信息' },
        { value: 'warning', label: '警告' }, { value: 'danger', label: '危险' }
      ],
      statusOptions: [],
      typeOptions: [],
      queryParams: { pageNum: 1, pageSize: 10, dictLabel: undefined, dictType: undefined, status: undefined },
      form: {},
      rules: {
        dictLabel: [{ required: true, message: '数据标签不能为空', trigger: 'blur' }],
        dictValue: [{ required: true, message: '数据键值不能为空', trigger: 'blur' }],
        dictSort: [{ required: true, message: '数据顺序不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    isTenantMode() { return !!this.tenantId },
    pageHeaderTitle() {
      const type = this.defaultDictType || ''
      return this.isTenantMode ? ('租户字典数据 - ' + type) : ('字典数据 - ' + type)
    },
    isAdminRoute() { return this.$route.path.indexOf('/admin') === 0 },
    addPermi() { return this.isTenantMode ? ['tenant:dict:add'] : ['system:dict:add'] },
    editPermi() { return this.isTenantMode ? ['tenant:dict:edit'] : ['system:dict:edit'] },
    removePermi() { return this.isTenantMode ? ['tenant:dict:remove'] : ['system:dict:remove'] }
  },
  created() {
    this.initTenantContext()
    const dictId = this.$route.params && this.$route.params.dictId
    this.loadDictType(dictId)
    if (!this.isTenantMode) this.getTypeList()
    this.getDicts('sys_normal_disable').then(r => { this.statusOptions = r.data })
  },
  methods: {
    initTenantContext() {
      this.tenantId = this.$route.query.tenantId ? Number(this.$route.query.tenantId) : null
    },
    goBack() {
      const from = this.$route.query.from
      if (from) {
        this.$router.push(from)
        return
      }
      if (window.history.length > 1) {
        this.$router.go(-1)
        return
      }
      const activeMenu = this.$route.meta && this.$route.meta.activeMenu
      if (activeMenu) {
        const query = this.tenantId ? { tenantId: this.tenantId } : {}
        this.$router.push({ path: activeMenu, query })
      }
    },
    isPlatformLocked(row) {
      if (!row) return false
      return Number(row.isPlatformManaged) === 1
    },
    assertNotPlatformLocked(rows) {
      if (!this.isTenantMode) return true
      const locked = (rows || []).filter(r => this.isPlatformLocked(r))
      if (!locked.length) return true
      this.$message.warning('「' + (locked[0].dictLabel || locked[0].dictName) + '」为平台管控字典，请通过「平台模板 + 同步下发」维护')
      return false
    },
    loadDictType(dictId) {
      const req = this.isTenantMode ? getTenantDictType(this.tenantId, dictId) : getType(dictId)
      req.then(response => {
        this.queryParams.dictType = response.data.dictType
        this.defaultDictType = response.data.dictType
        this.getList()
      })
    },
    getTypeList() {
      listType().then(response => { this.typeOptions = response.rows })
    },
    getList() {
      this.loading = true
      const req = this.isTenantMode
        ? listTenantDictData(this.tenantId, this.queryParams)
        : listData(this.queryParams)
      req.then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    cancel() { this.open = false; this.reset() },
    reset() {
      this.form = { dictCode: undefined, dictLabel: undefined, dictValue: undefined, cssClass: undefined, listClass: 'default', dictSort: 0, status: '0', remark: undefined }
      this.resetForm('form')
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.dictType = this.defaultDictType
      this.handleQuery()
    },
    handleAdd() { this.reset(); this.open = true; this.title = '添加字典数据'; this.form.dictType = this.queryParams.dictType },
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.ids = selection.map(item => item.dictCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleUpdate(row) {
      const target = row && row.dictCode ? row : this.selectedRows[0]
      if (this.isTenantMode && target && !this.assertNotPlatformLocked([target])) return
      this.reset()
      const dictCode = (target && target.dictCode) || this.ids[0]
      const req = this.isTenantMode ? getTenantDictData(this.tenantId, dictCode) : getData(dictCode)
      req.then(response => { this.form = response.data; this.open = true; this.title = '修改字典数据' })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) return
        let req
        if (this.isTenantMode) {
          const payload = { ...this.form }
          delete payload.dictSource
          delete payload.isPlatformManaged
          req = this.form.dictCode != null
            ? updateTenantDictData(this.tenantId, payload)
            : addTenantDictData(this.tenantId, payload)
        } else {
          req = this.form.dictCode != null ? updateData(this.form) : addData(this.form)
        }
        req.then(() => { this.msgSuccess('保存成功'); this.open = false; this.getList() })
          .catch(err => { this.$message.error((err && err.message) || err || '保存失败') })
      })
    },
    handleDelete(row) {
      const targets = row && row.dictCode ? [row] : this.selectedRows
      if (this.isTenantMode && !this.assertNotPlatformLocked(targets)) return
      const dictCodes = row.dictCode || this.ids.join(',')
      this.$confirm('是否确认删除?', '警告', { type: 'warning' })
        .then(() => this.isTenantMode ? delTenantDictData(this.tenantId, dictCodes) : delData(dictCodes))
        .then(() => { this.getList(); this.msgSuccess('删除成功') })
        .catch(err => {
          if (err && err !== 'cancel') {
            this.$message.error((err && err.message) || err || '删除失败')
          }
        })
    },
    handleExport() {
      this.$confirm('是否确认导出?', '警告', { type: 'warning' }).then(() => {
        this.exportLoading = true
        return exportData(this.queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => { this.exportLoading = false })
    }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 8px; }
.mb16 { margin-bottom: 16px; }
.filter-card { padding-bottom: 0; }
.toolbar-row { display: flex; flex-wrap: wrap; align-items: center; }
.dict-table { width: 100%; }
.page-header-bar >>> .el-page-header__content { font-size: 16px; font-weight: 600; }
</style>
