<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="数据类型名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入数据类型名" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="数据类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择数据类型" clearable filterable>
              <el-option v-for="item in dict.type.sys_data_type" :key="item.value" :value="item.value" :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <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-col>
        <el-col :span="6">
          <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-col>
      </el-row>
    </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="['md:propertytype: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="['md:propertytype: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="['md:propertytype:remove']"
        >删除</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:propertytype:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="toPropertyDict"
          v-hasPermi="['md:propertytype:dict']"
        >数据字典</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="数据类型名" prop="name"/>
      <el-table-column label="数据类型" width="150px" :formatter="formatDataType"/>
      <el-table-column label="约束" show-overflow-tooltip>
        <template slot-scope="{row}">
          <div>是否必填：{{ row.required === 'Y' ? '是' : '否' }}</div>
          <div v-if="row.length != null">最大长度：{{ row.length }}</div>
          <div v-if="row.min != null">最小值：{{ row.min }}</div>
          <div v-if="row.max != null">最大值：{{ row.max }}</div>
          <div v-if="row.regEx != null">正则：{{ row.regEx }}</div>
          <div v-if="row.dictId != null">枚举：{{ row.propertyDict.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="提示语" prop="errMsg" show-overflow-tooltip/>
      <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:propertytype:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-hasPermi="['md:propertytype:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(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="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <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="type">
              <el-select v-model.trim="form.type" placeholder="请选择数据类型" clearable>
                <el-option v-for="item in dict.type.sys_data_type" :key="item.value" :value="item.value" :label="item.label"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否必填" prop="required" required>
              <el-radio-group v-model="form.required">
                <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-col v-if="form.type === '1'" :span="12">
            <el-form-item label="最大长度" prop="length">
              <el-input v-model.trim.number="form.length" placeholder="请输入最大长度" clearable/>
            </el-form-item>
            <el-form-item label="正则" prop="regEx">
              <el-input v-model.trim="form.regEx" placeholder="请输入正则" clearable/>
            </el-form-item>
          </el-col>
          <template v-if="['2', '3'].includes(form.type)">
            <el-col :span="12">
              <el-form-item label="最小值" prop="min">
                <el-input v-model.trim.number="form.min" placeholder="请输入最小值" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大值" prop="max">
                <el-input v-model.trim.number="form.max" placeholder="请输入最大值" clearable/>
              </el-form-item>
            </el-col>
          </template>
          <el-col v-if="form.type === '7'" :span="12">
            <el-form-item label="枚举" prop="dictId">
              <el-select v-model="form.dictId" placeholder="请选择枚举类型" filterable remote :remote-method="onSearchDict" clearable>
                <el-option v-for="item in dictList" :key="item.id" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提示语" prop="errMsg">
              <el-input v-model.trim="form.errMsg" placeholder="请输入提示语" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableFlag" required>
              <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 type="primary" @click="cancel" v-if="optType === 'view'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addPropertytype, getPropertytype, listPropertytype, updatePropertytype, delPropertytype } from '@/api/mes/md/propertytype'
import {listPropertyDict} from '@/api/mes/md/propertydict'

export default {
  name: "Client",
  dicts: ['mes_client_type','sys_yes_no', 'sys_data_type'],
  data() {
    return {
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      propertyTypeOptions: [
        {label: '客户特性', value: 1},
        {label: '产品特性', value: 2},
        {label: '订单特性', value: 3},
        {label: '品牌特性', value: 4},
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        name: null,
        enableFlag: 'Y',
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        required: 'Y',
        type: null,
        length: null,
        min: null,
        max: null,
        regEx: null,
        errMsg: null,
        dictId: null,
        enableFlag: 'Y',
      },
      dictList: [],
      // 表单校验
      rules: {
        name: [{ required: true, max: 32, message: '数据类型名称不能为空，长度在32字以内', trigger: 'blur' }],
        type: [{ required: true, message: '数据类型不能为空', trigger: 'blur' }],
        length: [
          { required: true, message: '最大长度不能为空', trigger: 'blur' },
          // { pattern: /^[0-9]{1,4}$/, message: '最大输入为9999', trigger: 'blur' },
        ],
        min: [
          { required: true, message: '最小值不能为空', trigger: 'blur' }
        ],
        max: [
          { required: true, message: '最大值不能为空', trigger: 'blur' }
        ],
        errMsg: [{ required: true, max: 100, message: '提示语不能为空，长度在100字以内', trigger: 'blur' }],
        dictId: [{ required: true, message: '枚举类型不能为空', trigger: ['blur', 'change'] }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPropertytype(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
      }).finally(() => this.loading = false);
    },
    toPropertyDict() {
      this.$router.push("/mes/md/propertydict")
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    onSearchDict(key) {
      if (key !== '') {
        listPropertyDict({name: key}).then(response => this.dictList = response.rows)
      } else {
        this.dictList = []
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        required: 'Y',
        type: null,
        length: null,
        min: null,
        max: null,
        regEx: null,
        errMsg: null,
        dictId: null,
        enableFlag: 'Y',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据类型";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row.id && this.ids.length !== 1) this.$message.error("只能选择一条数据")
      this.reset();
      const id = row.id || this.ids[0]
      listPropertyDict({id: row.dictId}).then(response => this.dictList = response.rows)
      getPropertytype(id).then(response => {
        this.form = response.data;
        this.form.type = response.data.type;
        this.open = true;
        this.title = "修改数据类型";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.min != null && this.form.max != null) {
            if (this.form.min > this.form.max) return this.$message.error("最小值不能大于最大值")
          }
          if (this.form.id != null) {
            updatePropertytype(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPropertytype(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据类型编号为"' + ids + '"的数据项？').then(function() {
        return delPropertytype(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('md/propertytype/export', {
        ...this.queryParams
      }, `propertytype_${new Date().getTime()}.xlsx`)
    },
    formatDataType(row) {
      let item = this.dict.type.sys_data_type.find(item => item.value === row.type)
      return item ? item.label : ''
    }
  }
};
</script>
