<template>
  <div class="card-edit">
    <a-form :model="dataModel" @finish="onFinish" autocomplete="off">
      <a-divider orientation="left">主题定义</a-divider>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item :label-col="{span:6}" label="主题名称" name="subjectName"
                       :rules="[{ required: true, message: '请填写主题名称!' }]">
            <a-input v-model:value="dataModel.subjectName" placeholder="">
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label-col="{span:6}" label="表编码" name="tabCode"
                       :rules="[{ required: true, message: '请填写表编码!' }]">
            <a-input v-model:value="dataModel.tabCode" placeholder="">
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label-col="{span:6}" label="表名称" name="tabName"
                       :rules="[{ required: true, message: '请填表名称!' }]">
            <a-input v-model:value="dataModel.tabName" placeholder="">
            </a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item :label-col="{span:8}" label="是否有外键字段" name="isReferences"
                       :rules="[{ required: true, message: '请填写是否有外键字段!' }]">
            <a-radio-group v-model:value="dataModel.isReferences">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item :label-col="{span:6}" label="描述" name="tabDesc">
            <a-input v-model:value="dataModel.tabDesc" placeholder="">
            </a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider orientation="left">字段定义</a-divider>
      <a-row>
        <a-col :span="24" style="margin-right: 20px;">
          <div style="float: right;">
            <Space>
              <BImportExcel :options="importOptions" @success="onImportSuccess"></BImportExcel>
              &nbsp;
              <a-button @click="add()">
                <template #icon>
                  <plus-circle-outlined/>
                </template>
                新增
              </a-button>
            </Space>
          </div>
        </a-col>
      </a-row>
      <a-row>
        <a-col style="margin-bottom: 20px;">
          <a-table :columns="columns" :data-source="fieldData" :scroll="{ x:'100%', y: 500 }" :pagination="false"
                   bordered>
            <template #bodyCell="{ column ,record,index}">
              <template v-if="column.key === 'operation'">
                <a-button type="link" size="small" @click="edit(record)">修改</a-button>
                <a-popconfirm placement="leftTop"
                              title="是否删除数据?"
                              @confirm="onDelete(index)">
                  <a-button type="link" size="small">删除</a-button>
                </a-popconfirm>
              </template>
            </template>
          </a-table>
        </a-col>
      </a-row>
      <a-divider orientation="left">Sql预览</a-divider>
      <a-row>
        <a-col class="table-bottom-a1">
          <a-form-item :label-col="{span:8}" label="" name="remark">
            <codemirror
              v-model="code"
              :style="{ height: '100px',width:'100%' }"
              :autofocus="true"
              :indent-with-tab="true"
              :lang="lang"
              disabled="false"
              tab-size="2"
              :theme="'oneDark'"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: right;margin: 20px;">
          <Space>
            <a-form-item class="buttom-btns">
              <a-button @click="onClose">取消</a-button>
              <a-button type="primary" html-type="submit">提交</a-button>
            </a-form-item>
          </Space>
        </a-col>
      </a-row>
    </a-form>
    <FieldEdit ref="modalRef" :onSave="onFieldSave"></FieldEdit>
  </div>
</template>

<script lang="ts">
import {defineComponent, reactive, ref, toRefs, watch} from 'vue';
import {useTabsViewStore} from '@/store/modules/tabsView';
import BUploadFile from "@/components/file/uploadFile.vue";
import type {TableColumnsType} from 'ant-design-vue';
import {get, save} from '@/api/common';
import FieldEdit from "@/views/subject/fieldedit.vue";
import {getDictionaryItemList} from "@/api/system/dictionary";
import {Codemirror} from 'vue-codemirror';
import {oneDark} from '@codemirror/theme-one-dark';
import {sql, MySQL} from '@codemirror/lang-sql';
import type {Subjectfield, Subject} from "@/views/subject/model";
import type {ImportProps} from "@/components/basic/excel/importExcel/ImportProps";
import BImportExcel from "@/components/basic/excel/importExcel/importExcel.vue";
import {message} from "ant-design-vue";

interface FormState {
  dataModel: Subject;
}

export default defineComponent({
  name: 'subjectEditForm',
  components: {
    BUploadFile, FieldEdit, Codemirror, MySQL, sql, oneDark, BImportExcel
  },
  setup() {
    const subject: Subject = {
      subjectName: "",
      tabCode: "",
      tabName: "",
      isReferences: 0,
      tabDesc: "",
      execSql: ""
    }
    const formState = reactive<FormState>({dataModel: subject});
    const tabsViewStore = useTabsViewStore();
    const modalRef = ref();
    const fieldData = ref<Subjectfield[]>([]);
    const settingTypeList = ref([{name: '', value: ''}]);
    const queryTypeList = ref([{name: '', value: ''}]);
    const lang = sql();
    const code = ref("");
    let isEdit = false;

    const onFinish = () => {
      if (fieldData.value.length == 0) {
        message.warn("尚未添加任何字段定义。");
        return;
      }
      save('/subject/saveSubject', {dataModel: formState.dataModel, fieldList: fieldData.value}).then(result => {
        if (result) {
          onClose(1)
        }
      });
    };

    const onClose = (reload: any) => {
      tabsViewStore.closeCurrentTabByPath("/views/subjectedit");
      tabsViewStore.openTab("/subject/list", {reload: reload});
    };

    getDictionaryItemList({code: "queryType"}).then(data => {
      queryTypeList.value = data;
    });

    getDictionaryItemList({code: "settingType"}).then(data => {
      settingTypeList.value = data;
    });

    const onFieldSave = async (model: Subjectfield) => {
      if (!isEdit) {
        fieldData.value.push(model);
      }
      formState.dataModel.isReferences = fieldData.value.filter((x) => x.isForeignKey == 1).length > 0 ? 1 : 0;
    }

    const columns: TableColumnsType = [
      {
        title: '序号', width: 80, dataIndex: 'num', key: 'num', align: "center", customRender: ({index}) => {
          return `${index + 1}`;
        }
      },
      {title: '字段编码', dataIndex: 'fieldCode', key: 'fieldCode', align: "center"},
      {title: '字段名称', dataIndex: 'fieldName', key: 'fieldName', align: "center"},
      {
        title: '配置类型', dataIndex: 'settingTypeId', key: 'settingTypeId', align: "center", customRender: ({record}) => {
          return settingTypeList.value.filter(x => x.value == record.settingTypeId)[0]?.name;
        }
      },
      {
        title: '是否查询字段', dataIndex: 'isSearchField', key: 'isSearchField', align: "center", customRender: ({record}) =>
          record.isSearchField == "1" ? "是" : "否"
      },
      {
        title: '查询类型', dataIndex: 'queryTypeId', key: 'queryTypeId', align: "center", customRender: ({record}) =>
          queryTypeList.value.filter(x => x.value == record.queryTypeId)[0]?.name
      },
      {title: '取数字典编码', dataIndex: 'dictionaryCode', key: 'dictionaryCode', align: "center"},
      {title: '显示排序', dataIndex: 'disOrder', key: 'disOrder', align: "center"},
      {
        title: '是否关联字段', dataIndex: 'isForeignKey', key: 'isForeignKey', align: "center", customRender: ({record}) =>
          record.isForeignKey == "1" ? "是" : "否"
      },
      {title: '显示别名', dataIndex: 'fieldAlias', key: 'fieldAlias', align: "center"},
      {title: '外键表', dataIndex: 'referencesTab', key: 'referencesTab', align: "center"},
      {title: '外键列', dataIndex: 'foreignKey', key: 'foreignKey', align: "center"},
      {title: '外键表显示列', dataIndex: 'displayColumn', key: 'displayColumn', align: "center"},
      {title: '操作', key: 'operation', fixed: 'right', width: 120, align: "center"},
    ];
    const importOptions = ref<ImportProps>({
      title: "导入",
      url: 'subject/importData',
      columns: [
        {cnName: "字段编码", enName: "fieldCode", width: 100},
        {cnName: "字段名称", enName: "fieldName", width: 200},
        {cnName: "配置类型", enName: "settingTypeName", width: 200},
        {cnName: "字段描述", enName: "fieldDesc", width: 100},
        {cnName: "数据类型", enName: "dataType", width: 150},
        {cnName: "查询类型", enName: "queryTypeName", width: 100},
        {cnName: "取数字典编码", enName: "dictionaryCode", width: 200},
        {cnName: "显示排序", enName: "disOrder", width: 200},
        {cnName: "是否查询字段", enName: "isSearchFieldText", width: 200},
        {cnName: "是否关联字段", enName: "isForeignKeyText", width: 100},
        {cnName: "外键表", enName: "referencesTab", width: 150},
        {cnName: "外键列", enName: "foreignKey", width: 150},
        {cnName: "外键表显示列", enName: "displayColumn", width: 150},
        {cnName: "显示别名", enName: "fieldAlias", width: 200},
      ],
      template: {
        tempFileName: "主题字段导入模板.xlsx",
        url: '',
        params: null
      }
    });
    const onImportSuccess = (data: []) => {
      fieldData.value = fieldData.value.concat(data);
      formState.dataModel.isReferences = fieldData.value.filter((x) => x.isForeignKey == 1).length > 0 ? 1 : 0;
    }

    const data = ref([]);

    const add = () => {
      isEdit = false;
      modalRef.value.show(null);
    }
    const edit = (record) => {
      isEdit = true;
      modalRef.value.show(record);
    }
    const onDelete = (record) => {
      fieldData.value.splice(record, 1);
    }
    const loadData = (id) => {
      if (id != undefined) {
        get('subject/getSubject',
          {subjectId: id}).then(data => {
          formState.dataModel = data;
        })
        get('subject/getFieldList',
          {subjectId: id}).then(data => {
          fieldData.value = data;
        })
      }
    }
    watch(
      () => [formState.dataModel.tabCode, fieldData],
      () => {
        code.value = ` select ${formState.dataModel.tabCode}.*`;
        fieldData.value.filter(x => x.isForeignKey == 1).forEach(x => {
          code.value += `,${x.referencesTab}.${x.displayColumn} as ${x.fieldAlias}`
        })
        code.value += ` from ${formState.dataModel.tabCode}`;
        fieldData.value.filter(x => x.isForeignKey == 1).forEach(x => {
          code.value += ` left join ${x.referencesTab} on ${formState.dataModel.tabCode}.${x.fieldCode}=${x.referencesTab}.${x.foreignKey}`
        })
      }, {deep: true}
    );
    return {
      ...toRefs(formState),
      onFinish, onFieldSave, onClose, add, onImportSuccess,
      edit, importOptions,
      onDelete,
      loadData, oneDark,
      fieldData, columns,
      isEdit, data, lang, code, modalRef,
    };
  },
  created() {
    const id = history.state.params?.id;
    this.loadData(id);
  }
})
</script>
