<template>
  <div class="app-container">
    <el-page-header @back="goBack" :content="'租户字典数据 - ' + (defaultDictType || '')" class="mb8" />

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <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-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']">新增</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="['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" @click="handleDelete" v-hasPermi="['tenant:dict:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @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">
          <el-tag v-if="scope.row.listClass && scope.row.listClass !== 'default'" :type="scope.row.listClass === 'primary' ? '' : scope.row.listClass">{{ scope.row.dictLabel }}</el-tag>
          <span v-else>{{ scope.row.dictLabel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字典键值" align="center" prop="dictValue" />
      <el-table-column label="排序" align="center" prop="dictSort" width="70" />
      <el-table-column 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 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" 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="字典类型"><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="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="备注" prop="remark"><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 {
  listTenantDictData, getTenantDictData, addTenantDictData,
  updateTenantDictData, delTenantDictData, getTenantDictType
} from '@/api/tenant/dict'

export default {
  name: 'TenantDictData',
  data() {
    return {
      tenantId: null,
      loading: true,
      ids: [],
      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: [],
      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' }]
      }
    }
  },
  created() {
    this.tenantId = Number(this.$route.query.tenantId)
    const dictId = this.$route.params && this.$route.params.dictId
    if (!this.tenantId) {
      this.$message.error('缺少租户ID')
      return
    }
    this.getType(dictId)
    this.getDicts('sys_normal_disable').then(r => { this.statusOptions = r.data })
  },
  methods: {
    goBack() {
      this.$router.push({ path: '/admin/tenantDict', query: { tenantId: this.tenantId } })
    },
    isPlatformLocked(row) {
      return row.dictSource === 'platform' || row.isPlatformManaged === 1
    },
    getType(dictId) {
      getTenantDictType(this.tenantId, dictId).then(response => {
        this.queryParams.dictType = response.data.dictType
        this.defaultDictType = response.data.dictType
        this.getList()
      })
    },
    getList() {
      this.loading = true
      listTenantDictData(this.tenantId, this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        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.ids = selection.map(item => item.dictCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleUpdate(row) {
      this.reset()
      const dictCode = row.dictCode || this.ids[0]
      getTenantDictData(this.tenantId, dictCode).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改字典数据'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) return
        const req = this.form.dictCode != null
          ? updateTenantDictData(this.tenantId, this.form)
          : addTenantDictData(this.tenantId, this.form)
        req.then(() => { this.msgSuccess('保存成功'); this.open = false; this.getList() })
      })
    },
    handleDelete(row) {
      const dictCodes = row.dictCode || this.ids.join(',')
      this.$confirm('是否确认删除?', '警告', { type: 'warning' }).then(() =>
        delTenantDictData(this.tenantId, dictCodes)
      ).then(() => { this.getList(); this.msgSuccess('删除成功') }).catch(() => {})
    }
  }
}
</script>

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