<template>
  <div>
    <n-card
      :bordered="true"
      title="玩家天赋"
      class="proCard mt-2"
      size="small"
      :segmented="{ content: true }"
    >
      <template #header-extra>
        <n-space>
          <n-popconfirm
            @positive-click="handlePositiveClick(1)"
            @negative-click="handleNegativeClick"
          >
            <template #trigger>
              <n-button strong secondary type="success">一键满天赋</n-button>
            </template>
            再次确认？
          </n-popconfirm>
          <n-popconfirm
            @positive-click="handlePositiveClick(0)"
            @negative-click="handleNegativeClick"
          >
            <template #trigger>
              <n-button strong secondary type="error">一键清天赋</n-button>
            </template>
            再次确认？
          </n-popconfirm>
          <n-popconfirm
            @positive-click="handlePositiveClick(2)"
            @negative-click="handleNegativeClick"
          >
            <template #trigger>
              <n-button strong secondary type="success">打开所有天赋</n-button>
            </template>
            再次确认？
          </n-popconfirm>
          <n-button
            strong
            secondary
            type="info"
            v-show="!showModifyTalent"
            @click="showModifyTalent = true"
            >修改天赋</n-button
          >
          <n-button strong secondary type="info" v-show="showModifyTalent" @click="preview"
            >预览天赋</n-button
          >
        </n-space>
      </template>
      <n-skeleton v-if="loading" text :repeat="6" />

      <template v-else>
        <!-- 修改天赋 -->
        <n-form v-show="showModifyTalent" ref="formRef" :model="formValue">
          <n-row :gutter="24">
            <template v-for="(item, i) in formValue" :key="i">
              <n-col :span="6">
                <n-form-item :label="item.talent_name" size="large">
                  <n-input-number v-model:value="item.level" :max="item.max_level" min="0" />
                  <template #feedback> {{ item.description }} </template>
                </n-form-item>
              </n-col>
            </template>
          </n-row>

          <n-form-item>
            <n-space>
              <n-button type="info" @click="handleValidateClick">保存修改</n-button>
            </n-space>
          </n-form-item>
        </n-form>

        <!-- 预览天赋 -->
        <n-descriptions
          label-placement="left"
          label-align="left"
          :column="4"
          size="large"
          v-show="!showModifyTalent"
        >
          <template v-for="(item, i) in formValue" :key="i">
            <n-descriptions-item>
              <template #label>{{ item.talent_name }}</template>
              <span class="default_text_value">{{ item.level }}</span>
            </n-descriptions-item>
          </template>
        </n-descriptions>
      </template>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';
  import { FormInst, useMessage } from 'naive-ui';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { downloadJsonStore } from '@/store/modules/downloadJson';
  import { updateTalents } from '@/api/account/list';

  // 天赋数据
  const talentData = ref();
  const jsonStore = downloadJsonStore();

  const message = useMessage();

  const loading = ref(false);

  const formRef = ref<FormInst | null>(null);

  const formValue = ref([]);

  const showModifyTalent = ref(false);

  interface Props {
    userId?: number | string;
    userInfo?: any;
  }
  const props = withDefaults(defineProps<Props>(), { userId: 0, userInfo: userInfoObj });

  onMounted(async () => {
    loading.value = false;
  });

  // 一键天赋操作
  function handlePositiveClick(st: number) {
    // 清空
    if (st === 0) {
      for (let i = 0; i < formValue.value.length; i++) {
        formValue.value[i].level = 0;
      }
    } else if (st === 1) {
      // 点满
      for (let i = 0; i < formValue.value.length; i++) {
        formValue.value[i].level = formValue.value[i].max_level;
      }
    } else if (st === 2) {
      // 打开
      for (let i = 0; i < formValue.value.length; i++) {
        formValue.value[i].level = 1;
      }
    }
    showModifyTalent.value = true;
  }
  function handleNegativeClick() {}

  function handleValidateClick(e: MouseEvent) {
    e.preventDefault();
    formRef.value?.validate((errors) => {
      if (!errors) {
        let talent_info = {};
        for (let i = 0; i < formValue.value.length; i++) {
          talent_info[Number(formValue.value[i].talent_Id)] = formValue.value[i].level;
        }
        console.log('talent_info:' + JSON.stringify(talent_info));

        updateTalents({ ...{ playerid: Number(props.userId), talent_info: talent_info } })
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });
      } else {
        console.log('errors:' + errors);
        message.error(errors.toString);
      }
    });
  }

  function preview() {
    loadTalentData();
    showModifyTalent.value = false;
  }

  function loadTalentData() {
    if (talentData.value == undefined || talentData.value.length === 0) {
      talentData.value = [...jsonStore.getTalents];
    }

    for (let i = 0; i < talentData.value.length; i++) {
      let index = props.userInfo.talents.findIndex(
        (res) => res.id === talentData.value[i].talent_Id
      );

      if (index == -1) {
        talentData.value[i].level = 0;
      } else {
        talentData.value[i].level = props.userInfo.talents[index].level;
      }
    }
    formValue.value = talentData.value;
  }

  watch(props, (_newVal, _oldVal) => {
    loadTalentData();
  });

  onMounted(async () => {
    if (props.userId < 1) {
      console.log('传入用户信息不正确，props.userId：', props.userId);
      return;
    }
    await loadTalentData();
  });
</script>

<style lang="less" scoped>
  .default_text_value {
    color: var(--n-tab-text-color-active);
  }
</style>
