<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="关卡进度调整">
        <n-space>
          <n-button type="primary" @click="handleClick(1)">通关所有关卡</n-button>
          <n-button type="error" @click="handleClick(0)">清除通关记录</n-button>
        </n-space>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-2 proCard">
      <n-grid cols="1 s:1 m:3 l:3 xl:3 2xl:3" responsive="screen">
        <n-grid-item offset="0 s:0 m:1 l:1 xl:1 2xl:1">
          <n-form
            :label-width="80"
            :model="formValue"
            label-placement="left"
            ref="formRef"
            class="py-8"
          >
            <n-form-item label="通关到" path="matter">
              <n-select
                placeholder="请选择要通关的关卡"
                :options="matterList"
                v-model:value="formValue.matter"
                multiple
              />
            </n-form-item>
            <div style="margin-left: 80px">
              <n-space>
                <n-button type="primary" @click="formSubmit">提交</n-button>
                <n-button @click="resetForm">重置</n-button>
              </n-space>
            </div>
          </n-form>
        </n-grid-item>
      </n-grid>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref, reactive, onMounted } from 'vue';
  import { useMessage, useDialog } from 'naive-ui';
  import { downloadJsonStoreWidthOut } from '@/store/modules/downloadJson';
  import { updateChapter } from '@/api/account/list';
  import { getJsonVersion } from '@/utils/admin';

  interface Props {
    userId: number;
  }
  const downloadJsonStore = downloadJsonStoreWidthOut();
  // eslint-disable-next-line vue/require-valid-default-prop
  const props = withDefaults(defineProps<Props>(), {
    userId: 0,
  });

  const dialog = useDialog();

  const matterList = ref([{}]);

  const formRef: any = ref(null);
  const message = useMessage();

  const defaultValueRef = () => ({
    matter: '',
  });

  let formValue = reactive(defaultValueRef());

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        // console.log('formValue.value:' + JSON.stringify(formValue));

        updateChapter({
          ...{ playerid: props.userId, pass_chapters: formValue.matter },
        })
          .then((_res) => {
            // console.log('_res:' + JSON.stringify(_res));
            message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  // 一键通关操作
  function handleClick(st: number) {
    dialog.info({
      title: st === 1 ? '通关所有关卡' : '清除通关记录',
      content: '再次确认？',
      positiveText: '确认',
      negativeText: '取消',
      maskClosable: false,
      onPositiveClick: () => {
        let req = {
          one_empty: false,
          one_pass: false,
        };
        if (st === 0) {
          req.one_empty = true;
        }
        if (st === 1) {
          req.one_pass = true;
        }

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

  function resetForm() {
    formRef.value.restoreValidation();
    formValue = Object.assign(unref(formValue), defaultValueRef());
  }

  function uploadChange(list: string[]) {
    console.log(list);
  }

  async function loadLevelData() {
    matterList.value = downloadJsonStore.chapter;
    if (matterList.value.length === 0) {
      await downloadJsonStore.downloadChapter(getJsonVersion()).then((res) => {
        matterList.value = res;
      });
    }
  }

  onMounted(() => {
    loadLevelData();
  });
  const fatherRefresh = () => {
    loadLevelData();
  };
  defineExpose({ fatherRefresh });
</script>
