<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="type">
            <el-select v-model="queryParams.type" clearable filterable>
              <el-option v-for="item in dict.type.sap_property_type" :key="item.value" v-bind="item"/>
            </el-select>
          </el-form-item>
        </el-col>
        <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="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:sapproperty: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:sapproperty: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:sapproperty: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:sapproperty:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="toDataType"
          v-hasPermi="['md:sapproperty:dataType']"
        >数据类型</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="特性类型" prop="type" :formatter="formatType"/>
      <el-table-column label="sap属性" prop="sapField"/>
      <el-table-column label="数据类型名" prop="propertyType.name" />
      <el-table-column label="数据类型" prop="propertyType.type" :formatter="formatDataType"/>
      <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:sapproperty:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-hasPermi="['md:sapproperty: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">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="特性类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择特性类型" @change="onChangeType" clearable filterable>
                <el-option v-for="item in dict.type.sap_property_type" :key="item.value" v-bind="item"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="视图类型" prop="viewType">
              <el-select v-model="form.viewType" placeholder="请选择视图类型" clearable filterable>
                <el-option v-for="item in viewTypes" :key="item.value" v-bind="item"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="特性名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入特性名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据类型" prop="typeId">
              <el-select v-model="form.typeId" placeholder="请选择数据类型" clearable filterable remote :remote-method="onSearchType">
                <el-option class="data-type" v-for="item in typeList" :key="item.id" :value="item.id" :label="item.name">
                  <div style="float: left;font-size: 14px; line-height: 40px">{{ item.name }}</div>
                  <div v-if="['4','5','6'].includes(item.type)" style="float: right; color: #8492a6;width: 50%;line-height: 40px">
                    {{ dict.type.sys_data_type.find(type => type.value === item.type).label }}
                  </div>
                  <div v-else style="float: right; color: #8492a6;width: 50%">
                    <div style="overflow: hidden">{{ dict.type.sys_data_type.find(type => type.value === item.type).label }}</div>
                    <div style="overflow: hidden">{{ buildDataType(item) }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="sap属性" prop="sapField">
              <el-input v-model.trim="form.sapField" placeholder="请输入sap属性" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联属性" prop="relationField">
              <el-input v-model.trim="form.relationField" placeholder="请选择关联客户属性" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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 {
  addSapproperty,
  delSapproperty,
  getSapproperty,
  listSapproperty,
  updateSapproperty
} from '@/api/mes/md/sapproperty'
import { listPropertytype } from '@/api/mes/md/propertytype'

export default {
  name: "Client",
  dicts: ['mes_client_type','sys_yes_no','sys_data_type','sap_property_type', 'sap_property_view', 'sap_property_relation'],
  data() {
    return {
      //自动生成编码
      autoGenFlag:false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        name: null,
        enableFlag: 'Y',
      },
      typeList: [],
      // 表单参数
      form: {
        id: null,
        type: null,
        viewType: '1',
        name: null,
        typeId: null,
        sapField: null,
        relationField: null,
        money: 1,
        enableFlag: 'Y',
      },
      viewTypes: [],
      // 表单校验
      rules: {
        type: [{ required: true, message: '特性类型不能为空', trigger: ['blur', 'change']}],
        viewType: [{ required: true, message: '视图类型不能为空', trigger: ['blur', 'change']}],
        name: [{ required: true, max: 32, message: '特性名称不能为空，长度在32字符以内', trigger: ['blur', 'change'] }],
        typeId: [{ required: true, message: '数据类型不能为空', trigger: ['blur', 'change']}],
        sapField: [
          { required: true, max: 32, message: 'SAP属性不能为空，长度在32字符以内', trigger: 'blur' },
          { pattern: /^[a-zA-Z]\w{1,31}$/, message: '仅支持字母下划线数字,并以字母开头', trigger: ['blur', 'change'] }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    onChangeType(val) {
      this.viewTypes = this.dict.type.sap_property_view.filter(item => item.value === val).map(item => ({label: item.label, value: item.raw.cssClass}))
    },
    toDataType() {
      this.$router.push({ path: '/mes/md/propertytype'})
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listSapproperty(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
      }).finally(() => this.loading = false);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        name: null,
        typeId: null,
        sapField: null,
        enableFlag: 'Y',
      };
      this.autoGenFlag = false;
      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";
      listPropertytype({name: '', pageNum: 1, pageSize: 100}).then(response => this.typeList = response.rows)
    },
    onSearchType(key) {
      listPropertytype({name: key, pageNum: 1, pageSize: 1000}).then(response => this.typeList = response.rows)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      listPropertytype({id: row.typeId, pageNum: 1, pageSize: 1000}).then(response => this.typeList = response.rows)
      getSapproperty(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改特性";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSapproperty(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSapproperty(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + id + '"的数据项？').then(function() {
        return delSapproperty(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('md/sapproperty/export', {
        ...this.queryParams
      }, `sapProperty_${new Date().getTime()}.xlsx`)
    },
    formatType(row) {
      let item = this.dict.type.sap_property_type.find(item => item.value === row.type)
      return item ? item.label : ''
    },
    formatDataType(row) {
      let item = this.dict.type.sys_data_type.find(item => item.value === row.propertyType.type)
      return item ? item.label : ''
    },

    buildDataType(item) {
      let datatype = ''
      if (item.length != null) datatype += `最大长度：${item.length}；`
      if (item.min != null) datatype += `最小值：${item.min}；`
      if (item.max != null) datatype += `最大值：${item.max}；`
      if (item.regEx != null) datatype += `正则：${item.regEx}；`
      if (item.dictId != null) datatype += `枚举：${item.propertyDict.name}；`
      return datatype
    }
  }
};
</script>

<style>
body .el-select-dropdown__item.data-type {
  height: 40px !important;
  line-height: 20px !important;
  font-size: 12px !important;
}
</style>
