<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($event, 1)"
            @negative-click="handleNegativeClick"
          >
            <template #trigger>
              <n-button strong secondary type="success">全部引导通过</n-button>
            </template>
            再次确认？
          </n-popconfirm>
          <n-popconfirm
            @positive-click="handlePositiveClick($event, 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-spin :show="loading" description="正在从服务器查询引导信息...">
        <n-form ref="formRef" :model="formValue">
          <n-row :gutter="24">
            <template v-for="(item, i) in formValue" :key="i">
              <n-col :span="3">
                <n-form-item :label="item.label" size="large">
                  <n-switch size="large" v-model:value="item.pass" />
                  <template #feedback> 功能ID：{{ item.value }} </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-spin>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { FormInst, useMessage } from 'naive-ui';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { updateGuides } from '@/api/account/list';
  import { guidesMaps } from '@/convert/guide/map';

  export type GuideItem = {
    label: string;
    value: number;
    pass: boolean;
  };

  const message = useMessage();

  const loading = ref(false);

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

  const formValue = ref<GuideItem[]>([]);

  const showModifyTalent = ref(false);

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

  // 一键引导操作
  function handlePositiveClick(event, st: number) {
    // 清空
    if (st === 0) {
      for (let i = 0; i < formValue.value.length; i++) {
        formValue.value[i].pass = false;
      }
    } else if (st === 1) {
      // 点满
      for (let i = 0; i < formValue.value.length; i++) {
        formValue.value[i].pass = true;
      }
    }
    showModifyTalent.value = true;
    handleValidateClick(event);
  }

  function handleNegativeClick() {}

  function handleValidateClick(e: MouseEvent) {
    e.preventDefault();
    formRef.value?.validate((errors) => {
      if (!errors) {
        console.log('formValue.value:' + JSON.stringify(formValue.value));

        let guides: number[] = [];
        for (let i = 0; i < formValue.value.length; i++) {
          console.log('formValue.value[i]:' + JSON.stringify(formValue.value[i]));
          if (formValue.value[i].pass === true) {
            guides.push(formValue.value[i].value);
          }
        }

        console.log('guides:' + JSON.stringify(guides));

        updateGuides({ ...{ playerid: Number(props.userId), guides: guides } })
          .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 loadGuideData() {
    loading.value = true;
    const userGuides = props.userInfo.guides;
    for (let i = 0; i < guidesMaps.length; i++) {
      formValue.value[i] = {
        label: guidesMaps[i].label,
        value: guidesMaps[i].value,
        pass: false,
      };
      if (userGuides === null) {
        continue;
      }
      if (userGuides[guidesMaps[i].value] === undefined) {
        continue;
      }
      formValue.value[i].pass = userGuides[guidesMaps[i].value] === 1;
    }
    loading.value = false;
  }

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

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