<template>
  <div class="app-container">
    <el-alert
      v-if="!tenantId"
      title="请先在上方选择租户，再进行字典维护"
      type="warning"
      show-icon
      :closable="false"
      class="mb8"
    />

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="租户" required>
        <inline-tenant-selector mode="admin" @change="onTenantChange" />
      </el-form-item>
      <el-form-item label="字典名称" prop="dictName">
        <el-input v-model="queryParams.dictName" placeholder="请输入字典名称" clearable size="small" style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input v-model="queryParams.dictType" placeholder="请输入字典类型" clearable size="small" style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="字典状态" clearable size="small" style="width: 140px">
          <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" :disabled="!tenantId">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['tenant:dict:add']" :disabled="!tenantId">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single || !tenantId" @click="handleUpdate" v-hasPermi="['tenant:dict:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple || !tenantId" @click="handleDelete" v-hasPermi="['tenant:dict:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="handleRefreshCache" v-hasPermi="['tenant:dict:edit']" :disabled="!tenantId">刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编号" align="center" prop="dictId" width="90" />
      <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
      <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <router-link :to="{ path: '/admin/tenant-dict-data/index/' + scope.row.dictId, query: { tenantId: tenantId } }" class="link-type">
            <span>{{ scope.row.dictType }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="dictSource" width="90">
        <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 label="平台管控" align="center" prop="isPlatformManaged" 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" class-name="small-padding fixed-width" width="140">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['tenant:dict:edit']" :disabled="isPlatformLocked(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['tenant:dict:remove']" :disabled="isPlatformLocked(scope.row)">删除</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="90px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" :disabled="form.dictId != null" />
        </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="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </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 InlineTenantSelector from '@/components/InlineTenantSelector'
import {
  listTenantDictType, getTenantDictType, addTenantDictType,
  updateTenantDictType, delTenantDictType, refreshTenantDictCache
} from '@/api/tenant/dict'

export default {
  name: 'AdminTenantDict',
  components: { InlineTenantSelector },
  data() {
    return {
      loading: false,
      tenantId: null,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      typeList: [],
      title: '',
      open: false,
      statusOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      form: {},
      rules: {
        dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
        dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    if (this.$route.query.tenantId) {
      this.tenantId = Number(this.$route.query.tenantId)
      this.getList()
    }
  },
  methods: {
    onTenantChange(val) {
      this.tenantId = val
      this.handleQuery()
    },
    isPlatformLocked(row) {
      return row.dictSource === 'platform' || row.isPlatformManaged === 1
    },
    getList() {
      if (!this.tenantId) {
        this.typeList = []
        this.total = 0
        return
      }
      this.loading = true
      listTenantDictType(this.tenantId, this.queryParams).then(response => {
        this.typeList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = { dictId: undefined, dictName: undefined, dictType: undefined, status: '0', remark: undefined }
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加租户字典类型'
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleUpdate(row) {
      this.reset()
      const dictId = row.dictId || this.ids[0]
      getTenantDictType(this.tenantId, dictId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改租户字典类型'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) return
        const req = this.form.dictId != null
          ? updateTenantDictType(this.tenantId, this.form)
          : addTenantDictType(this.tenantId, this.form)
        req.then(() => {
          this.msgSuccess(this.form.dictId != null ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    handleDelete(row) {
      const dictIds = row.dictId || this.ids.join(',')
      this.$confirm('是否确认删除字典编号为"' + dictIds + '"的数据项?', '警告', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => delTenantDictType(this.tenantId, dictIds)).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleRefreshCache() {
      refreshTenantDictCache(this.tenantId).then(() => this.msgSuccess('缓存刷新成功'))
    }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 8px; }
</style>
