<template>
  <view class="table">
    <uni-table border stripe emptyText="暂无更多数据">
      <!-- 表头行 -->
      <uni-tr>
        <uni-th align="center" width="50">序号</uni-th>
        <uni-th align="center">上级服务类型</uni-th>
        <uni-th align="center" width="50">积分值</uni-th>
        <uni-th align="center" width="50">任务总个数</uni-th>
        <uni-th align="center" width="50">已用个数</uni-th>
        <uni-th align="center" width="50">任务个数</uni-th>
        <uni-th align="center" width="80">任务积分值</uni-th>
      </uni-tr>
      <!-- 表格数据行 -->
      <uni-tr v-for="(item, index) in tableData" :key="item?.taskTypeId" index>
        <uni-td>{{ index + 1 }}</uni-td>
        <uni-td>{{ item.baseId }}</uni-td>
        <uni-td>{{ item.score }}</uni-td>
        <uni-td>{{ item.allQty }}</uni-td>
        <uni-td>{{ item.used }}</uni-td>
        <uni-td>
          <input type="number" @blur="(e) => change(e, index, item)" v-model="item.qty" />
        </uni-td>
        <uni-td>{{ item.subtotal }}</uni-td>
      </uni-tr>
      <!-- 结尾 -->
      <uni-tr>
        <uni-td>总计</uni-td>
        <uni-td>---</uni-td>
        <uni-td>---</uni-td>
        <uni-td>---</uni-td>
        <uni-td>---</uni-td>
        <uni-td>{{ totalQty }}</uni-td>
        <uni-td>{{ totalsubtotal }}</uni-td>
      </uni-tr>
    </uni-table>
  </view>
</template>

<script setup lang="ts">
import { ref, defineEmits } from 'vue'

const emit = defineEmits(['updateScope'])

const tableData = ref<any[]>([])

const totalQty = ref(0)
const totalsubtotal = ref(0)

const change = (detail: any, index: number, item: any) => {
  let max = item.allQty - item.used
  const value = tableData.value[index].qty
  if (value > max) {
    tableData.value[index].qty = max
  }
  tableData.value[index].subtotal = tableData.value[index].qty * tableData.value[index].score
  totalQty.value = tableData.value.reduce((sum, row) => Number(sum) + Number(row.qty), 0)
  totalsubtotal.value = tableData.value.reduce((sum, row) => Number(sum) + Number(row.subtotal), 0)
  emit('updateScope', totalsubtotal.value)
}

const setData = (data: any[]) => {
  tableData.value = [...data]
  tableData.value.forEach((item, index) => {
    item.index = index
    item.score = item.price
    item.subtotal = 0
    item.baseId = item.taskTypeName
    item.allQty = item.qty
    item.qty = 0
  })
}
const getData = () => {
  return tableData.value
}

defineExpose({ setData, getData })
</script>

<style lang="scss" scoped>
.table {
  margin-top: 20rpx;
  width: 640rpx;
  min-height: 300rpx;
  background-color: #fff;
  border-radius: 12rpx;
}
</style>
