<template>
  <a-modal
    v-model:visible="visible"
    :width="560"
    title-align="start"
    top="10px"
    :align-center="false"
    :mask-closable="false"
    :esc-to-close="false"
    @before-open="modalBeforeOpen"
  >
    <template #title> 下载设置 </template>
    <a-form ref="formRef" :model="formData" :rules="rules" auto-label-width>
      <a-form-item field="pictureType" label="下载文件">
        <a-checkbox-group v-model="formData.pictureType" direction="vertical">
          <template v-for="(option, index) in pictureOptions" :key="index">
            <a-checkbox :value="option.value">
              {{ option.label }}
            </a-checkbox>
            <div class="tips-info" style="padding-left: 27px">
              {{ pictureDesc[option.value as PictureTypeEnum] }}
            </div>
          </template>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item field="outputDir" label="保存目录" :content-flex="false">
        <a-input-search
          v-model.trim="formData.outputDir"
          :style="{ width: '420px' }"
          readonly
          search-button
          button-text="浏览"
          @search="toSelectDir"
        >
        </a-input-search>
        <a-checkbox
          v-model="formData.outputDirIsDefault"
          :style="{ marginTop: '5px' }"
          >设为默认下载路径</a-checkbox
        >
      </a-form-item>
      <a-form-item field="trackColorType" label="轨迹颜色">
        <a-radio-group v-model="formData.trackColorType">
          <a-radio
            v-for="(val, key) in TRACK_COLOR_TYPE"
            :key="key"
            :value="key"
            >{{ val }}</a-radio
          >
        </a-radio-group>
      </a-form-item>
      <a-form-item field="studentFileRule" label="文件名规则">
        <a-radio-group v-model="formData.studentFileRule">
          <a-radio
            v-for="(val, key) in STUDENT_FILE_RULE"
            :key="key"
            :value="key"
            >{{ val }}</a-radio
          >
        </a-radio-group>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="close">取消</a-button>
      <a-button type="primary" :disabled="loading" @click="confirm"
        >确认</a-button
      >
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { nextTick, reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import type { FormInstance } from '@arco-design/web-vue/es/form';
  import useLoading from '@/hooks/loading';
  import useModal from '@/hooks/modal';
  import { objAssign, objModifyAssign } from '@/utils/utils';
  import { FormRules } from '@/types/global';
  import useDictOption from '@/hooks/dict-option';
  import { useAppStore } from '@/store';
  import { TrackConfigType } from '@/store/modules/app/types';
  import {
    PictureTypeEnum,
    TRACK_COLOR_TYPE,
    TrackColorTypeEnum,
    STUDENT_FILE_RULE,
    StudentFileRuleEnum,
  } from '@/constants/enumerate';

  defineOptions({
    name: 'ModifySet',
  });

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

  const appStore = useAppStore();

  const { optionList: pictureOptions } = useDictOption('PICTURE_TYPE');
  const pictureDesc: Record<PictureTypeEnum, string> = {
    track: '批阅后图片',
    origin: '学生作答原图',
    pdf: '将学生批阅后的图片合并成一个PDF，一个学生一个PDF',
  };

  const defaultFormData = {
    pictureType: ['track'] as PictureTypeEnum[],
    outputDir: '',
    curOutputDir: '',
    outputDirIsDefault: true,
    trackColorType: 'DEFAULT' as TrackColorTypeEnum,
    studentFileRule: 'CODE' as StudentFileRuleEnum,
  };

  const emit = defineEmits(['modified']);

  const formRef = ref<FormInstance>();
  const formData = reactive<TrackConfigType>({ ...defaultFormData });
  const rules: FormRules<keyof TrackConfigType> = {
    pictureType: [
      {
        required: true,
        message: '请选择图片类型',
      },
    ],
    outputDir: [
      {
        required: true,
        message: '请选择保存目录',
      },
    ],
  };

  async function toSelectDir() {
    const result = await window.electron.dialogSelectFile({
      title: '选择保存目录',
      properties: ['openDirectory'],
    });

    if (result.canceled) return;

    formData.outputDir = result.filePaths[0];

    formRef.value?.validateField('outputDir');
  }

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

    setLoading(true);
    const datas = objAssign(formData, {});
    if (datas.outputDirIsDefault) datas.curOutputDir = datas.outputDir;

    let res = true;
    await window.db
      .updateDict({ key: 'trackConfig', val: JSON.stringify(datas) })
      .catch(() => {
        res = false;
      });
    setLoading(false);
    if (!res) return;

    appStore.setInfo({ trackConfig: datas });
    Message.success('修改成功！');
    emit('modified', datas);
    close();
  }
  /* init modal */
  async function modalBeforeOpen() {
    const res = await window.db.getDict('trackConfig');
    if (res) {
      const config = JSON.parse(res);
      objModifyAssign(formData, config);
    } else {
      objModifyAssign(formData, defaultFormData);
    }

    nextTick(() => {
      formRef.value?.clearValidate();
    });
  }
</script>
