<template>
  <div>
    <n-modal v-model:show="isShowModal" :show-icon="false" preset="dialog" title="修改段位积分">
      <n-alert :show-icon="false" type="info"> 调整玩家最强王者所在段位 </n-alert>
      <n-form
        :model="params"
        ref="formPacketRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-spin :show="loading" description="请稍候...">
          <n-form-item label="赛季ID" path="seasonId">
            <n-input placeholder="" v-model:value="params.seasonId" disabled />
          </n-form-item>
          <n-form-item label="段位分" path="danScore">
            <n-input-number
              placeholder="请输入段位分"
              v-model:value="params.danScore"
              min="0"
              style="width: 100%"
            />
            <template #feedback> 所在段位：{{ danName }}</template>
          </n-form-item>
        </n-spin>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="closeForm">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">保存修改 </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted, ref, watch } from 'vue';
  import { useMessage } from 'naive-ui';
  import { GetGrandmaster, SetDanScore } from '@/api/account/list';
  import { getJsonVersion } from '@/utils/admin';
  import { downloadJsonStoreWidthOut } from '@/store/modules/downloadJson';
  const downloadJsonStore = downloadJsonStoreWidthOut();

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

  interface Props {
    showModal: boolean;
    userId?: number | string;
  }

  const props = withDefaults(defineProps<Props>(), {
    showModal: false,
    userId: 0,
  });

  const isShowModal = computed({
    get: () => {
      return props.showModal;
    },
    set: (value) => {
      emit('updateShowModal', value);
    },
  });

  const loading = ref(false);
  const params = ref<any>({
    seasonId: 0,
    danScore: 0,
  });

  const formBtnLoading = ref(false);
  const formPacketRef = ref();
  const message = useMessage();

  function confirmForm(e) {
    e.preventDefault();
    const req = {
      playerid: props.userId,
      danScore: params.value.danScore,
    };

    SetDanScore(req)
      .then((_res) => {
        message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
        setTimeout(() => {
          closeForm();
        });
      })
      .finally(() => {
        formBtnLoading.value = false;
      });
  }

  onMounted(async () => {
    // loadKingSeasonDan();
  });

  function closeForm() {
    isShowModal.value = false;
  }

  function loadForm(value) {
    loading.value = true;
    GetGrandmaster({ playerid: value })
      .then((res) => {
        if (res === null) {
          message.error('该玩家还没有参与过最强王者');
          return;
        }
        console.log('loadForm res:' + JSON.stringify(res));
        const season = JSON.parse(res.season);
        params.value.seasonId = season.seasonId;
        params.value.danScore = season.danScore;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const kingSeasonDan = ref([]);
  function loadKingSeasonDan() {
    kingSeasonDan.value = downloadJsonStore.chapter;
    if (kingSeasonDan.value.length === 0) {
      downloadJsonStore.downloadKingSeasonDan(getJsonVersion()).then((res) => {
        kingSeasonDan.value = res;
      });
    }
  }

  const danName = computed(() => {
    if (!kingSeasonDan.value || kingSeasonDan.value.length == 0) {
      return '';
    }
    if (params.value.danScore <= kingSeasonDan.value[0].count) {
      return kingSeasonDan.value[0].danName; // 返回最小段位名称
    }

    if (params.value.danScore >= kingSeasonDan.value[kingSeasonDan.value.length - 1].count) {
      return kingSeasonDan.value[kingSeasonDan.value.length - 1].danName; // 返回最大段位名称
    }

    for (let i = 1; i < kingSeasonDan.value.length; i++) {
      if (params.value.danScore < kingSeasonDan.value[i].count) {
        return kingSeasonDan.value[i - 1].danName; // 返回最小的段位名称
      }
    }
    return ''; // 若未找到对应段位，则返回空字符串
  });

  // watch(
  //   () => props.userId,
  //   (value) => {
  //     loadForm(value);
  //   }
  // );

  watch(
    () => props.showModal,
    (value) => {
      if (value === true) {
        loadForm(props.userId);
      }
    }
  );

  watch(
    () => params.value.danScore,
    (value) => {
      console.log('danScore:' + value);
    }
  );
</script>

<style lang="less"></style>
