<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"
    />

    <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.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 { getFieldListByCode, addField, delField } from "@/api/field.js"
// 新增所需字段
const fields = [
  "id",
  "fieldType",
  "label",
  "prop",
  "fieldLength",
  "hisElementIdent",
  "hisDataType",
  "hisRepresentFormat",
  "hisAllowance",
]
// 字段关系映射
const fieldMap = {
  label: "fieldName",
  prop: "fieldCode",
}
export default {
  name: "FieldList",
  props: {
    tableCode: {},
    tableId: {},
    dbId: {},
  },
  components: {
    WidgetConfig,
  },
  data() {
    return {
      propNotEdit: false,
      loading: false,
      widgetVisible: false,
      widgetFormSelect: {},
      listLoading: false,
      // 查询列表
      searchList: [
        {
          label: "字段名",
          type: "input",
          prop: "fieldName",
          placeholder: "请输入字段名",
        },
        {
          label: "属性值",
          type: "input",
          prop: "fieldCode",
          placeholder: "请输入属性值",
        },

        {
          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({ isDefault }) {
                return {
                  disabled: isDefault === 1,
                  label: "编辑",
                  type: "primary",
                }
              },
            },
            {
              func: this.handleDel,
              formatter({ isDefault }) {
                return {
                  disabled: isDefault === 1,
                  label: "删除",
                  type: "warning",
                }
              },
            },
          ],
        },
      ],
      tableData: [],
      cacheForm: {},
    }
  },
  watch: {
    tableCode(val) {
      if (val) {
        this.handleFormSearch()
      } else {
        this.tableData = []
      }
    },
  },

  methods: {
    handleAdd({ id, jsonStr, tableCode }) {
      if (!this.tableCode) {
        this.$message.error("未选择数据表")
        return
      }
      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-zA-Z]+([a-zA-Z0-9]*([_-]?[a-zA-Z0-9]+)*)*$/.test(form.prop)) {
        this.$message.error(
          "只能包含大小字母、数字、下划线。必须以字母开始，下划线不可连续重复，下划线后不可紧跟着数字，不能以数字、下划线结束"
        )
        return
      }
      const data = {
        jsonStr: JSON.stringify(form),
        dbId: this.dbId,
        tableId: this.tableId,
      }
      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) {
      if (!this.tableCode) return
      this.cacheForm = Object.assign(this.cacheForm, form)
      this.listLoading = true
      const params = Object.assign(
        {
          tableCode: this.tableCode,
        },
        this.cacheForm
      )
      for (let key in params) {
        if (params[key] === "") {
          delete params[key]
        }
      }
      getFieldListByCode(params).then((res) => {
        this.listLoading = false
        this.tableData = res.data || []
      })
    },
  },
}
</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>
