<template>
  <a-modal :open="open" title="字段管理" style="top: 30px" :footer="null">
    <div class="field-manager">
      <div class="header-box">
        <a-space>
          <a-input
            v-model:value="fieldName"
            placeholder="请输入字段名称"
            allow-clear
            style="width: 200px"
            @change="search"
          />
          <a-button type="primary" @click="addField">新建</a-button>
        </a-space>
      </div>
      <a-table
        :columns="viewCfgCols"
        :data-source="dataList"
        :pagination="false"
        size="small"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template
            v-if="
              [
                'field_name',
                'field_title',
                'belong_to_table',
                'original_sql',
              ].includes(column.dataIndex)
            "
          >
            <a-input
              v-if="editableData[record.field_id]"
              v-model:value="record[column.dataIndex]"
              allow-clear
              placeholder="请输入"
            />
            <template v-else>
              {{ record[column.dataIndex] }}
            </template>
          </template>
          <template v-if="column.dataIndex === 'field_numerical_name'">
            <a-select 
              v-if="editableData[record.field_id]" 
              v-model:value="record.field_numerical_type_id" 
              :options="fieldNumTypeSel" 
              placeholder="请选择"
              allow-clear
              style="width: 120px">
            </a-select>
            <template v-else>
              {{ record.field_numerical_name }}
            </template>
          </template>
          <template v-if="column.dataIndex === 'field_type_name'">
            <a-select
              v-if="editableData[record.field_id]"
              v-model:value="record.field_type_id"
              :options="fieldTypeSel"
              placeholder="请选择"
              allow-clear
              style="width: 120px"
            >
            </a-select>
            <template v-else>
              {{ record.field_type_name }}
            </template>
          </template>
          <template v-if="column.dataIndex === 'is_search'">
            <a-switch
              v-if="editableData[record.field_id]"
              v-model:checked="record.is_search"
              :checkedValue="1"
              :unCheckedValue="0"
            />
            <template v-else>
              {{ record.is_search ? "是" : "否" }}
            </template>
          </template>
          <template v-if="column.dataIndex === 'is_other_database'">
            <template v-if="editableData[record.field_id]">
              <a-switch
                v-model:checked="record.is_other_database"
                :checkedValue="1"
                :unCheckedValue="0" 
              />
              <a-button v-if="record.is_other_database" type="link" @click="openSpecialModal(record)">请填写</a-button>
            </template>
            <template v-else>
              {{ record.is_other_database ? "是" : "否" }}
            </template>
          </template>
          <template v-if="column.dataIndex === 'original_type'">
            <a-select 
              v-if="editableData[record.field_id]"
              placeholder="请选择" 
              v-model:value="record.original_type"
              :options="originalTypes"
              allow-clear
            >
            </a-select>
            <template v-else>
              {{ record.original_type_name }}
            </template>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space v-if="editableData[record.field_id]">
              <a-button type="primary" size="small" @click="handleSave(record)"
              >保存</a-button
              >
              <a-button size="small" @click="handleCancel(record)"
              >取消</a-button
              >
            </a-space>
            <a-button v-else type="link" @click="handleEdit(record)"
            >修改</a-button
            >
          </template>
        </template>
      </a-table>
      <a-pagination
        :current="pageState.page"
        :page-size="pageState.perPage"
        :total="pageState.total"
        class="pagination-box"
        size="small"
        @change="pageChange"
      />
    </div>
    <a-modal :open="specialVisible" :width="640" title="数据库特配" :bodyStyle="{ marginTop: '30px' }" @ok="specialVisible = false" @cancel="specialVisible = false">
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="数据库驱动">
          <a-radio-group v-model:value="specialModalData[specialModalId].drive_type">
            <a-radio :value="1">MySQL</a-radio>
            <a-radio :value="2">Click House</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="数据库地址">
          <a-input placeholder="请输入数据库地址" v-model:value="specialModalData[specialModalId].database_address" allow-clear />
        </a-form-item>
        <a-form-item label="数据库端口">
          <a-input-number placeholder="请输入数据库端口" style="width: 200px" v-model:value="specialModalData[specialModalId].database_port" allow-clear />
        </a-form-item>
        <a-form-item label="数据库名称">
          <a-input placeholder="请输入数据库名称" v-model:value="specialModalData[specialModalId].database_name" allow-clear />
        </a-form-item>
        <a-form-item label="数据库用户">
          <a-input placeholder="请输入数据库用户" v-model:value="specialModalData[specialModalId].database_username" allow-clear />
        </a-form-item>
        <a-form-item label="数据库密码">
          <a-input-password placeholder="请输入数据库密码" v-model:value="specialModalData[specialModalId].database_password" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import { viewCfgCols, originalTypes } from "@/views/config-manage/module-cfg/config";
import {
  getFieldTypeSelect,
  getFieldNumSelect,
  getFieldList,
  // deleteField,
  saveField,
  // getFieldDetail,
} from "@/views/config-manage/module-cfg/service";
import { message } from "ant-design-vue";

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  modularId: {
    type: Number,
    default: 0,
  },
});
const listLoading = ref(false);
const fieldName = ref("");
const dataList = ref([]);
const fieldTypeSel = ref([]);
const fieldNumTypeSel = ref([]);
const specialVisible = ref(false);
const specialModalId = ref();
const pageState = reactive({
  page: 1,
  perPage: 20,
  total: 0,
});
const editableData = reactive({});
const specialModalData = reactive({
  drive_type: undefined,
  database_address: undefined,
  database_port: undefined,
  database_name: undefined,
  database_username: undefined,
  database_password: undefined,
});

watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      toGetList();
    }
  },
);

onMounted(() => {
  toGetFieldTypes();
  toGetFieldNumSelect();
});

// 字段搜索类型下拉
const toGetFieldTypes = () => {
  getFieldTypeSelect().then((res) => {
    fieldTypeSel.value = res.data;
  });
};

// 字段类型下拉
const toGetFieldNumSelect = () => {
  getFieldNumSelect().then((res) => {
    fieldNumTypeSel.value = res.data;
  })
};

// 字段列表
const toGetList = () => {
  listLoading.value = true;
  getFieldList({
    fieldName: fieldName.value,
    modularId: props.modularId,
    page: pageState.page,
    perPage: pageState.perPage,
  }).then((res) => {
    dataList.value = res.data.list;
    pageState.total = res.data.total;
  });
};

const pageChange = () => {
  toGetList();
};

const search = () => {
  pageState.page = 1;
  toGetList();
};

const addField = () => {
  const item = {
    field_id: new Date().getTime() + "",
    field_title: undefined,
    field_name: undefined,
    field_numerical_type_id: undefined,
    is_search: 0,
    field_type_id: undefined,
    belong_to_table: undefined,
    is_other_database: 0,
    original_type: undefined,
    original_sql: undefined,
    sort: 0,
    drive_type: undefined,
    database_address: undefined,
    database_port: undefined,
    database_name: undefined,
    database_username: undefined,
    database_password: undefined,
  };
  dataList.value.unshift(item);
  editableData[item.field_id] = {
    ...item,
  };
};

const handleEdit = (record) => {
  editableData[record.field_id] = {
    ...record,
  };
};

const handleCancel = (record) => {
  if (typeof record.field_id === "string") {
    dataList.value.shift();
  } else {
    delete editableData[record.field_id];
  }
};

const openSpecialModal = (record) => {
  specialVisible.value = true
  specialModalId.value = record.field_id
  if (!specialModalData[record.field_id]) {
    specialModalData[record.field_id] = {
      drive_type: undefined,
      database_address: undefined,
      database_port: undefined,
      database_name: undefined,
      database_username: undefined,
      database_password: undefined,
    }
  }
}

const handleSave = (record) => {
  const params = {
    is_search: record.is_search,
    field_type_id: record.field_type_id,
    modular_id: props.modularId,
    original_type: record.original_type,
    original_sql: record.original_sql,
    is_other_database: record.is_other_database,
  };
  // 如果数据库特配弹框有数据
  if (specialModalData[record.field_id]) {
    params.drive_type = specialModalData[record.field_id].drive_type
    params.database_address = specialModalData[record.field_id].database_address
    params.database_port = specialModalData[record.field_id].database_port
    params.database_name = specialModalData[record.field_id].database_name
    params.database_username = specialModalData[record.field_id].database_username
    params.database_password = specialModalData[record.field_id].database_password
  }
  // 检验必填参数
  const validateFields = [
    { field: 'field_title', msg: "请填写字段标题" },
    { field: 'field_name', msg: "请填写字段名称" },
    { field: 'field_numerical_type_id', msg: "请选择字段类型" },
    { field: 'belong_to_table', msg: "请填写关联表" },
  ]
  for(let i = 0; i < validateFields.length; i++) {
    const curr = validateFields[i];
    if (!record[curr.field]) {
      message.error(curr.msg);
      return;
    } else {
      params[curr.field] = record[curr.field];
    }
  }
  if (record.is_search && !record.field_type_id) {
    message.error("请选择搜索类型");
    return;
  }

  // 如果是编辑操作
  if (typeof record.field_id === "number") {
    params.field_id = record.field_id;
  }

  saveField(params).then(() => {
    delete editableData[record.field_id];
    message.success("保存成功");
    toGetList();
  });
};
</script>

<style lang="less" scoped>
.header-box {
  margin-bottom: 10px;
}

.pagination-box {
  text-align: center;
}
</style>
