<template>
  <div class="model-design">
    <a-form-model
      layout="horizontal"
      v-bind="{
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
      }"
      ref="baseForm"
      :model="model"
    >
      <a-row>
        <a-col :span="8">
          <a-form-model-item :label="$t('源库')">
            <a-input-group compact>
              <source-selection v-model="dataSource" style="width: 50%" />
              <table-selection
                :option="dataSource"
                v-model="dataSource.tableCode"
                @change="changeTable"
                style="width: 50%"
              />
            </a-input-group>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item :label="$t('模型中文名')" prop="tableName">
            <a-input
              :placeholder="$t('请输入模型中文名')"
              v-model="model.tableName"
              allow-clear
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item :label="$t('模型英文名')" prop="tableCode">
            <a-input
              v-model.lazy="model.tableCode"
              :placeholder="$t('请输入模型英文名')"
              :disabled="!!modelId"
              allow-clear
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item :label="$t('模型编码')" prop="tableSno">
            <a-input
              :placeholder="$t('请输入模型编码')"
              v-model="model.tableSno"
              allow-clear
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item :label="$t('关联指标')" prop="indicatorCode">
            <vxe-tree-select
              v-model="model.indicatorCode"
              :placeholder="$t('请选择关联指标')"
              clearable
              :tree-config="{
                transform: true,
                keyField: 'id',
                parentField: 'pid',
                trigger: 'node',
                radioConfig: {
                  checkMethod({ node }) {
                    return !node.children || !node.children.length;
                  },
                },
              }"
              :options="indicatorOptions"
              :option-props="{ label: 'name', value: 'code' }"
              @change="handleIndicatorChange"
            ></vxe-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item :label="$t('目标库')">
            <a-input-group compact>
              <source-selection v-model="targetDataSource" />
            </a-input-group>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-card size="small" :title="$t('模型字段')" :bordered="false">
      <template #extra>
        <!-- <a-button
            type="link"
            @click="batchSelectionDataElement"
            >{{ $t('引用数据表') }}</a-button
          > -->
        <a-button type="link" @click="addField">{{ $t("添加字段") }}</a-button>
      </template>
      <div class="table_list">
        <vxe-table
          show-overflow
          show-header-overflow
          border
          resizable
          :loading="loading"
          :row-config="{ isHover: true, keyField: '_X_ROW_KEY' }"
          :data="fields"
          height="auto"
          ref="field_table"
          :keep-source="true"
          :edit-config="{
            trigger: 'click',
            mode: 'cell',
            showIcon: false,
            showStatus: true,
          }"
          :scroll-y="{ enabled: true, gt: 10 }"
        >
          <vxe-column
            type="seq"
            :title="$t('序号')"
            width="50"
            align="center"
            fixed="left"
          />
          <vxe-column
            field="columnCode"
            :title="$t('英文名')"
            :edit-render="{}"
            sortable
            minWidth="160px"
            fixed="left"
          >
            <template #edit="{ row }">
              <a-input
                :placeholder="$t('请输入英文名')"
                v-model.lazy="row.columnCode"
                @change="keyCode(row.columnCode)"
              />
            </template>
          </vxe-column>
          <vxe-column
            field="columnName"
            :title="$t('中文名')"
            :edit-render="{}"
            minWidth="160px"
            sortable
            fixed="left"
          >
            <template #edit="{ row }">
              <a-input :placeholder="$t('请输入中文名')" v-model.lazy="row.columnName" />
            </template>
          </vxe-column>
          <!-- <vxe-column
              field="description"
              :title="$t('说明')"
              :edit-render="{}"
              minWidth="160px"
            >
              <template #edit="{ row }">
                <a-input
                  :placeholder="$t('请输入说明')"
                  v-model.lazy="row.description"
                />
              </template>
            </vxe-column> -->
          <!-- <vxe-column
              field="sortNumber"
              :title="$t('顺序')"
              minWidth="120px"
              :edit-render="{}"
              sortable
            >
              <template #edit="{ row }">
                <a-input-number
                  :placeholder="$t('顺序')"
                  :min="0"
                  v-model.lazy="row.sortNumber"
                />
              </template>
            </vxe-column> -->
          <vxe-column
            field="columnType"
            :title="$t('类型')"
            minWidth="160px"
            :edit-render="{}"
          >
            <template #default="{ row }">{{ row.columnType }}</template>
            <template #edit="{ row }">
              <a-select
                v-model="row.columnType"
                :placeholder="$t('类型')"
                @change="changeColumnType(row)"
              >
                <a-select-option
                  :value="item.value"
                  v-for="(item, i) in databaseOptions"
                  :key="i"
                  >{{ item.value }}</a-select-option
                >
              </a-select>
            </template>
          </vxe-column>
          <vxe-column
            field="columnSize"
            :title="$t('长度')"
            minWidth="120px"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <a-input-number
                :placeholder="$t('长度')"
                :min="0"
                v-model.lazy="row.columnSize"
              />
            </template>
          </vxe-column>
          <vxe-column
            field="columnAccuracy"
            :title="$t('精度')"
            minWidth="120px"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <a-input-number
                :placeholder="$t('精度')"
                :min="0"
                v-model.lazy="row.columnAccuracy"
              />
            </template>
          </vxe-column>
          <vxe-column
            field="defaultValue"
            :title="$t('默认值')"
            :edit-render="{}"
            minWidth="160px"
          >
            <template #edit="{ row }">
              <a-input
                :placeholder="$t('请输入默认值')"
                v-model.lazy="row.defaultValue"
              />
            </template>
          </vxe-column>

          <vxe-column
            field="isNull"
            :title="$t('是否必填')"
            minWidth="100px"
            :edit-render="{}"
            align="center"
          >
            <template #default="{ row }">
              {{ row.isNull ? $t("是") : $t("否") }}
            </template>
            <template #edit="{ row }">
              <a-checkbox v-model="row.isNull">{{ $t("是") }}</a-checkbox>
            </template>
          </vxe-column>
          <vxe-column
            field="pk"
            :title="$t('物理主键')"
            minWidth="100px"
            :edit-render="{}"
            align="center"
          >
            <template #default="{ row }">
              <span v-if="row.pk">
                <win-icon class="icon_primary_key" type="icon_primary_key" />{{
                  $t("主键")
                }}</span
              >
              <span v-else>-</span>
            </template>
            <template #edit="{ row }">
              <a-checkbox v-model="row.pk">{{ $t("主键") }}</a-checkbox>
            </template>
          </vxe-column>
          <!-- <vxe-column
              field="autoincrement"
              :title="$t('自增')"
              minWidth="100px"
              align="center"
              :edit-render="{}"
            >
              <template #default="{ row }">
                <span v-if="row.autoincrement">{{ $t('自增') }}</span>
                <span v-else>-</span>
              </template>
              <template #edit="{ row }">
                <a-checkbox v-model="row.autoincrement">{{ $t('自增') }}</a-checkbox>
              </template>
            </vxe-column> -->
          <vxe-column
            field="title"
            :title="$t('操作')"
            width="90"
            align="center"
            fixed="right"
          >
            <template #default="{ row }">
              <a-button type="link" class="a_danger" @click="deleteRow(row)">{{
                $t("删除")
              }}</a-button>
            </template>
          </vxe-column>
          <template #empty>
            <a-empty
              :image-style="{
                height: '80px',
              }"
            >
              <span slot="description">{{ $t("暂无数据") }}</span>
            </a-empty>
          </template>
        </vxe-table>
      </div>
    </a-card>
    <data-element
      v-model="referenceData.show"
      :radio="referenceData.radio"
      @change="batchSetDataElement"
    />
  </div>
</template>
<script>
const $metaService = require("w-vue-chongqing/src/api/metadata");
const $modelService = require("w-vue-chongqing/src/api/dataModel");
const $userService = require("w-vue-chongqing/src/api/userService");
const dataElement = require("./components/dataElement").default;
const { sourceSelection, tableSelection } = require("w-vue-middle/dataSourceService");
const oriModel = {
  id: undefined,
  datasourceId: undefined, // 目标数据源id
  schemaName: undefined, // 目标数据源schema
  indicatorCode: undefined, // 指标code
  indicatorName: undefined, // 指标name
  tableId: undefined, // 表id
  tableCode: undefined, // 表code
  tableName: undefined, // 表name
  tableSno: undefined, // 表编码
  sourceDatasourceId: undefined, // 来源数据源id
  sourceSchemaName: undefined, // 来源数据源schema
};
const oriDataSource = {
  clusterId: undefined,
  dbId: undefined, //数据源ID
  dbSchema: undefined, //SchemaName
  tableCode: undefined, // 数据表code
  columnName: undefined, // 列名称
};
export default {
  name: "modelDesign",
  components: {
    dataElement,
    sourceSelection,
    tableSelection,
  },
  props: {
    modelId: {
      //表ID
      type: [String, Number],
    },
  },
  data() {
    return {
      referenceData: {
        show: false,
        radio: false,
      },
      indicatorOptions: [], // 指标列表
      databaseOptions: [], // 数据库字段类型
      dataSource: oriDataSource,
      targetDataSource: oriDataSource,
      model: oriModel,
      loading: false,
      fields: [],
    };
  },
  created() {
    this.getDataBase();
    this.getIndicatorData();
    this.getList();
  },
  methods: {
    // 获取字段列表
    keyCode(value) {
      let keyValue = "";
      let val = value;
      for (let i = 0; i < val.length; i++) {
        if (val.charCodeAt(i) > 0 && val.charCodeAt(i) < 255) {
          keyValue += val[i];
        }
      }
      value = keyValue;
    },
    // 批量选择数据元素
    batchSelectionDataElement() {
      this.referenceData.show = true;
      this.referenceData.radio = false;
    },
    // 批量设置数据元素
    batchSetDataElement(dataElements) {
      this.fields = this.fields.concat(
        dataElements.map((item, i) => {
          return {
            name: item.name,
            autoincrement: false,
            description: item.description,
            code: item.code, // 关联字段
            columnType: item.columnType === "date" ? item.dataType : item.columnType,
            columnSize: item.dataType === "D" || item.dataType === "DT" ? "" : 64,
            notNull: false,
            pk: false,
            sortNumber: this.fields.length + i + 1,
            columnAccuracy:
              item.dataType === "D" || item.dataType === "DT" ? "" : item.columnAccuracy,
            valueDomainCode: undefined,
            rule: undefined,
            defaultValue: undefined,
            dataElementCode: item.uid,
            tableName: undefined,
            defineCode: undefined,
          };
        })
      );
    },
    // 新增字段
    addField() {
      const field = {
        columnCode: undefined,
        columnSize: 64,
        columnType: "varchar",
        defaultValue: "",
        columnName: undefined,
        isNull: false,
        pk: false,
        columnAccuracy: undefined,
      };
      this.fields.push(field);
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.field_table.scrollToRow(field);
        }, 0);
      });
    },
    // 删除字段
    deleteRow(row) {
      this.fields = this.fields.filter((item) => {
        return row._X_ROW_KEY != item._X_ROW_KEY;
      });
    },
    // 选择表
    changeTable(val) {
      // 模型编码和表英文默认一致
      this.model.tableCode = this.model.tableSno = val;
      this.loading = true;
      const { clusterId, dbId, dbSchema, tableCode } = this.dataSource;
      $userService
        .collectionDataInfo({
          clusterId,
          collectType: "column", // 采集类型：schema、table、column
          dsId: dbId,
          schema: dbSchema,
          tableName: tableCode,
        })
        .then(({ data }) => {
          this.fields = data.map((item) => {
            return {
              columnCode: item.columnName,
              columnName: item.description,
              columnType: item.columnType,
              columnSize: item.columnSize,
              columnAccuracy: item.columnAccuracy,
              defaultValue: "",
              isNull: item.notNull,
              pk: item.pk,
              id: undefined,
            };
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 保存字段
    saveModel(callback) {
      $modelService
        .saveSelectedMetadata({
          ...this.model,
          sourceDatasourceId: this.dataSource.dbId,
          sourceSchemaName: this.dataSource.dbSchema,
          datasourceId: this.targetDataSource.dbId,
          schemaName: this.targetDataSource.dbSchema,
          columnList: this.fields,
        })
        .then(() => {
          this.drawerVisible = false;
          this.$message.success($t("保存成功"));
        })
        .finally(() => {
          callback && callback();
        });
    },
    // 获取数据库类型
    async getDataBase() {
      this.databaseOptions = [];
      const { data } = await $modelService.getDataBaseDataType();
      this.databaseOptions = data || [];
    },
    // 获取关联指标
    async getIndicatorData() {
      this.indicatorOptions = [];
      const { data } = await $metaService.queryAllQuotaData({ keyWords: "" });
      this.indicatorOptions = data || [];
    },
    // 选择关联指标
    handleIndicatorChange({ option }) {
      this.model.indicatorName = option?.name;
    },
    // 重置初始状态
    resetState() {
      this.model = { ...oriModel };
      this.dataSource = { ...oriDataSource };
      this.targetDataSource = { ...oriDataSource };
      this.fields = [];
    },
    // 创建数据源配置
    createDataSourceConfig(type) {
      return {
        dbId: this.model[type === "source" ? "sourceDatasourceId" : "datasourceId"],
        dbSchema: this.model[type === "source" ? "sourceSchemaName" : "schemaName"],
        tableCode: this.model.tableCode,
      };
    },
    // 获取字段列表
    getList() {
      this.resetState();
      if (!this.modelId) {
        return;
      }
      this.loading = true;
      $modelService
        .getIndicatorTableDataById({ id: this.modelId })
        .then(({ data }) => {
          const { columnList, ...rest } = data;
          this.fields = columnList || [];
          this.model = rest;
          this.model = {
            ...rest,
            id: this.modelId, // 编辑
          };
          this.dataSource = this.createDataSourceConfig("source");
          this.targetDataSource = this.createDataSourceConfig("target");
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style lang="less" scoped>
.model-design {
  padding: 12px 0;
  background-color: #fff;
  /deep/.collect_info_container {
    top: -1px;
  }
  /deep/ .vxe-tree-select {
    width: 100%;
  }
}
.table_list {
  height: calc(100vh - 240px);
}
</style>
