<template>
  <div class="container">
    <direct-search
      ref="form"
      :label-position="'right'"
      :forms="searchList"
      :style="{ textAlign: 'left' }"
      @handleSearch="handleFormSearch"
    />
    <el-table-self
      ref="table"
      :table-data="tableData"
      :columns="columns"
      :list-loading="listLoading"
      :current-page="pageIndex"
      :total-count="total"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      @pageSizeChange="handleSizeChange"
      @currentPageChange="handleCurrentChange"
    />

    <el-drawer
      :title="widgetFormSelect.id ? '编辑' : '新增'"
      :visible.sync="widgetVisible"
      :size="500"
      :wrapperClosable="false"
    >
      <div class="drawer__container">
        <div class="drawer__content">
          <widget-config
            :data="widgetFormSelect"
            :propNotEdit="propNotEdit"
            layout-hidden
          >
            <template v-slot:dbtable>
              <el-collapse-item
                name="4"
                title="数据库属性与命名标准"
                v-if="!['group', 'title'].includes(widgetFormSelect.type)"
              >
                <el-form-item label="数据库表">
                  <el-select
                    v-model="widgetFormSelect.tableCode"
                    placeholder="数据库表"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in dictMap['table']"
                      :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="数据类型">
                  <el-select
                    v-model="widgetFormSelect.fieldType"
                    placeholder="字段存储类型"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in dictMap['data_type']"
                      :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="数据宽度">
                  <el-input
                    style="width: 100%"
                    v-model="widgetFormSelect.fieldLength"
                    :controls="false"
                    clearable
                    placeholder="数据宽度"
                  ></el-input>
                </el-form-item>
                <el-form-item label="数据元标识">
                  <el-input
                    v-model="widgetFormSelect.hisElementIdent"
                    clearable
                    placeholder="数据元标识"
                  ></el-input>
                </el-form-item>
                <el-form-item label="数据元值类型">
                  <el-input
                    v-model="widgetFormSelect.hisDataType"
                    clearable
                    placeholder="数据元值类型"
                  ></el-input>
                </el-form-item>
                <el-form-item label="表达格式">
                  <el-input
                    v-model="widgetFormSelect.hisRepresentFormat"
                    clearable
                    placeholder="表达格式"
                  ></el-input>
                </el-form-item>
                <el-form-item label="允许值">
                  <el-input
                    v-model="widgetFormSelect.hisAllowance"
                    clearable
                    placeholder="允许值"
                  ></el-input>
                </el-form-item>
              </el-collapse-item>
            </template>
          </widget-config>
        </div>

        <div class="footer">
          <el-button @click="widgetVisible = false" size="large"
            >取 消</el-button
          >
          <el-button
            size="large"
            type="primary"
            :loading="loading"
            @click="handleConfirm(widgetFormSelect)"
            >确 定</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import WidgetConfig from "packages/WidgetConfig.vue"
import paginationMixin from "@/components/TabComponents/mixin"
import { getFieldPage, addField, delField } from "@/api/field.js"
// 新增所需字段
const fields = [
  "id",
  "fieldType",
  "label",
  "prop",
  "tableCode",
  "tableName",
  "fieldLength",
  "hisElementIdent",
  "hisDataType",
  "hisRepresentFormat",
  "hisAllowance",
]
// 字段关系映射
const fieldMap = {
  label: "fieldName",
  prop: "fieldCode",
}
export default {
  name: "FieldConfig",
  components: {
    WidgetConfig,
  },
  mixins: [paginationMixin],
  data() {
    return {
      propNotEdit: false,
      loading: false,
      widgetVisible: false,
      widgetFormSelect: {},
      listLoading: false,
      // 查询列表
      searchList: [
        {
          label: "字段名",
          type: "input",
          prop: "fieldName",
          placeholder: "请输入字段名",
        },

        {
          label: "数据库存储表",
          type: "select",
          prop: "tableCode",
          optsFormatter: () => {
            return this.dictMap && this.dictMap["table"]
          },
        },
        {
          type: "button",
          value: "查询",
          icon: "el-icon-search",
        },
        {
          type: "button",
          color: "primary",
          icon: "el-icon-plus",
          hasForm: true,
          value: "添加",
          func: this.handleAdd,
        },
      ],
      columns: [
        {
          label: "字段名",
          minWidth: 120,
          value: "fieldName",
        },
        {
          label: "属性值",
          minWidth: 120,
          value: "fieldCode",
        },
        {
          label: "数据库存储表名称",
          minWidth: 120,
          value: "tableName",
        },
        {
          label: "数据库存字段类型",
          minWidth: 120,
          value: "fieldType",
          formatter: (row) => {
            return this.$handle.formatDicList(
              this.dictMap["data_type"],
              row.fieldType
            )
          },
        },
        {
          label: "数据宽度",
          minWidth: 100,
          value: "fieldLength",
        },
        {
          label: "操作",
          width: 200,
          fixed: "right",
          operType: "button",
          operations: [
            {
              func: this.handleAdd,
              formatter(row) {
                return {
                  label: "编辑",
                  type: "primary",
                }
              },
            },
            {
              func: this.handleDel,
              formatter(row) {
                return {
                  label: "删除",
                  type: "warning",
                }
              },
            },
          ],
        },
      ],
      tableData: [],
      cacheForm: {},
    }
  },

  methods: {
    handleAdd({ id, jsonStr, tableCode }) {
      const fields = jsonStr ? JSON.parse(jsonStr) : {}
      const form = id ? { id, ...fields } : { tableCode, importantField: true }
      this.propNotEdit = Boolean(id)
      this.widgetFormSelect = Object.assign(
        { type: "input", display: true },
        form
      )
      this.widgetVisible = true
    },
    handleConfirm(form) {
      if (!/^[a-z]+([a-z0-9]*([_]?[a-z]+)*)*$/.test(form.prop)) {
        this.$message.error(
          "只能包含字母、数字、下划线。必须以字母开始，下划线不可连续重复，下划线后不可紧跟着数字，不能以数字、下划线结束"
        )
        return
      }
      form.tableName = this.$handle.formatDicList(
        this.dictMap["table"],
        form.tableCode
      )

      const data = { jsonStr: JSON.stringify(form) }
      Object.keys(form).forEach((key) => {
        if (fields.includes(key)) {
          if (fieldMap[key]) {
            data[fieldMap[key]] = form[key]
          } else {
            data[key] = form[key]
          }
        }
      })
      const msg = data.id ? "编辑成功" : "新增成功"
      this.loading = true
      addField(data)
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(msg)
            this.handleSearch()
            // this.widgetVisible = false
            this.loading = false
          }
        })
        .catch((e) => {
          this.loading = false
        })
    },
    handleDel(row) {
      this.$confirm(`是否删除【${row.fieldName}】?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delField(row.id).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              })
              this.handleSearch()
            }
          })
        })
        .catch(() => {})
    },

    // 查询
    handleFormSearch(form) {
      this.pageIndex = 1
      this.handleSearch(form)
    },
    handleSearch(form) {
      this.cacheForm = Object.assign(this.cacheForm, form)
      this.listLoading = true
      const params = Object.assign({}, this.cacheForm)
      for (let key in params) {
        if (params[key] === "") {
          delete params[key]
        }
      }
      params.current = this.pageIndex
      params.size = this.pageSize
      getFieldPage(params).then((res) => {
        this.listLoading = false
        if (res.code === 1) {
          const d = res.data
          this.tableData = d.records || []
          this.total = Number(d.total)
        }
      })
    },
  },
  created() {
    this.handleFormSearch()
  },
}
</script>

<style lang="scss" scoped>
.drawer__container {
  padding: 0 20px;
  .drawer__content {
    height: calc(100vh - #{"160px"});
    overflow-y: auto;

    ::v-deep .el-input-number {
      width: 100%;
    }
    &::-webkit-scrollbar {
      width: 0px;
      height: 0px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #fff;
    }
  }
  .footer {
    margin-top: 20px;
    display: flex;
    button {
      flex: 1;
    }
  }
}
</style>
