<template>
  <n-drawer v-model:show="isDrawer" :width="width" :placement="placement">
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="100"
      >
        <n-divider title-placement="left">基本设置</n-divider>
        <n-form-item label="玩家ID" path="playerid">
          <n-input v-model:value="userId" :disabled="true" />
        </n-form-item>
        <n-form-item label="角色ID" path="role_id" style="display: none">
          <n-input v-model:value="roleDrawerData.id" />
        </n-form-item>
        <n-form-item label="选择等级" path="new_role_id">
                   <n-cascader
                      :options="options"
                      :default-value="[roleDrawerData.label]"
                      label-field="label"
                      value-field="value"
                      children-field="children"
                      :on-update:value="updateLevels"
                    />
                    <template #option-label="{ option }">  
                      {{ 'Lv.' + option.label }}  
                    </template>  
                    <!-- <n-select v-model:value="formParams.new_role_id" :options="options" label-field="level"/> -->
          <n-input v-model:value="formParams.new_role_id" />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts">
  import { defineComponent, reactive, ref, toRefs, watch } from 'vue';
  import { TreeSelectOption, useMessage } from 'naive-ui';
  import { QuestionCircleOutlined } from '@vicons/antd';
  import { genRoleOptions } from '@/convert/role/roles';
  import { upgradeRole,getRoleLevel } from '@/api/account/list';
  // import { number } from 'vue-types';

  const rules = {
    label: {
      required: true,
      message: '请输入标题',
      trigger: 'blur',
    },
    path: {
      required: true,
      message: '请输入路径',
      trigger: 'blur',
    },
  };
  export default defineComponent({
    name: 'CreateDrawer',
    components: {},
    props: {
      title: {
        type: String,
        default: '添加顶级菜单',
      },
      userId: {
        type: String,
        default: '',
      },
      roleDrawerData: {
        type: Object,
        default: [],
      },
      roleName:{
        type: String,
        default: '',
      }
    },
    
    setup(props) {
      const message = useMessage();
      const formRef: any = ref(null);
      const defaultValueRef = () => ({
        playerid: props.userId,
        role_id: props.roleDrawerData.id,
        new_role_id: null,
        role_name:props.roleName
      });

      console.log('props.roleDrawerData.id:' + JSON.stringify(props.roleDrawerData));
      const options = ref([])
      // 异步函数用于调用后端接口
      const fetchData = async (roleName) => {
        try {
          const response = await getRoleLevel({ role_name: roleName });
          console.log('response====:', response[0].levels);
          options.value = response.map(roleData => ({
            label: `Lv. ${roleData.star}`, // 添加 "Lv." 前缀
            value: roleData.star,  
            children: roleData.levels.map(levelItem => ({  
              label: `Lv. ${levelItem.level}`, // 添加 "Lv." 前缀
              value: levelItem.id,  
            })),

          }));
      
        } catch (error) {
          console.log('Error during backend request:', error);
        }
      };


      const state = reactive({
        width: 500,
        isDrawer: false,
        subLoading: false,
        formParams: defaultValueRef(),
        placement: 'right',
        icon: '',
        alertText:
          '该功能主要实时预览各种布局效果，更多完整配置在 projectSetting.ts 中设置，建议在生产环境关闭该布局预览功能。',
      });

      function openDrawer() {
        if (document.body.clientWidth < 500) {
          state.width = document.body.clientWidth;
        }
        state.isDrawer = true;
      }

      function closeDrawer() {
        state.isDrawer = false;
      }

      function updateLevels(val) {
        console.log('updateLevels val:' + JSON.stringify(val));
        state.formParams = Object.assign(state.formParams, defaultValueRef(), { new_role_id: val });
      }

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

            if (state.formParams.new_role_id == null || state.formParams.new_role_id <= 0) {
              message.error('输入的新角色等级无效！');
              return;
            }
            upgradeRole({
              ...{
                user_id: Number(props.userId),
                role_id: Number(state.formParams.role_id),
                new_role_id: Number(state.formParams.new_role_id),
              },
            })
              .then((_res) => {
                console.log('_res:' + JSON.stringify(_res));
                message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
              })
              .catch((e: Error) => {
                message.error(e.message ?? '操作失败');
              });

            handleReset();
            closeDrawer();
          } else {
            message.error('请填写完整信息');
          }
        });
      }

      function handleReset() {
        formRef.value.restoreValidation();
        state.formParams = Object.assign(state.formParams, defaultValueRef());
      }

      // 处理选项更新
      function handleUpdateValue(
        value: string | number | Array<string | number> | null,
        option: TreeSelectOption | null | Array<TreeSelectOption | null>
      ) {
        console.log(value, option);
      }

      watch(props, (_newVal, _oldVal) => {
        fetchData(props.roleName);
        state.formParams.role_id = _newVal.roleDrawerData.id;
        loadOptions(_newVal.roleDrawerData.id);
      });

      function loadOptions(role_id) {
        options.value = genRoleOptions(role_id);
      }

      return {
        ...toRefs(state),
        formRef,
        rules,
        formSubmit,
        handleReset,
        openDrawer,
        closeDrawer,
        handleUpdateValue,
        QuestionCircleOutlined,
        options,
        updateLevels,
      };
    },
  });
</script>
