<template>
  <view class="container">
    <u-sticky offsetTop="0rpx" customNavHeight="0rpx">
      <view class="toolbar">
        <view class="summary">
          <text class="summary-label">明细合计</text>
          <text class="summary-value">{{ detailTotalCost }} 元</text>
        </view>
        <view class="toolbar-actions">
          <view class="toolbar-btn" @click="handleAdd">
            <uni-icons type="plusempty" size="18" color="#667eea"></uni-icons>
            <text>新增</text>
          </view>
          <view class="toolbar-btn primary" @click="handleUpdateCost">
            <uni-icons type="checkmarkempty" size="18" color="#ffffff"></uni-icons>
            <text>汇总</text>
          </view>
        </view>
      </view>
    </u-sticky>

    <u-list @scrolltolower="loadmore" :spaceHeight="104" lowerThreshold="100">
      <u-list-item v-for="item in listData" :key="item.id">
        <view class="list-item">
          <view class="item-header">
            <view class="card-name-section">
              <view class="card-icon">
                <uni-icons type="list" size="20" color="#ffffff"></uni-icons>
              </view>
              <view class="card-info">
                <text class="card-name">{{ item.costName || dictStr(item.type, costTypeList) || '费用明细' }}</text>
                <text class="card-code">{{ item.costTime || '--' }}</text>
              </view>
            </view>
          </view>

          <view class="card-body">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">费用类型</text>
                <text class="info-value">{{ dictStr(item.type, costTypeList) || '--' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">费用名称</text>
                <text class="info-value">{{ item.costName || '--' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">单价</text>
                <text class="info-value">{{ item.price || '--' }} 元</text>
              </view>
              <view class="info-item">
                <text class="info-label">数量</text>
                <text class="info-value">{{ item.count || '--' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">单位</text>
                <text class="info-value">{{ dictStr(item.unit, packageUnitList) || '--' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">总价</text>
                <text class="info-value cost">{{ item.totalCost || '--' }} 元</text>
              </view>
              <view class="info-item info-item-full" v-if="item.remark">
                <text class="info-label">备注</text>
                <text class="info-value">{{ item.remark }}</text>
              </view>
            </view>
          </view>

          <view class="operate" @click.stop>
            <view class="btn-edit" @click="handleEdit(item)">
              <uni-icons type="compose" size="16" color="#667eea"></uni-icons>
              <text>修改</text>
            </view>
            <view class="btn-copy" @click="handleCopy(item)">
              <uni-icons type="copy" size="16" color="#fa8c16"></uni-icons>
              <text>复制</text>
            </view>
            <view class="btn-delete" @click="handleDelete(item)">
              <uni-icons type="trash" size="16" color="#f5576c"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </u-list-item>
      <u-empty v-if="listData.length === 0 && status === 'nomore'" mode="data" text="暂无费用明细"></u-empty>
      <u-loadmore :status="status" loadingIcon="semicircle" height="88" fontSize="32rpx" @loadmore="loadmore" />
    </u-list>

    <u-toast ref="uToast"></u-toast>
    <suspend></suspend>
  </view>
</template>

<script setup>
import { listDoctorRecordCost, delDoctorRecordCost } from '@/api/health/doctorRecordCost'
import { getDoctorRecord, updateDoctorRecord } from '@/api/health/doctorRecord'
import { getDicts } from '@/api/system/dict/data.js'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'

const pageNum = ref(1)
const listData = ref([])
const status = ref('loadmore')
const doctorRecordId = ref(null)
const doctorRecord = ref({})
const isShow = ref(false)
const costTypeList = ref([])
const packageUnitList = ref([])

const detailTotalCost = computed(() => {
  return listData.value
    .reduce((sum, item) => {
      return sum + Number(item.totalCost || 0)
    }, 0)
    .toFixed(2)
})

onLoad((option) => {
  doctorRecordId.value = option.doctorRecordId
  getData()
})

onShow(() => {
  if (isShow.value) {
    refreshList()
    isShow.value = false
  }
})

function getData() {
  getDicts('cost_type').then(res => {
    costTypeList.value = res.data
  })
  getDicts('package_unit').then(res => {
    packageUnitList.value = res.data
  })
  if (doctorRecordId.value) {
    getDoctorRecord(doctorRecordId.value).then(res => {
      doctorRecord.value = res.data
    })
  }
  getList()
}

function dictStr(val, arr) {
  let str = ''
  arr.map(item => {
    if (item.dictValue === val) {
      str = item.dictLabel
    }
  })
  return str
}

function loadmore() {
  pageNum.value += 1
  if (status.value === 'loadmore') {
    getList()
  }
}

function refreshList() {
  pageNum.value = 1
  listData.value = []
  getList()
}

function getList() {
  if (!doctorRecordId.value) {
    status.value = 'nomore'
    return
  }
  status.value = 'loading'
  listDoctorRecordCost({ pageSize: 1000, pageNum: pageNum.value, doctorRecordId: doctorRecordId.value }).then(res => {
    listData.value = listData.value.concat(res.rows)
    if (listData.value.length < res.total) {
      status.value = 'loadmore'
    } else {
      status.value = 'nomore'
    }
  }).catch(() => {
    status.value = 'nomore'
  })
}

function handleAdd() {
  uni.navigateTo({ url: `/pages/health/doctorRecord/costAddEdit?doctorRecordId=${doctorRecordId.value}` })
  isShow.value = true
}

function handleEdit(item) {
  uni.navigateTo({ url: `/pages/health/doctorRecord/costAddEdit?doctorRecordId=${doctorRecordId.value}&id=${item.id}` })
  isShow.value = true
}

function handleCopy(item) {
  uni.navigateTo({ url: `/pages/health/doctorRecord/costAddEdit?doctorRecordId=${doctorRecordId.value}&flag=copy&id=${item.id}` })
  isShow.value = true
}

function handleDelete(item) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条费用明细吗？',
    confirmText: '删除',
    cancelText: '取消',
    confirmColor: '#f5576c',
    cancelColor: '#909399',
    success: function (res) {
      if (res.confirm) {
        delDoctorRecordCost(item.id).then(() => {
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          refreshList()
        })
      }
    }
  })
}

function buildCostDetailSummary() {
  if (!listData.value.length) return ''

  // 按费用类型分组汇总
  const groupMap = new Map()
  listData.value.forEach(item => {
    const typeKey = item.type || '__other__'
    const typeLabel = item.type ? (dictStr(item.type, costTypeList.value) || '未分类') : '未分类'
    if (!groupMap.has(typeKey)) {
      groupMap.set(typeKey, { label: typeLabel, total: 0, count: 0 })
    }
    const g = groupMap.get(typeKey)
    g.total += Number(item.totalCost || 0)
    g.count += 1
  })

  // 拼接汇总字符串，每行一个类型，末行合计
  const lines = []
  let grandTotal = 0
  let grandCount = 0
  groupMap.forEach(g => {
    lines.push(`${g.label}：${g.total.toFixed(2)}元（${g.count}笔）`)
    grandTotal += g.total
    grandCount += g.count
  })
  lines.push(`合计：${grandTotal.toFixed(2)}元（${grandCount}笔）`)
  return lines.join('\n')
}

function handleUpdateCost() {
  if (!doctorRecord.value.id) {
    uni.showToast({
      title: '就医记录不存在',
      icon: 'none'
    })
    return
  }
  if (!listData.value.length) {
    uni.showToast({
      title: '暂无费用明细，无法汇总',
      icon: 'none'
    })
    return
  }
  const total = Number(detailTotalCost.value)
  const costDetail = buildCostDetailSummary()

  // 会覆盖主表原有的费用明细字段，所以弹窗确认
  uni.showModal({
    title: '确认汇总',
    content: `总费用：${total.toFixed(2)}元\n费用明细将按类型汇总并覆盖原有内容，是否继续？`,
    confirmText: '确认汇总',
    cancelText: '取消',
    success: function (res) {
      if (res.confirm) {
        updateDoctorRecord({
          ...doctorRecord.value,
          totalCost: total,
          costDetail: costDetail
        }).then(() => {
          doctorRecord.value.totalCost = total
          doctorRecord.value.costDetail = costDetail
          uni.showToast({
            title: '汇总成功',
            icon: 'success'
          })
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
@import '@/styles/health-common.scss';

// 工具栏
.toolbar {
  padding: 16rpx 24rpx;
  background-color: #ffffff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

.summary {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 6rpx;

  .summary-label {
    color: #606266;
    font-size: 24rpx;
  }

  .summary-value {
    color: #2c3e50;
    font-size: 34rpx;
    font-weight: 700;
  }
}

.toolbar-actions {
  display: flex;
  gap: 12rpx;
  flex-shrink: 0;
}

.toolbar-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 12rpx 22rpx;
  background: rgba(102, 126, 234, 0.08);
  border-radius: 24rpx;
  border: 2rpx solid rgba(102, 126, 234, 0.3);

  text {
    color: #667eea;
    font-size: 28rpx;
    font-weight: 600;
  }

  &.primary {
    background: #667eea;
    border-color: #667eea;

    text {
      color: #ffffff;
    }
  }
}

// 费用金额特殊样式
.info-value.cost {
  color: #f5576c;
  font-weight: 700;
}
</style>
