<template>
  <a-modal
    v-model:open="visible"
    :width="470"
    style="top: 10vh"
    :confirm-loading="loading"
    @ok="confirm"
  >
    <template #title> {{ title }} </template>

    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ style: { width: '80px' } }"
    >
      <a-form-item name="subjectCode" label="科目代码">
        <select-course
          v-model:value="formData.subjectCode"
          :exam-id="userStore.curExam.id"
        ></select-course>
      </a-form-item>
      <a-space
        v-for="(condition, index) in formData.conditions"
        :key="condition.code"
        :size="8"
      >
        <a-form-item
          :label="index === 0 ? '任务条件' : ' '"
          :name="['conditions', index, 'code']"
          :rules="{
            required: true,
            message: '请选择条件类型',
            trigger: 'change',
          }"
        >
          <a-select
            v-model:value="condition.code"
            :options="conditionList"
            :field-names="fieldNames"
            style="width: 200px"
            @change="(val) => conditionChange(val, index)"
          ></a-select>
        </a-form-item>

        <a-form-item
          v-if="formData.conditions[index].needValue"
          :span="5"
          :name="['conditions', index, 'value']"
          :rules="{
            required: true,
            message: '请输入',
            trigger: 'change',
          }"
        >
          <a-input-number
            v-model:value="condition.value"
            placeholder="数值"
            :min="1"
            :max="999"
            :precision="0"
            :controls="false"
            style="width: 60px"
          />
        </a-form-item>
        <a-form-item>
          <a-button @click="onAddCondition(index)">
            <template #icon><PlusOutlined /></template>
          </a-button>
          <a-button
            :disabled="deleteDisabled"
            @click="onDeleteCondition(index)"
          >
            <template #icon><MinusOutlined /></template>
          </a-button>
        </a-form-item>
      </a-space>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, computed, reactive, ref, watch } from "vue";
import type { UnwrapRef } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined, MinusOutlined } from "@ant-design/icons-vue";

import useLoading from "@/hooks/useLoading";
import useModal from "@/hooks/useModal";
import {
  recognizeCheckTaskSave,
  recognizeConditionsList,
} from "@/ap/recognizeCheck";
import {
  RecognizeConditionItem,
  RecognizeCheckListItem,
  RecognizeCheckTaskSaveParams,
  RecognizeCheckTaskSetConditionItem,
} from "@/ap/types/recognizeCheck";
import { useUserStore } from "@/store";

defineOptions({
  name: "ModifyRecognizeCheckTask",
});

/* modal */
const { visible, open, close } = useModal();
defineExpose({ open, close });

const userStore = useUserStore();

const defaultFormData = {
  id: undefined,
  examId: 0,
  subjectCode: "",
  conditions: [] as RecognizeCheckTaskSetConditionItem[],
};

const props = defineProps<{
  rowData: RecognizeCheckListItem | null;
}>();
const emit = defineEmits(["modified"]);

const isEdit = computed(() => !!props.rowData);
const title = computed(() => `${isEdit.value ? "编辑" : "新增"}任务`);

const formRef = ref();
const formData: UnwrapRef<RecognizeCheckTaskSaveParams> = reactive({
  ...defaultFormData,
});
const rules: FormRules<keyof RecognizeCheckTaskSaveParams> = {
  subjectCode: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
};

const deleteDisabled = computed(() => formData.conditions.length <= 1);

// condition action
const conditionList = ref<RecognizeConditionItem[]>([]);
const fieldNames = { label: "name", value: "code" };
async function getConditionList() {
  const res = await recognizeConditionsList();

  conditionList.value = res || [];
}

function conditionChange(val: string, index: number) {
  const curCondition = conditionList.value.find((item) => item.code === val);
  if (!curCondition) return;

  formData.conditions[index].needValue = curCondition.needValue;
  formData.conditions[index].name = curCondition.name;
}

function onAddCondition(index: number) {
  formData.conditions.splice(index + 1, 0, {
    code: "",
    name: "",
    needValue: false,
    value: null,
  });
}
function onDeleteCondition(index: number) {
  formData.conditions.splice(index, 1);
}

/* confirm */
const { loading, setLoading } = useLoading();
async function confirm() {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  setLoading(true);
  const res = await recognizeCheckTaskSave(formData).catch(() => false);
  setLoading(false);
  if (!res) return;
  message.success("保存成功！");
  emit("modified");
  close();
}

/* init modal */
watch(
  () => visible.value,
  (val) => {
    if (val) {
      modalOpenHandle();
    }
  },
  {
    immediate: true,
  }
);

function modalOpenHandle() {
  const conditionMap: Record<string, RecognizeConditionItem> = {};
  conditionList.value.forEach((item) => {
    conditionMap[item.code] = item;
  });

  if (props.rowData) {
    formData.id = props.rowData.id;
    formData.subjectCode = props.rowData.subjectCode;
    formData.examId = userStore.curExam.id;
    formData.conditions = props.rowData.conditions.map((item) => {
      return {
        ...item,
        needValue: conditionMap[item.code]?.needValue,
      };
    });
  } else {
    formData.id = undefined;
    formData.subjectCode = "";
    formData.examId = userStore.curExam.id;
    formData.conditions = [
      { code: "", name: "", needValue: false, value: null },
    ];
  }
}

onMounted(() => {
  getConditionList();
});
</script>
