<template>
  <div>
    <n-card
      :bordered="true"
      title="属性信息"
      class="proCard mt-2"
      size="small"
      :segmented="{ content: true }"
    >
      <template #header-extra>
        <n-space>
          <!--          <n-button
            strong
            secondary
            type="error"
            v-show="useUserStore.config.mode !== 'release'"
            @click="openCompatibilityTest"
            >档案拷贝
          </n-button> -->
          <n-button strong secondary type="success" @click="showModalRetrofit = true"
            >添加配装
          </n-button>
          <!-- <n-button strong secondary type="info" @click="openSetDanScoreModal">修改段位分</n-button>
          <n-button strong secondary type="info" @click="showModal">账号等级对照表</n-button>
          <n-button
            strong
            secondary
            type="success"
            v-show="!showModifyBase"
            @click="openUpdatePlayerBase"
            >修改属性
          </n-button>
          <n-button
            strong
            secondary
            type="info"
            v-show="showModifyBase"
            @click="showModifyBase = false"
            >预览属性
          </n-button>
          <n-button strong secondary type="success" @click="showModalGift = true"
            >赠送礼包</n-button
          >-->
        </n-space>
      </template>
      <n-descriptions
        label-placement="left"
        label-align="left"
        :column="4"
        size="large"
        v-show="!showModifyBase"
      >
        <n-descriptions-item>
          <template #label>玩家等级</template>
          <span class="default_text_value">{{ userInfo.userLevel }}</span>
        </n-descriptions-item>
        <n-descriptions-item label="玩家体力">
          <n-space>
            <span class="default_text_value">{{ userInfo.materials['16001'] }}</span>
          </n-space>
        </n-descriptions-item>
        <n-descriptions-item label="玩家精力">
          <n-space>
            <span class="default_text_value">{{ userInfo.materials['16001'] }}</span>
          </n-space>
        </n-descriptions-item>
        <n-descriptions-item label="玩家经验">
          <n-space>
            <span class="default_text_value">{{ userInfo.userExp }}</span>
          </n-space>
        </n-descriptions-item>
        <n-descriptions-item label="玩家金币">
          <n-space>
            <span class="default_text_value">{{ userInfo.materials['3001'] }}</span>
          </n-space>
        </n-descriptions-item>
        <n-descriptions-item label="玩家钻石">
          <n-space>
            <span class="default_text_value">{{ userInfo.materials['3002'] }}</span>
          </n-space>
        </n-descriptions-item>
      </n-descriptions>

      <!-- 修改属性 -->
      <n-form v-show="showModifyBase" ref="formRef" :model="formValue">
        <n-alert :show-icon="false">增加或减少玩家属性，默认填0表示不修改</n-alert>
        <n-row :gutter="24">
          <n-col :span="6">
            <n-form-item label="玩家经验" size="large">
              <n-input-number v-model:value="formValue.userExp" min="0" :max="99999999" />
              <template #feedback> 当前值 {{ userInfo.userExp }}</template>
            </n-form-item>
          </n-col>

          <n-col :span="6">
            <n-form-item label="天赋点" size="large">
              <n-input-number v-model:value="formValue.talentPoint" min="0" :max="99999999" />
              <template #feedback> 当前值 {{ userInfo.talentPoint }}</template>
            </n-form-item>
          </n-col>

          <n-col :span="6">
            <n-form-item label="玩家钻石" size="large">
              <n-input-number v-model:value="formValue.diamond" :max="99999999" :min="-99999999" />
              <template #feedback> 当前值 {{ userInfo.diamond }}</template>
            </n-form-item>
          </n-col>

          <n-col :span="6">
            <n-form-item label="玩家金币" size="large">
              <n-input-number v-model:value="formValue.coin" :max="99999999" :min="-99999999" />
              <template #feedback> 当前值 {{ userInfo.coin ?? 0 }}</template>
            </n-form-item>
          </n-col>

          <n-col :span="6">
            <n-form-item label="玩家体力" size="large">
              <n-input-number v-model:value="formValue.stamina" :max="99999999" :min="-99999999" />
              <template #feedback> 当前值 {{ userInfo.stamina }}</template>
            </n-form-item>
          </n-col>

          <n-col :span="6">
            <n-form-item label="玩家精力" size="large">
              <n-input-number v-model:value="formValue.energy" :max="99999999" :min="-99999999" />
              <template #feedback> 当前值 {{ userInfo.energy ?? 0 }}</template>
            </n-form-item>
          </n-col>
        </n-row>

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

    <n-card
      :bordered="true"
      title="账号信息"
      class="proCard mt-2"
      size="small"
      :segmented="{ content: true }"
    >
      <n-skeleton v-if="loading" text :repeat="6" />
      <template v-else>
        <n-descriptions label-placement="left" label-align="left" :column="4" size="large">
          <n-descriptions-item>
            <template #label>玩家ID</template>
            <span class="default_text_value">{{ userInfo.userId }}</span>
          </n-descriptions-item>

          <n-descriptions-item label="账号ID">
            <n-space>
              <span class="default_text_value">{{ userInfo.accId ?? '' }}</span>
            </n-space>
          </n-descriptions-item>

          <n-descriptions-item label="服务器">
            <n-space>
              <span class="default_text_value">{{ getServerName(attr.serverId) }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="openid">
            <n-space>
              <span class="default_text_value">{{ attr.openId }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="昵称">
            <n-space>
              <span class="default_text_value">{{ userInfo.nick }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="注册时间(当前服)">
            <n-space>
              <span class="default_text_value">{{ user.createtime }}</span>
            </n-space>
          </n-descriptions-item>

          <n-descriptions-item label="累计签到次数">
            <n-space>
              <span class="default_text_value">{{ attr.signinCount }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="最近登录">
            <n-space>
              <span class="default_text_value">{{ attr.lastlogintick ?? '' }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="最近登出">
            <n-space>
              <span class="default_text_value">{{ attr.lastlogouttick ?? '' }}</span>
            </n-space>
          </n-descriptions-item>

          <n-descriptions-item label="近90天登录">
            <n-space>
              <span class="default_text_value">{{ attr.loginCount ?? 0 }}次</span>
            </n-space>
          </n-descriptions-item>

          <n-descriptions-item label="近90天看广告">
            <n-space>
              <span class="default_text_value">{{ attr.advCount ?? '' }}次</span>
            </n-space>
          </n-descriptions-item>

          <n-descriptions-item label="近90天在线">
            <n-space>
              <span class="default_text_value">{{ attr.onlineDuration ?? '' }}</span>
            </n-space>
          </n-descriptions-item>
        </n-descriptions>
      </template>
    </n-card>

    <!--    <n-card
      :bordered="true"
      title="充值与消费 （消费数据统计时间从2022年9月1日开始）"
      class="proCard mt-2"
      size="small"
      :segmented="{ content: true }"
    >
      <n-skeleton v-if="loading" text :repeat="6" />
      <template v-else>
        <n-descriptions label-placement="left" label-align="left" :column="4" size="large">
          <n-descriptions-item>
            <template #label>累计充值次数</template>
            <span class="default_text_value">{{ order.rechargeCount }}</span>
          </n-descriptions-item>
          <n-descriptions-item label="累计充值钻石次数">
            <n-space>
              <span class="default_text_value">{{ order.rechargeDiamondCount }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="累计消费金币">
            <n-space>
              <span class="default_text_value">{{ order.consumptionCoinCount }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="累计消费钻石">
            <n-space>
              <span class="default_text_value">{{ order.consumptionDiamondCount }}</span>
            </n-space>
          </n-descriptions-item>

          <n-descriptions-item label="累计充值金额">
            <n-space>
              <span class="default_text_value">{{ order.rechargeAmount }} 元</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="首充时间">
            <n-space>
              <span class="default_text_value">{{ order.firstChargeAt }}</span>
            </n-space>
          </n-descriptions-item>
          <n-descriptions-item label="最近充值时间">
            <n-space>
              <span class="default_text_value">{{ order.lastChargeAt }}</span>
            </n-space>
          </n-descriptions-item>
        </n-descriptions>
      </template>
    </n-card>-->
    <!--    <n-card
      :bordered="true"
      title="玩家操作"
      class="proCard mt-2"
      size="small"
      :segmented="{ content: true }"
    >
      <n-skeleton v-if="loading" text :repeat="6" />
      <template v-else>
        <n-grid :cols="2">
          <n-form-item-gi label="全服封禁/解封">
            <n-switch v-model:value="userBan.ban" @update:value="handleBanUser">
              <template #checked> 已封禁 </template>
              <template #unchecked> 未封禁 </template>
            </n-switch>
            <span style="margin-left: 15px"> 封禁原因 </span>
            <n-input v-model:value="userBan.banReason" style="margin-left: 5px; width: 72%" />
          </n-form-item-gi>
          <n-form-item-gi label="当前服封禁/解封">
            <n-switch v-model:value="singleBan.ban" @update:value="handleSingleBanUser">
              <template #checked> 已封禁 </template>
              <template #unchecked> 未封禁 </template>
            </n-switch>
            <span style="margin-left: 15px"> 封禁原因 </span>
            <n-input v-model:value="singleBan.banReason" style="margin-left: 5px; width: 72%" />
          </n-form-item-gi>
          <n-form-item-gi label="支付关闭/开启">
            <n-switch v-model:value="paySwitch.pay" @update:value="PaymentSwitch">
              <template #checked> 已开启 </template>
              <template #unchecked> 已关闭 </template>
            </n-switch>
            <span style="margin-left: 15px"> 关闭原因 </span>
            <n-input v-model:value="paySwitch.banReason" style="margin-left: 5px; width: 72%" />
          </n-form-item-gi>
          <n-form-item-gi label="禁止聊天/解禁">
            <n-switch v-model:value="chatBan.ban" @update:value="handleChatBan">
              <template #checked> 已封禁 </template>
              <template #unchecked> 未封禁 </template>
            </n-switch>
            <span style="margin-left: 15px"> 解禁时间 </span>
            <n-date-picker
              style="margin-left: 5px"
              v-model:value="chatBan.deadline_time"
              type="datetime"
              clearable
            />
            <span style="margin-left: 15px"> 封禁原因 </span>
            <n-input v-model:value="chatBan.banReason" style="margin-left: 5px; width: 46%" />
          </n-form-item-gi>
        </n-grid>
      </template>
    </n-card>-->

    <!-- <n-card
      :bordered="true"
      title="支付操作"
      class="proCard mt-2"
      size="small"
      :segmented="{ content: true }">
      <n-skeleton v-if="loading" text :repeat="6" />
      <template v-else>
        <n-descriptions label-align="left" :column="2" size="large">
          <n-descriptions-item label="支付关闭/开启">
            <n-switch v-model:value="paySwitch.pay" @update:value="PaymentSwitch" />
            &nbsp;
            <span v-if="paySwitch.pay">已开启</span>
            <span v-else>已关闭</span>
          </n-descriptions-item>
        </n-descriptions>
      </template>
    </n-card> -->

    <n-modal
      v-model:show="showModalRetrofit"
      :show-icon="false"
      preset="dialog"
      title="添加配装"
      style="width: 620px"
    >
      <n-form
        :model="formParamsRetrofit"
        ref="formRefRetrofit"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="选择模板" path="equipments">
          <n-select
            v-model:value="formParamsRetrofit.rid"
            placeholder="选择配装模板"
            :options="retrofitOptions"
            @update:value="handleMaterialTypeChange"
          />
          <template #feedback>
            <br />
            <p>
              <n-button size="small" secondary strong @click="addRetrofitGroup">
                去添加配装模板
                <template #icon>
                  <n-icon>
                    <arrow-forward />
                  </n-icon>
                </template>
              </n-button>
            </p>
          </template>
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModalRetrofit = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="retrofitConfirmForm"
            >确定
          </n-button>
        </n-space>
      </template>
    </n-modal>

    <basicModal @register="modalRegister" ref="modalRef" class="basicModal" @on-ok="okModal">
      <template #default>
        <Level />
      </template>
    </basicModal>

    <n-modal
      v-model:show="showModalOpenAccount"
      :mask-closable="false"
      preset="dialog"
      title="确认"
      :content="
        '开通账号登录后，将无法继续使用微信登录，开通成功后账号为：u' + userId + ', 密码为：123'
      "
      positive-text="确认"
      negative-text="取消"
      @positive-click="onPositiveClick"
      @negative-click="onNegativeClick"
    />

    <n-modal
      v-model:show="showModalUpdateNickname"
      :mask-closable="false"
      preset="dialog"
      title="修改玩家昵称"
    >
      <n-form
        :model="formParamsUpdateNickname"
        ref="formRefUpdateNickname"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="昵称" path="nickname">
          <n-input v-model:value="formParamsUpdateNickname.nickname" />
          <template #feedback> 修改前请确认该账号已退出游戏，否则修改可能不会生效 </template>
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModalUpdateNickname = false)">取消</n-button>
          <n-button
            type="info"
            :loading="formBtnUpdateNicknameLoading"
            @click="updateNicknameConfirmForm"
            >确定
          </n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal
      v-model:show="showModalCompatibilityTest"
      :show-icon="false"
      preset="dialog"
      title="档案拷贝"
      :style="{
        width: '720px',
      }"
    >
      <n-alert :show-icon="false"
        >将正式服玩家数据拷贝到测试服，操作过程中请勿登录该测试服账号，迁移成功后重启测试服生效！</n-alert
      >
      <n-form
        :model="formCompatibilityTestParams"
        ref="formRefCompatibilityTest"
        label-placement="left"
        :label-width="120"
        class="py-4"
      >
        <n-form-item label="服务器" path="service">
          <n-select
            placeholder="请选择服务器"
            :options="serviceList"
            v-model:value="formCompatibilityTestParams.service"
          />
        </n-form-item>
        <n-form-item label="正式服玩家ID" path="userId">
          <n-input-group>
            <n-input-number
              placeholder="请输入正式服玩家ID"
              style="width: 100%"
              v-model:value="formCompatibilityTestParams.produceUserId"
            />
            <n-button type="primary" @click="compatibilityTestVerify">验证账号</n-button>
          </n-input-group>
        </n-form-item>
        <n-form-item label="正式服所在服务器" path="serverName">
          <n-input
            placeholder=" "
            v-model:value="formCompatibilityTestParams.serverName"
            disabled
          />
        </n-form-item>
        <n-form-item label="正式服昵称" path="nickname">
          <n-input placeholder=" " v-model:value="formCompatibilityTestParams.nickname" disabled />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModalCompatibilityTest = false)">取消</n-button>
          <n-button
            type="info"
            :loading="formBtnCompatibilityTestLoading"
            @click="confirmCompatibilityTestForm"
            :disabled="!formCompatibilityTestParams.has"
            >拷贝玩家数据</n-button
          >
        </n-space>
      </template>
    </n-modal>

    <n-modal
      v-model:show="showModalGift"
      :show-icon="false"
      preset="dialog"
      title="赠送礼包"
      style="width: 620px"
    >
      <n-form
        :model="formParamsGift"
        ref="formRefGift"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="礼包ID" path="giftId">
          <n-input-number placeholder="请输入礼包ID" v-model:value="formParamsGift.giftId" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModalGift = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="giftConfirmForm">确定 </n-button>
        </n-space>
      </template>
    </n-modal>

    <SetDanScore
      :showModal="showSetDanScoreModal"
      @updateShowModal="updateSetDanScoreModal"
      :userId="playerId"
    />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref, watch, computed } from 'vue';
  import { FormInst, SelectOption, useMessage } from 'naive-ui';
  import { baseForm, userInfoObj } from '@/views/account/accountList/userInfo';
  import { timestampToTime } from '@/utils/dateUtil';
  import {
    getPlayerAttr,
    // getSigninCount,
    getUserAccountInfo,
    openAccount,
    // orderStatistics,
    // playerAccountBan,
    updatePlayerBase,
    // playerSingleBan,
    UpdateNickname,
    CompatibilityTestVerify,
    CompatibilityTestMigrate,
    // playerPaymentSwitch,
    addGift,
    // playerChatBan,
  } from '@/api/account/list';
  import { useModal } from '@/components/Modal';
  import Level from '@/views/modal/Level.vue';
  import SetDanScore from './SetDanScore.vue';
  import { addPlayerRetrofit, RetrofitGroupOptions } from '@/api/echarts/rechargeList';
  import { ArrowForwardCircleOutline as ArrowForward } from '@vicons/ionicons5';
  import { useRouter } from 'vue-router';
  // import { useUserStoreWidthOut } from '@/store/modules/user';
  import { getServerName } from '@/utils/admin';

  // const useUserStore = useUserStoreWidthOut();

  const serviceList = [
    {
      label: '微信',
      value: 1,
    },
    {
      label: '抖音',
      value: 2,
    },
    {
      label: '美团',
      value: 3,
    },
    {
      label: '闲闲',
      value: 4,
    },
  ];

  const [modalRegister, { closeModal }] = useModal({
    title: '账号等级对照表',
  });

  async function okModal() {
    closeModal();
  }

  const singleBan = reactive({
    ban: false,
    banReason: '',
  });

  const chatBan = reactive({
    ban: false,
    deadline_time: 0,
    banReason: '',
  });

  const paySwitch = reactive({
    pay: false,
    banReason: '',
  });

  const userBan = reactive({
    ban: false,
    banReason: '',
  });
  const formParamsRetrofit = ref({
    rid: null,
  });

  interface Props {
    userId?: number | string;
    userInfo?: any;
  }

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

  const formParamsGift = ref({
    giftId: 0,
  });
  const formRefCompatibilityTest = ref();
  const showModalCompatibilityTest = ref(false);
  const formBtnCompatibilityTestLoading = ref(false);
  const formCompatibilityTestParams = ref<any>({
    service: null,
    nickname: '',
    has: false,
    produceUserId: null,
    server: null,
    serverName: '',
  });

  const formRefUpdateNickname = ref();
  const showModalUpdateNickname = ref(false);
  const formBtnUpdateNicknameLoading = ref(false);
  const formParamsUpdateNickname = ref({
    nickname: '',
  });

  const playerId = computed(() => {
    return props.userId;
  });

  const router = useRouter();
  const retrofitOptions = ref([]);
  const formRefRetrofit: any = ref(null);
  const message = useMessage();
  const showModalOpenAccount = ref(false);
  const showModalRetrofit = ref(false);
  const showModalGift = ref(false);
  const formBtnLoading = ref(false);
  const loading = ref(false);
  const showModifyBase = ref(false);
  const formRef = ref<FormInst | null>(null);
  const formValue = ref<baseForm>({
    stamina: 0,
    energy: 0,
    userExp: 0,
    talentPoint: 0,
    coin: 0,
    diamond: 0,
  });

  const user = ref(
    reactive({
      openid: '',
      nickname: '',
      account: '',
      createtime: '',
      ban: '',
    })
  );

  const attr = ref(
    reactive({
      lastlogintick: '',
      lastlogouttick: '',
      signinCount: 0,
      advCount: 0,
      onlineDuration: '',
      serverId: 0,
      accId: 0,
      openId: '',
      loginCount: 0,
    })
  );

  /*const order = reactive({
    playerid: 0,
    orderPlatform: '',
    rechargeCount: 0,
    rechargeDiamondCount: 0,
    consumptionCoinCount: '',
    consumptionDiamondCount: '',
    firstChargeAt: '',
    lastChargeAt: '',
    rechargeAmount: 0,
  });*/

  /* function handleBanUser(info: boolean) {
    const banInfo = info ? 1 : 0;
    if (!info) {
      userBan.banReason = '';
    }
    playerAccountBan({
      ...{ playerid: Number(props.userId), ban: banInfo, reason: userBan.banReason },
    }).then((res) => {
      console.log('res:' + JSON.stringify(res));

      if (banInfo == 1) {
        userBan.ban = true;
        message.success('封禁成功，下次登录生效');
      } else {
        userBan.ban = false;
        message.success('解封成功');
      }
    });
  }

    function handleSingleBanUser(info: boolean) {
    const banInfo = info ? 1 : 0;
    if (!info) {
      singleBan.banReason = '';
    }
    playerSingleBan({
      ...{ playerid: Number(props.userId), ban: banInfo, reason: singleBan.banReason },
    }).then((res) => {
      console.log('res:' + JSON.stringify(res));
      if (banInfo == 1) {
        singleBan.ban = true;
        message.success('封禁成功，下次登录生效');
      } else {
        singleBan.ban = false;
        message.success('解封成功');
      }
    });
  }

  function handleChatBan(info: boolean) {
    const banInfo = info ? 1 : 0;
    if (!info) {
      chatBan.banReason = '';
    }
    if (info && chatBan.deadline_time < Date.now()) {
      chatBan.ban = false;
      chatBan.deadline_time = null;
      message.error('时间选择不正确');
      return;
    }
    playerChatBan({
      ...{
        playerid: Number(props.userId),
        ban: banInfo,
        deadline_time: chatBan.deadline_time / 1000,
        reason: chatBan.banReason,
      },
    }).then((res) => {
      console.log('res:' + JSON.stringify(res));
      if (banInfo == 1) {
        chatBan.ban = true;
        message.success('封禁成功，下次登录生效');
      } else {
        chatBan.ban = false;
        chatBan.deadline_time = null;
        message.success('解封成功');
      }
    });
  }

  function PaymentSwitch(info: boolean) {
    let switchInfo = info ? 1 : 0;
    if (!info) {
      paySwitch.banReason = '';
    }
    console.log(switchInfo);
    playerPaymentSwitch({
      ...{ playerid: Number(props.userId), switch: switchInfo, reason: paySwitch.banReason },
    }).then((res) => {
      console.log('res:' + JSON.stringify(res));
      if (switchInfo == 1) {
        paySwitch.pay = true;
        message.success('关闭成功，下次登录生效');
      } else {
        paySwitch.pay = false;
        message.success('开启成功');
      }
    });
  }*/

  // function openUpdatePlayerBase() {
  //   formValue.value = {
  //     stamina: 0,
  //     energy: 0,
  //     userExp: 0,
  //     talentPoint: 0,
  //     coin: 0,
  //     diamond: 0,
  //   };
  //   showModifyBase.value = true;
  // }

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

        updatePlayerBase({ ...formValue.value, ...{ playerid: Number(props.userId) } }).then(
          (_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
          }
        );
      } else {
        console.log('errors:' + errors);
        message.error('Invalid');
      }
    });
  }

  function loadBaseInfo() {
    new Promise((_resolve, _reject) => {
      getUserAccountInfo({ playerid: props.userId })
        .then((res) => {
          // 用户信息
          // user.openid = res.openid;
          // user.nickname = res.nickname;
          user.value.account = res.account;
          // user.createtime = res.createtime > 0 ? timestampToTime(res.createtime) : '';
          // user.ban = res.ban == 1 ? '禁用' : '正常';
          userBan.ban = res.ban == 1;
          userBan.banReason = userBan.ban ? res.banReason : '';
          singleBan.ban = res.singleBan == 1;
          singleBan.banReason = singleBan.ban ? res.singleBanReason : '';
          chatBan.ban = res.chatBan == 1;
          chatBan.banReason = chatBan.ban ? res.chatBanReason : '';
          chatBan.deadline_time =
            res.chatBanDeadlineTime * 1000 < Date.now() ? 0 : res.chatBanDeadlineTime * 1000;
          paySwitch.banReason = res.payOffReason;
        })
        .catch((error) => {
          message.error(error.toString());
        });
    });

    new Promise((_resolve, _reject) => {
      getPlayerAttr({ playerid: props.userId })
        .then((res) => {
          console.log('=======res:', res);
          // 属性
          attr.value.lastlogintick =
            res.lastlogintick > 0 ? timestampToTime(res.lastlogintick) : '';
          attr.value.lastlogouttick =
            res.lastlogouttick > 0 ? timestampToTime(res.lastlogouttick) : '';

          attr.value.advCount = res.advCount;
          attr.value.onlineDuration = res.onlineDuration;
          attr.value.accId = res.accId;
          attr.value.serverId = res.line;
          attr.value.openId = res.openId;
          user.value.nickname = res.nickName;
          user.value.createtime = res.create_time > 0 ? timestampToTime(res.create_time) : '';

          paySwitch.pay = res.paySwitch == 1;
          paySwitch.banReason = paySwitch.pay ? paySwitch.banReason : '';
        })
        .catch((error) => {
          // message.error(error.toString());
          console.log('error:' + error.toString());
        });
    });

    /*new Promise((_resolve, _reject) => {
      orderStatistics({ playerid: props.userId })
        .then((res) => {
          if (res.orderPlatform == 1) {
            order.orderPlatform = '安卓';
          } else {
            order.orderPlatform = '苹果';
          }

          order.rechargeCount = res.rechargeCount;
          order.rechargeDiamondCount = res.rechargeDiamondCount;
          order.rechargeAmount = res.rechargeAmount;
          order.firstChargeAt = res.firstChargeAt > 0 ? timestampToTime(res.firstChargeAt) : '';
          order.lastChargeAt = res.lastChargeAt > 0 ? timestampToTime(res.lastChargeAt) : '';

          order.consumptionCoinCount = UtilsTool.unitConversion(res.consumptionCoinCount);
          order.consumptionDiamondCount = UtilsTool.unitConversion(res.consumptionDiamondCount);
        })
        .catch((error) => {
          // message.error(error.toString());
          console.log('error:' + error.toString());
        });
    });*/

    /*new Promise((_resolve, _reject) => {
      getSigninCount({ playerid: props.userId })
        .then((res) => {
          attr.signinCount = res.signinCount;
          attr.loginCount = res.loginCount;
        })
        .catch((e: Error) => {
          // message.error(e.message ?? '操作失败');
          console.log('error:' + e.message);
        });
    });*/
  }

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

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

  function getRetrofitOptions() {
    new Promise((_resolve, _reject) => {
      RetrofitGroupOptions({})
        .then((res) => {
          retrofitOptions.value = res;
        })
        .catch((error) => {
          // message.error(error.toString());
          console.log('error:' + error.toString());
        });
    });
  }

  function handleMaterialTypeChange(value: string, _option: SelectOption) {
    console.log('value' + value);
  }

  function retrofitConfirmForm(e) {
    e.preventDefault();

    formRefRetrofit.value.validate((errors) => {
      if (!errors) {
        // console.log('formParamsRetrofit:' + JSON.stringify(formParamsRetrofit));

        if (formParamsRetrofit.value.rid === null) {
          message.error('请先选择一个配装');
          return;
        }

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

        setTimeout(() => {
          showModalRetrofit.value = false;
          // reloadTable();
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  // function openUpdateNickname() {
  //   showModalUpdateNickname.value = true;
  //   formParamsUpdateNickname.value.nickname = user.nickname;
  // }

  function updateNicknameConfirmForm(e) {
    e.preventDefault();

    formRefUpdateNickname.value.validate((errors) => {
      if (!errors) {
        console.log('formParamsUpdateNickname:' + JSON.stringify(formParamsUpdateNickname));

        if (formParamsUpdateNickname.value.nickname === '') {
          message.error('请输入昵称');
          return;
        }

        UpdateNickname({ nickname: formParamsUpdateNickname.value.nickname, userId: props.userId })
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            user.value.nickname = formParamsUpdateNickname.value.nickname;
            message.success('修改成功');
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });

        setTimeout(() => {
          showModalUpdateNickname.value = false;
          // reloadTable();
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnUpdateNicknameLoading.value = false;
    });
  }

  function addRetrofitGroup() {
    router.push({
      name: 'retrofit-list',
      params: {},
    });
  }

  function onPositiveClick() {
    showModalOpenAccount.value = false;
    openAccount({
      ...{ userId: props.userId },
    })
      .then((res) => {
        console.log(res);
        message.success('开通成功');
        loadBaseInfo();
      })
      .catch((err) => {
        console.log(err);
        message.error(err);
      });
  }

  function onNegativeClick() {
    showModalOpenAccount.value = false;
  }

  // function openCompatibilityTest() {
  //   showModalCompatibilityTest.value = true;
  //   formCompatibilityTestParams.value.nickname = null;
  //   formCompatibilityTestParams.value.server = null;
  //   formCompatibilityTestParams.value.has = false;
  //   formCompatibilityTestParams.value.serverName = '';
  // }

  function compatibilityTestVerify() {
    if (
      formCompatibilityTestParams.value.produceUserId === null ||
      formCompatibilityTestParams.value.produceUserId < 1
    ) {
      message.error('请输入正式服玩家ID');
      return;
    }
    console.log(formCompatibilityTestParams);

    CompatibilityTestVerify(formCompatibilityTestParams.value)
      .then((res) => {
        formCompatibilityTestParams.value.nickname = res.nickname;
        formCompatibilityTestParams.value.server = res.server;
        formCompatibilityTestParams.value.has = res.has;
        formCompatibilityTestParams.value.serverName = getServerName(
          formCompatibilityTestParams.value.server
        );
        console.log('_res:' + JSON.stringify(res));
      })
      .catch((error) => {
        message.error(error.message);
      });
  }

  function confirmCompatibilityTestForm(e) {
    e.preventDefault();

    formRefCompatibilityTest.value.validate((errors) => {
      if (!errors) {
        console.log('formParamsCompatibilityTest:' + JSON.stringify(formCompatibilityTestParams));

        if (formCompatibilityTestParams.value.produceUserId < 1) {
          message.error('请输入正式服玩家ID');
          return;
        }

        CompatibilityTestMigrate({
          produceUserId: formCompatibilityTestParams.value.produceUserId,
          userId: props.userId,
          service: formCompatibilityTestParams.value.service,
        })
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('数据迁移成功，请重启服务器！');
            setTimeout(() => {
              showModalCompatibilityTest.value = false;
              // reloadTable();
            });
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });
      } else {
        message.error('请填写完整信息');
      }
      formBtnCompatibilityTestLoading.value = false;
    });
  }

  const showSetDanScoreModal = ref(false);

  // function openSetDanScoreModal() {
  //   showSetDanScoreModal.value = true;
  // }

  function updateSetDanScoreModal(value) {
    showSetDanScoreModal.value = value;
  }

  function giftConfirmForm(e) {
    e.preventDefault();
    addGift({
      ...{ player_id: Number(props.userId), gift_id: formParamsGift.value.giftId },
    })
      .then((_res) => {
        console.log('_res:' + JSON.stringify(_res));
        message.success('已提交后台处理,添加成功后会推送系统消息');
      })
      .catch((e: Error) => {
        message.error(e.message ?? '操作失败');
      });

    setTimeout(() => {
      showModalGift.value = false;
    });
  }
</script>

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