<script setup lang="ts">
import type { UserInfo } from '.'
import studentManageApi from '@/api/studentManage'
import { status_disabled, status_enabled, type_coin, type_diamond } from '@/api/studentManage'
import hud from '@/utils/hud'
import router from '@/router'
import { useStudentManageStore } from '../store'
import { storeToRefs } from 'pinia'
import { word_book_mode_print } from '../../subject/user-word-book/hooks/main'
import { userStore } from '@/stores'
import num from '@/utils/num'

const props = defineProps<{
  modelValue: boolean
  user: UserInfo
}>()

const emit = defineEmits(['update:modelValue'])
const value = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

defineOptions({ name: 'UserDetail' })

const store = useStudentManageStore()
const { schoolId, classId } = storeToRefs(store)

const { schoolMap, classesMap } = storeToRefs(userStore())

const { user } = toRefs(props)

// 乐贝
const coin = ref('')
const coinReason = ref('')
const coinDisabled = computed(() => {
  const num = Number(coin.value)
  if (isNaN(num)) {
    return true
  }
  return num <= 0
})
// 钻石
const diamond = ref('')
const diamondReason = ref('')
const diamondDisabled = computed(() => {
  const num = Number(diamond.value)
  if (isNaN(num)) {
    return true
  }
  return num <= 0
})

// 用户是否被冻结
const userDisabled = computed(() => {
  return Number(user.value.status) === status_disabled
})

// 弹窗文本
function dialogText(data: { name: string; amount: any; add: boolean; type: string }) {
  let text = '确定要给'
  text += `${hud.highlight(data.name)}同学`
  if (data.add) {
    text += hud.highlight('增加', 'green')
  } else {
    text += hud.highlight('减少')
  }
  text += `【${hud.highlight(Number(data.amount))}】个${data.type}吗？`
  return text
}

// 统一处理逻辑
async function processCoinDiamond(add: boolean, typeNo: number) {
  // 参数处理
  let amount = coin.value as string
  let api = add ? studentManageApi.addCoin : studentManageApi.subCoin
  let type = '乐贝'
  let reason = coinReason.value
  if (typeNo === type_diamond) {
    amount = diamond.value
    type = '钻石'
    api = add ? studentManageApi.addDiamond : studentManageApi.subDiamond
    reason = diamondReason.value
  }
  let option = add ? '奖励' : '扣除'
  option += type

  // 数值判断
  const numAmount = Number(amount)
  if (isNaN(numAmount) || numAmount <= 0 || amount.includes('.')) {
    hud.error('只能输入大于0的整数')
    return
  }

  // 调用接口
  await hud.confirmLoad({
    task: async () =>
      await api({
        amount,
        userId: user.value.id,
        reason,
        typeId: schoolId.value,
      }),
    option,
    dialog: dialogText({
      name: user.value.name,
      amount,
      add,
      type,
    }),
  })

  // 清空文本框
  if (typeNo === type_diamond) {
    if (!add) {
      user.value.diamond = Number(user.value.diamond) - Number(diamond.value)
    }
    diamond.value = ''
  } else {
    if (!add) {
      user.value.currency = Number(user.value.currency) - Number(coin.value)
    }
    coin.value = ''
  }
}

// 增加乐贝
function addCoin() {
  processCoinDiamond(true, type_coin)
}
// 减少乐贝
function subCoin() {
  processCoinDiamond(false, type_coin)
}
// 增加钻石
async function addDiamond() {
  processCoinDiamond(true, type_diamond)
}
// 减少钻石
async function subDiamond() {
  processCoinDiamond(false, type_diamond)
}

// 重置密码
function resetPassword() {
  hud.confirmLoad({
    task: async () => await studentManageApi.resetPassword(user.value.id),
    option: '重置密码',
    dialog: `确定要重置${hud.highlight(user.value.name)}同学的密码吗？`,
  })
}

// 统一处理启用禁用
async function enableDisableAccount(status: number) {
  let color: any = 'green'
  let type = '启用'
  if (status === status_disabled) {
    color = undefined
    type = '禁用'
  }
  await hud.confirmLoad({
    task: async () =>
      await studentManageApi.changeStatus({
        id: user.value.id,
        status,
      }),
    option: type + '账号',
    dialog: `确定要${hud.highlight(type, color)}【${hud.highlight(user.value.name)}】同学的账号吗？`,
  })
  user.value.status = status
}

// 启用账号
function enableAccount() {
  enableDisableAccount(status_enabled)
}

// 禁用账号
function disableAccount() {
  enableDisableAccount(status_disabled)
}

// 打开学情分析
function toAnalysis() {
  if (!user.value.lastLoginTime) {
    hud.error('从未登录过，没有学情数据')
    return
  }
  router.push({
    path: '/studyAnalysis',
    query: {
      id: user.value.id,
    },
  })
}

// 打开单词书
function toWordBook() {
  router.push({
    path: '/subject/user-word-book',
    query: {
      userId: user.value.id,
      userName: user.value.name,
      mode: word_book_mode_print,
    },
  })
}

// 打开任务详情
function toTaskDetail() {
  router.push({
    path: '/task/user-task-records',
    query: {
      userId: user.value.id,
      userName: user.value.name,
    },
  })
}

// 打开学员的乐贝名字
function showCoinDetail() {
  const schoolName = schoolMap.value[schoolId.value]?.schoolName
  const className = classesMap.value[classId.value]?.className
  router.push({
    path: '/self-coin-detail',
    query: {
      userId: user.value.id,
      userName: `${schoolName}-${className}-${user.value.name}`,
    },
  })
}

watch(
  () => value.value,
  async val => {
    if (!val) return
    // 重置属性
    coin.value = ''
    coinReason.value = ''
    diamond.value = ''
    diamondReason.value = ''
  },
)
</script>

<template>
  <mj-dialog v-model="value" :title="user.name" hide-footer :width="1440">
    <div class="basic-info-dialog">
      <div class="mj-data-rows">
        <div class="mj-data-row">
          <div class="mj-data-item">
            <span class="mj-data-item-title">账号</span>
            <span class="value">{{ user.account }}</span>
          </div>
          <div class="mj-data-item">
            <span class="mj-data-item-title">昵称</span>
            <span class="value">{{ user.nickName }}</span>
          </div>
          <div class="mj-data-item">
            <span class="mj-data-item-title">累计签到</span>
            <span class="value">{{ user.aggregateLoginNum }}天</span>
          </div>
        </div>

        <div class="mj-data-row">
          <div class="mj-data-item">
            <span class="mj-data-item-title">上次登录</span>
            <span class="value">{{ user.lastLoginTimeStr }}</span>
          </div>
          <div class="mj-data-item">
            <span class="mj-data-item-title">累计登录</span>
            <span class="value">{{ user.cumulativeTimeDurationStr }}</span>
          </div>
          <div class="mj-data-item">
            <span class="mj-data-item-title">状态</span>
            <span
              :class="{
                value: true,
                status: true,
                disabled: userDisabled,
              }"
              >{{ userDisabled ? '禁用' : '正常' }}</span
            >
            <!-- </div> -->
            <div class="options">
              <mj-button v-if="userDisabled" class="option" type="success" @click="enableAccount"
                >启用</mj-button
              >
              <mj-button v-else class="option" type="danger" @click="disableAccount"
                >禁用</mj-button
              >
            </div>
          </div>
        </div>

        <div class="mj-data-divider"></div>

        <div class="mj-data-row">
          <div class="mj-data-item">
            <div class="desc">
              <span class="mj-data-item-title">乐贝</span>
              <span class="value">{{ num.formatMoney(user.currency) }}</span>
            </div>
            <div class="options">
              <el-input
                v-model="coin"
                class="amount mj-data-item-input"
                type="number"
                placeholder="数量"
              />
              <el-input v-model="coinReason" class="reason mj-data-item-input" placeholder="理由" />
              <mj-button :disabled="coinDisabled" class="option" type="success" @click="addCoin"
                >奖励</mj-button
              >
              <mj-button :disabled="coinDisabled" class="option" type="danger" @click="subCoin"
                >扣除</mj-button
              >
            </div>
          </div>
        </div>
        <div class="mj-data-row">
          <div class="mj-data-item">
            <div class="desc">
              <span class="mj-data-item-title">钻石</span>
              <span class="value">{{ num.formatMoney(user.diamond) }}</span>
            </div>
            <div class="options">
              <el-input
                v-model="diamond"
                class="amount mj-data-item-input"
                type="number"
                placeholder="数量"
              />
              <el-input
                v-model="diamondReason"
                class="reason mj-data-item-input"
                placeholder="理由"
              />
              <mj-button
                :disabled="diamondDisabled"
                class="option"
                type="success"
                @click="addDiamond"
                >奖励</mj-button
              >
              <mj-button
                :disabled="diamondDisabled"
                class="option"
                type="danger"
                @click="subDiamond"
                >扣除</mj-button
              >
            </div>
          </div>
        </div>
      </div>

      <div class="mj-data-divider"></div>

      <div class="bottom">
        <div class="buttons">
          <mj-button type="warn" icon="coin" @click="showCoinDetail">乐贝明细</mj-button>
          <mj-button type="danger" @click="resetPassword">重置密码</mj-button>
        </div>
        <div class="buttons">
          <mj-button type="primary" @click="toAnalysis">学情分析</mj-button>
          <mj-button type="primary" @click="toWordBook">单词书</mj-button>
          <mj-button type="primary" @click="toTaskDetail">任务详情</mj-button>
        </div>
      </div>
    </div>
  </mj-dialog>
</template>

<style lang="scss" scoped>
@use './dialog.scss' as *;

.basic-info-dialog {
  .mj-data-rows {
    padding: 0;
    font-size: $font_size;
    margin-bottom: 3.33vh;

    .status {
      color: green;
      &.disabled {
        color: red;
      }
    }

    .desc {
      display: flex;
      align-items: center;
      width: 300px;
    }

    .options {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 30px;

      .option {
        width: 150px;
        height: 5vh;
      }
    }
  }

  .bottom {
    display: flex;
    flex-direction: column;
    gap: 3vh;
    margin-top: 2.5vh;
  }
}
</style>
