<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" inline v-show="showSearch" label-width="90px">
      <el-form-item label="字典类型" prop="dictId">
        <el-select v-model="queryParams.dictId" placeholder="请选择字典类型" filterable remote clearable :remote-method="onSearchDict">
          <el-option v-for="item in dictList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请选择字典名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="是否启用" prop="enableFlag">
        <el-select v-model="queryParams.enableFlag" clearable>
          <el-option v-for="item in dict.type.sys_yes_no" v-bind="item" :key="item.value"/>
        </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="onShowEdit({})" v-hasPermi="['md:sapDictData:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="ids.length !== 1" @click="onShowEdit({})" v-hasPermi="['md:sapDictData:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="!ids.length" @click="handleDelete" v-hasPermi="['md:sapDictData:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-refresh" size="mini" @click="toDict">
          返回
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['md:sapDictData:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="tableLoading" :data="page.records" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="字典名称" prop="name"/>
      <el-table-column label="字典数值" prop="name"/>
      <el-table-column label="字典类型" prop="dictName"/>
      <el-table-column label="是否启用" prop="enableFlag">
        <template slot-scope="{row}">
          <dict-tag :options="dict.type.sys_yes_no" :value="row.enableFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-hasPermi="['md:sapDictData:edit']" size="mini" type="text" icon="el-icon-edit" @click="onShowEdit(row)">
            修改
          </el-button>
          <el-button v-hasPermi="['md:sapDictData:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="page.total>0" :total="page.total" :page.sync="queryParams.current" :limit.sync="queryParams.size" @pagination="getList"/>

    <el-dialog :visible.sync="showEdit" :title="form.id ? '修改字典值' : '新增字典值'" width="750px">
      <el-form ref="form" :model="form" :rules="rules" label-width="95px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典类型" prop="dictId">
              <el-select v-model="form.dictId" placeholder="请选择数据值" filterable remote clearable :remote-method="onSearchDict">
                <el-option v-for="item in dictList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联字典" prop="parentId">
              <el-select v-model="form.parentId" placeholder="请选择数据值" filterable remote clearable :remote-method="onSearchDictData">
                <el-option label="无" :value="0"/>
                <el-option v-for="item in dataList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入数据名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典数值" prop="value">
              <el-input v-model.trim="form.value" placeholder="请输入数据值" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-radio-group v-model="form.enableFlag">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEdit = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, list, get, add, update, del } from '@/api/mes/md/sapDictData'
import { listSapDict } from '@/api/mes/md/sapDict'

export default {
  name: 'Client',
  dicts: ['mes_client_type', 'sys_yes_no'],
  data() {
    return {
      loading: false,
      tableLoading: false,
      ids: [],
      showSearch: true,
      page: {
        total: 0,
        records: []
      },
      showEdit: false,
      queryParams: {
        current: 1,
        size: 10,
        parentId: 0,
        dictId: null,
        name: null,
        enableFlag: 'Y'
      },
      dictList: [],
      dataList: [],
      form: {enableFlag: 'Y'},
      rules: {
        dictId: [{ required: true, message: '字典类型不能为空', trigger: 'change' }],
        name: [{ required: true, max: 32, message: '字典名称不能为空，长度在32字以内', trigger: 'blur' }],
        value: [{ required: true, max: 32, message: '字典名称不能为空，长度在32字以内', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    onSearchDict(name) {
      listSapDict({name, pageNum: 1, pageSize: 100}).then(res => {
        let { rows } = res
        if (this.form.dictId && !rows.some(item => item.id == this.form.dictId)) {
          rows.shift({id: this.form.dictId, name: this.form.dictName})
        }
        this.dictList = rows || []
      })
    },
    onSearchDictData(name) {
      list({name, pageNum: 1, pageSize: 100}).then(res => {
        let { data } = res
        if (this.form.id && !data.some(item => item.id == this.form.id)) {
          data.shift({id: this.form.id, name: this.form.name})
        }
        this.dataList = data || []
      })
    },
    /** 查询客户列表 */
    getList() {
      this.tableLoading = true
      page(this.queryParams).then(response => {
        this.page = response.data
      }).finally(() => this.tableLoading = false)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    onShowEdit(row) {
      this.showEdit = true
      let id = row.id || this.ids[0]
      if (id) {
        get(id).then(res => {
          this.$refs.form.resetFields()
          this.form = res.data || {}
        })
      } else {
        this.$refs.form && this.$refs.form.resetFields()
        this.form = {enableFlag: 'Y'}
      }
      this.onSearchDict(null)
      this.onSearchDictData(null)
    },
    /** 提交按钮 */
    submitForm() {
      if (this.loading) return
      if (this.form.id && this.form.id == this.form.parentId) {
        return this.$message.error("不能关联自己")
      }
      this.loading = true
      this.$refs['form'].validate(valid => {
        if (valid) {
          let edit = this.form.id ? update : add
          edit(this.form).then(() => {
            this.$modal.msgSuccess('操作成功')
            this.showEdit = false
            this.getList()
          }).finally(() => this.loading = false)
        } else {
          this.loading = false
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除客户编号为"' + ids + '"的数据项？').then(function() {
        return del(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('md/dictData/export', {...this.queryParams}, `dictData_${Date.now()}.xlsx`)
    },
    toDict() {
      this.$router.replace("/md/sapDict")
    }
  }
}
</script>
