<script setup lang="ts">
import studentManageApi from '@/api/studentManage'
import type { CoinDiamondBatchApi } from '@/api/studentManage'
import { operation_add, operation_sub } from '@/api/studentManage'
import type { UserInfo } from '.'
import hud from '@/utils/hud'
import { useStudentManageStore } from '../store'

const props = defineProps<{
  modelValue: boolean
  users: UserInfo[]
}>()

const emit = defineEmits(['update:modelValue', 'send-success'])

const { schoolId } = storeToRefs(useStudentManageStore())

defineOptions({ name: 'BatchSend' })
const value = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

const render = ref(false)

const coin_value = 1
const diamond_value = 2
const goods = [
  {
    label: '乐贝',
    value: coin_value,
  },
  {
    label: '钻石',
    value: diamond_value,
  },
]
const goodsValue = ref(goods[0].value)

// 操作
const ops = [
  {
    label: '奖励',
    value: operation_add,
  },
  {
    label: '扣除',
    value: operation_sub,
  },
]

// 文本框
const batchAmount = ref('')
const batchReason = ref('')
const batchOperation = ref(operation_add)
const userData = ref([] as CoinDiamondBatchApi)

watch(
  () => value.value,
  async val => {
    setTimeout(() => {
      render.value = val
    }, 100)

    if (!val) return
    // 重置属性
    batchAmount.value = ''
    batchReason.value = ''
    goodsValue.value = goods[0].value
    batchOperation.value = ops[0].value
    userData.value = []
    for (const user of props.users) {
      userData.value.push({
        amount: '',
        reason: '',
        operation: operation_add,
        userId: user.id,
        // 学校id
        typeId: schoolId.value,
      })
    }
  },
)

// 是否填写了内容
function hasInput(): boolean {
  return (batchAmount.value ||
    batchReason.value ||
    userData.value.some(item => item.amount || item.reason)) as boolean
}

// 发送
function send(hide: any) {
  if (!hasInput()) {
    hud.error('请输入内容')
    return true
  }
  hud.confirmLoad({
    dialog: '确定要执行么？',
    option: '执行',
    task: async () => {
      const data = toRaw(userData.value)
      if (goodsValue.value === coin_value) {
        await studentManageApi.coinBatch(data)
      } else {
        await studentManageApi.diamondBatch(data)
      }
      hide()
      emit('send-success')
      // 扣除的数据
      const subDataMap: any = {}
      for (const item of data) {
        if (item.operation === operation_add) {
          continue
        }
        const amount = Number(item.amount)
        if (isNaN(amount) || amount <= 0) {
          continue
        }
        item.amount = amount
        subDataMap[item.userId] = item
      }
      // 更新UI
      for (const user of props.users) {
        const item = subDataMap[user.id]
        if (!item) {
          continue
        }
        if (goodsValue.value === coin_value) {
          user.currency = Number(user.currency) - item.amount
        } else {
          user.diamond = Number(user.diamond) - item.amount
        }
      }
    },
  })
  return true
}

watch(
  () => batchAmount.value,
  () => {
    userData.value.forEach(item => {
      item.amount = batchAmount.value
    })
  },
)

watch(
  () => batchReason.value,
  () => {
    userData.value.forEach(item => {
      item.reason = batchReason.value
    })
  },
)

watch(
  () => batchOperation.value,
  () => {
    userData.value.forEach(item => {
      item.operation = batchOperation.value
    })
  },
)
</script>

<template>
  <mj-dialog
    v-model="value"
    :title="`批量奖惩(共${users?.length}人)`"
    :width="1280"
    hide-close
    :confirm-close="hasInput"
    :mask-close="false"
    ok-text="执行"
    :ok="send"
  >
    <div class="basic-info-dialog">
      <div class="mj-data-row">
        <div class="mj-data-item">
          <span class="mj-data-item-title">物品</span>
          <SelectTab v-model="goodsValue" :dataList="goods" type="small" />
        </div>
      </div>
      <div class="user header">
        <div class="name mj-data-item-title">批量设置</div>
        <el-input
          v-model="batchAmount"
          class="amount mj-data-item-input"
          type="number"
          placeholder="数量"
        />
        <el-input v-model="batchReason" class="reason mj-data-item-input" placeholder="理由" />
        <SelectTab v-model="batchOperation" :dataList="ops" type="small" />
      </div>
      <div v-if="render" class="users">
        <div v-for="(user, i) in users" :key="i" class="user">
          <div class="name">{{ user.name }}</div>
          <div class="current">{{ goodsValue === coin_value ? user.currency : user.diamond }}</div>
          <el-input
            v-model="userData[i].amount"
            class="amount mj-data-item-input"
            type="number"
            placeholder="数量"
          />
          <el-input
            v-model="userData[i].reason"
            class="reason mj-data-item-input"
            placeholder="理由"
          />
          <SelectTab v-model="userData[i].operation" :dataList="ops" type="small" />
        </div>
      </div>
    </div>
  </mj-dialog>
</template>

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

.basic-info-dialog {
  .buttons {
    margin-top: 1.67vh;
  }

  .user {
    display: flex;
    align-items: center;
    border-bottom: 0.08vh #ddd solid;
    padding-bottom: 1.67vh;

    $amount_w: 150px;
    $name_w: 200px;

    &:last-child {
      border-bottom: none;
    }

    &.header {
      margin-top: 3.33vh;
      border-color: #333;
      .name {
        width: $name_w + $amount_w - 60px;
        text-align: center;
        margin: 0 30px;
      }
    }

    :deep(.data-item) {
      &.active:last-child {
        background: $error-color;
        color: #fff;
      }
    }

    .current {
      width: $amount_w;
    }

    .name,
    .amount {
      width: $name_w;
    }

    .amount,
    .reason {
      margin-right: 30px;
    }
  }

  .users {
    font-size: $font_size;
    margin-top: 3.33vh;
    display: flex;
    flex-direction: column;
    row-gap: 1.67vh;
    height: 41.67vh;
    overflow: scroll;
    @include hidden_scroll;
  }
}
</style>
