<script lang="ts">
import type { PropType } from "vue";
import { computed, defineComponent, ref, toRaw, unref } from "vue";
import { Alert, Descriptions, Divider } from "ant-design-vue";
import type { Recordable } from "@vben/types";
import { useDebounceFn } from "@vueuse/core";
import { step3Schemas } from "./data";
import { ApiSelect, BasicForm, useForm } from "@/components/Form";
import { Button } from "@/components/Button";
import { pointListApi } from "@/api/alert/model/select";
import { modelSaveApi } from "@/api/alert/model/models";

export default defineComponent({
  components: {
    Button,
    BasicForm,
    ApiSelect,
    [Alert.name]: Alert,
    [Divider.name]: Divider,
    [Descriptions.name]: Descriptions,
    [Descriptions.Item.name]: Descriptions.Item,
  },
  props: {
    beforeData: {
      type: Object as PropType<Record<string, any> | null | undefined>,
    },
    systemId: {
      type: Number,
    },
  },
  emits: ["next", "prev"],
  setup(props, { emit }) {
    const [
      register,
      { appendSchemaByField, removeSchemaByField, validate, setProps },
    ] = useForm({
      labelWidth: 100,
      schemas: step3Schemas,
      actionColOptions: {
        span: 14,
      },
      resetButtonOptions: {
        text: "上一步",
      },
      submitButtonOptions: {
        text: "创建模型",
      },
      resetFunc: customResetFunc,
      submitFunc: customSubmitFunc,
    });
    const n = ref(4);

    function add() {
      appendSchemaByField(
        [
          {
            field: `point${n.value}`,
            component: "Input",
            label: `参数${n.value}`,
            required: true,
            slot: "remoteSearch",
            colProps: {
              span: 23,
            },
          },
          {
            field: `${n.value}`,
            component: "Input",
            label: " ",
            slot: "add",
            colProps: {
              span: 1,
            },
          },
        ],
        ""
      );
      n.value++;
    }

    function del(field) {
      removeSchemaByField([`point${field}`, `${field}`]);
      n.value--;
    }

    async function customResetFunc() {
      emit("prev");
    }

    async function customSubmitFunc() {
      try {
        const values = await validate();
        const pointInfo = [];
        for (const key in values) {
          if (key.startsWith("point")) {
            const point = values[key].split("|");
            const p = {
              description: point[0],
              pointId: point[1],
              unit: point[2],
              Lower: point[3],
              Upper: point[4],
              dead: true,
              limit: false,
            };
            pointInfo.push(p);
          }
        }
        const modelInfo = toRaw(props.beforeData);
        modelInfo.pointInfo = pointInfo;
        const modelId = await modelSaveApi(modelInfo);
        setProps({
          submitButtonOptions: {
            loading: true,
          },
        });
        setTimeout(() => {
          setProps({
            submitButtonOptions: {
              loading: false,
            },
          });
          emit("next", modelId);
        }, 1500);
      } catch (error) {
        console.error(error);
      }
    }

    const keyword = ref<string>("");
    const searchParams = computed<Recordable>(() => {
      return { keyword: unref(keyword) };
    });

    function onSearch(value: string) {
      keyword.value = value;
    }

    async function searchPoint(params) {
      if (params.keyword) {
        const data = await pointListApi(params);
        return data;
      }
    }

    return {
      register,
      del,
      add,
      onSearch: useDebounceFn(onSearch, 300),
      searchParams,
      searchPoint,
      handleReset: () => {
        keyword.value = "";
      },
    };
  },
});
</script>

<template>
  <div class="step3">
    <a-alert message="选择系统测点作为模型数据源。" show-icon />
    <a-descriptions :column="1" class="mt-5">
      <a-descriptions-item label="模型名称">
        {{ beforeData.modelName }}
      </a-descriptions-item>
      <a-descriptions-item label="描述">
        {{ beforeData.description }}
      </a-descriptions-item>
      <a-descriptions-item label="模型算法">
        {{ beforeData.algorithm }}
      </a-descriptions-item>
      <a-descriptions-item label="训练采样间隔">
        {{ beforeData.sampling }}
      </a-descriptions-item>
      <a-descriptions-item label="最小主元贡献率">
        {{ beforeData.rate }}
      </a-descriptions-item>
    </a-descriptions>
    <a-divider />
    <BasicForm @register="register">
      <template #remoteSearch="{ model, field }">
        <ApiSelect
          v-model:value="model[field]"
          :api="searchPoint"
          show-search
          :filter-option="false"
          result-field="list"
          label-field="name"
          value-field="id"
          :params="searchParams"
          @search="onSearch"
        />
      </template>
      <template #add="{ field }">
        <Button v-if="Number(field) === 0" @click="add"> + </Button>
        <Button v-if="field > 0" @click="del(field)"> - </Button>
      </template>
    </BasicForm>
  </div>
</template>

<style lang="less" scoped>
.step3 {
  width: 450px;
  margin: 0 auto;
}
</style>
