<template>
  <scroll-view scroll-y class="page">
    <!-- 个人信息卡片 -->
    <view class="profile card">
      <image class="avatar" src="/static/logo.png" />
      <view class="info not-login-in" v-if="!isLoggedIn" @tap="goLogin">
        <text class="name">未登录</text>
        <text class="sub">点击登录/注册</text>
      </view>
      <view class="info" v-else>
        <text class="name">{{ staff?.user_name || staff?.name || '已登录' }}</text>
        <text class="sub">类型：{{ userTypeText }}</text>
        <text class="sub">角色：{{ staff?.role_name || '-' }}</text>
        <text class="sub" v-if="staff?.job_no">工号：{{ staff?.job_no }}</text>
        <view class="actions">
          <button class="btn btn-danger" @tap="logout">退出登录</button>
        </view>
      </view>
    </view>

    <!-- 我的任务标题 -->
    <view class="section-title">
      <text>我的任务</text>
    </view>

    <!-- 任务列表 -->
    <view class="task-list">
      <view v-if="loading" class="empty">加载中...</view>
      <view v-else-if="!taskList.length" class="empty">暂无任务</view>
      <view v-else class="list-wrap">
        <view class="task card" v-for="(task, idx) in taskList" :key="task.id || idx">
          <view class="row">
            <text class="label">申请时间：</text>
            <text class="value">{{ fmt(task.decTime) }}</text>
          </view>
          <view class="row">
            <text class="label">申请科室：</text>
            <text class="value">{{ fmt(task.decDeptName) }}</text>
          </view>
          <view class="row two-cols">
            <view class="col">
              <text class="label">申请床号：</text>
              <text class="value">{{ fmt(task.decBedNo) }}</text>
            </view>
            <view class="col">
              <text class="label">运送工具：</text>
              <text class="value">{{ fmt(task.carryingtoolsName) }}</text>
            </view>
          </view>
          <view class="row two-cols">
            <view class="col">
              <text class="label">是否预约：</text>
              <text class="value">{{ task.ordered ? '预约' : '立即' }}</text>
            </view>
            <view class="col" v-if="task.ordered">
              <text class="label">预约时间：</text>
              <text class="value">{{ fmt(task.orderedDatetime) }}</text>
            </view>
          </view>
          <view class="row">
            <text class="label">运单状态：</text>
            <text class="value">{{ fmt(task.tasksheetStateName) }}</text>
          </view>
          <view class="row">
            <text class="label">接单时间：</text>
            <text class="value">{{ fmt(task.recieveTime) }}</text>
          </view>
          <view class="row">
            <text class="label">接单电话：</text>
            <text class="value">{{ fmt(task.undertakePersonTel) }}</text>
          </view>
          <view class="row">
            <text class="label">启运时间：</text>
            <text class="value">{{ fmt(task.transportTime) }}</text>
          </view>
          <view class="row">
            <text class="label">结运时间：</text>
            <text class="value">{{ fmt(task.finishTime) }}</text>
          </view>
          <view class="row">
            <text class="label">服务费用：</text>
            <text class="value">{{ fmt(task.serviceFee) }}</text>
          </view>
          <view class="row" v-if="task.tasksheetState === '06'">
            <text class="label">评价等级：</text>
            <text class="value">{{ fmt(task.satisfactionEvaluationName) }}</text>
          </view>
          <view class="actions-inline">
            <button class="btn btn-text red" v-if="task.tasksheetState === '03' && task.undertakePersonTel" @tap="onPhoneCall(idx)">电话</button>
            <button class="btn btn-text blue" v-if="task.tasksheetState === '05'" @tap="onEvaluate(idx)">评价</button>
            <button class="btn btn-text yellow" @tap="dispNewDetail(idx)">详情</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 详情弹层 -->
    <view v-if="isDispDetail" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">当前运单信息</text>
          <text class="modal-close" @tap="isDispDetail = false">×</text>
        </view>
        <scroll-view scroll-y class="modal-body">
          <view class="row"><text class="label">申请时间：</text><text class="value">{{ fmt(currentTask?.decTime) }}</text></view>
          <view class="row"><text class="label">申请科室：</text><text class="value">{{ fmt(currentTask?.decDeptName) }}</text></view>
          <view class="row"><text class="label">申请床号：</text><text class="value">{{ fmt(currentTask?.decBedNo) }}</text></view>
          <view class="row"><text class="label">申请电话：</text><text class="value">{{ fmt(currentTask?.decTel) }}</text></view>
          <view class="row"><text class="label">运输工具：</text><text class="value">{{ fmt(currentTask?.carryingtoolsName) }}</text></view>
          <view class="row"><text class="label">工具数量：</text><text class="value">{{ fmt(currentTask?.carryingtoolsCount) }}</text></view>
          <view class="row"><text class="label">是否预约：</text><text class="value">{{ currentTask?.ordered ? '预约' : '立即' }}</text></view>
          <view class="row" v-if="currentTask?.ordered"><text class="label">预约时间：</text><text class="value">{{ fmt(currentTask?.orderedDatetime) }}</text></view>
          <view class="row"><text class="label">支付方式：</text><text class="value">{{ fmt(currentTask?.paymentMethodName) }}</text></view>
          <view class="row"><text class="label">代申请部门：</text><text class="value">{{ fmt(currentTask?.needcontactDeptName) }}</text></view>
          <view class="row"><text class="label">代申请电话：</text><text class="value">{{ fmt(currentTask?.needcontactTel) }}</text></view>
          <view class="row"><text class="label">运单状态：</text><text class="value">{{ fmt(currentTask?.tasksheetStateName) }}</text></view>
          <view class="row"><text class="label">接单骑手：</text><text class="value">{{ fmt(currentTask?.undertakePersonName) }}</text></view>
          <view class="row"><text class="label">骑手电话：</text><text class="value">{{ fmt(currentTask?.undertakePersonTel) }}</text></view>
          <view class="row"><text class="label">接单时间：</text><text class="value">{{ fmt(currentTask?.recieveTime) }}</text></view>
          <view class="row"><text class="label">启运时间：</text><text class="value">{{ fmt(currentTask?.transportTime) }}</text></view>
          <view class="row"><text class="label">结运时间：</text><text class="value">{{ fmt(currentTask?.finishTime) }}</text></view>
          <view class="row"><text class="label">服务费用：</text><text class="value">{{ fmt(currentTask?.serviceFee) }}</text></view>
          <view class="row" v-if="currentTask?.tasksheetState === '06'"><text class="label">评价等级：</text><text class="value">{{ fmt(currentTask?.satisfactionEvaluationName) }}</text></view>
          <view class="row" v-if="currentTask?.tasksheetState === '06'"><text class="label">评价意见：</text><text class="value">{{ fmt(currentTask?.satisfactionContent) }}</text></view>
        </scroll-view>
        <view class="modal-footer">
          <button class="btn" @tap="isDispDetail = false">关闭</button>
        </view>
      </view>
    </view>

    <!-- 评价弹层 -->
    <view v-if="isEvaluate" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">请对担架运送服务进行评价</text>
          <text class="modal-close" @tap="cancelEvaluate">×</text>
        </view>
        <view class="modal-body">
          <view class="form-row">
            <text class="label">服务评价：</text>
            <view class="radio-group">
              <label v-for="item in satisfactionEvaluationDatas" :key="item.value" class="radio-item">
                <radio :value="item.value" :checked="evaluateRequest.satisfactionEvaluation === item.value" @tap="evaluateRequest.satisfactionEvaluation = item.value" />
                <text>{{ item.label }}</text>
              </label>
            </view>
          </view>
          <view class="form-row">
            <text class="label">意见：</text>
            <textarea class="textarea" maxlength="200" placeholder="请输入评价信息" v-model="evaluateRequest.satisfactionContent" />
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn btn-primary" @tap="submitEvaluate">评价</button>
          <button class="btn" @tap="cancelEvaluate">取消</button>
        </view>
      </view>
    </view>
  </scroll-view>
  
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
// @ts-ignore JS模块无类型声明
import queryService from '@/service/queryService.js'
// @ts-ignore JS模块无类型声明
import getService from '@/service/getService.js'
// @ts-ignore JS模块无类型声明
import config from '@/config.js'

type Task = Record<string, any>

const isLoggedIn = ref(false)
const staff = ref<any | null>(null)
const isWeixin = ref(false)
const taskList = ref<Task[]>([])
const loading = ref(false)

const isDispDetail = ref(false)
const currentTask = ref<Task | null>(null)

const isEvaluate = ref(false)
const evaluateRequest = ref<{ id: string | number | null; satisfactionContent: string | null; satisfactionEvaluation: string }>({
  id: null,
  satisfactionContent: null,
  satisfactionEvaluation: '04'
})
const satisfactionEvaluationDatas = [
  { value: '03', label: '不满意' },
  { value: '04', label: '满意' },
  { value: '05', label: '非常满意' }
]

const userTypeText = computed(() => {
  const t = staff.value?.user_type
  if (!t) return '非注册用户'
  if (t === 1) return '系统用户'
  if (t === 2) return '医院职工'
  if (t === 3) return '物业员工'
  return '非注册用户'
})

function fmt(v: any) {
  return v === null || v === undefined || v === '' ? '' : String(v)
}

function goLogin() {
  uni.navigateTo({ url: '/pages/login/index' })
}

function logout() {
  uni.setStorageSync('staff', null)
  uni.setStorageSync('token', null)
  staff.value = null
  isLoggedIn.value = false
  taskList.value = []
  uni.showToast({ title: '已退出登录', icon: 'none' })
}

async function initEnv() {
  // 平台标识
  // @ts-ignore
  isWeixin.value = process?.env?.VUE_APP_PLATFORM === 'mp-weixin'
  if (isWeixin.value) {
    // 确保 openid
    const openid = uni.getStorageSync('openid')
    if (!openid) {
      try { await getService.getOpenId?.() } catch {}
    }
  }
}

async function loadTasks() {
  loading.value = true
  try {
    const staffId = staff.value?.id
    let openid: string | null = null
    if (!staffId) {
      openid = uni.getStorageSync('openid') || (config?.defaultOpenId || null)
    }
    const data = {
      decTel: null,
      needcontactTel: null,
      openid: staffId ? staffId : openid,
      decendDatetime: null,
      decstartDatetime: null,
      index: 0,
      page: 0,
      size: 0,
      sort: null,
      tasksheetStates: null
    }
    const res = await queryService.queryStretcherTask(data)
    if (res?.data?.code === 0) {
      taskList.value = res.data.data || []
    } else {
      taskList.value = []
    }
  } catch (e) {
    taskList.value = []
    console.warn('加载任务失败：', e)
  } finally {
    loading.value = false
  }
}

function dispNewDetail(index: number) {
  currentTask.value = taskList.value[index] || null
  isDispDetail.value = true
}

function onPhoneCall(index: number) {
  const t = taskList.value[index]
  const tel = t?.undertakePersonTel
  if (!tel) {
    return uni.showToast({ title: '暂无联系电话', icon: 'none' })
  }
  uni.makePhoneCall({
    phoneNumber: tel,
    success() { console.log('拨打成功') },
    fail() { uni.showToast({ title: '拨打失败', icon: 'error', duration: 3000 }) }
  })
}

function onEvaluate(index: number) {
  currentTask.value = taskList.value[index] || null
  if (!currentTask.value) return
  evaluateRequest.value.id = currentTask.value.id || null
  evaluateRequest.value.satisfactionContent = null
  evaluateRequest.value.satisfactionEvaluation = '04'
  isEvaluate.value = true
}

async function submitEvaluate() {
  if (!currentTask.value || !evaluateRequest.value.id) {
    return uni.showToast({ title: '无法提交评价', icon: 'none' })
  }
  try {
    const res = await queryService.evaluateStretcherTransport(evaluateRequest.value)
    if (res?.data?.code === 0) {
      uni.showToast({ title: '评价提交成功', icon: 'none' })
      isEvaluate.value = false
      // 重置
      evaluateRequest.value = { id: null, satisfactionContent: null, satisfactionEvaluation: '04' }
      // 刷新列表
      await loadTasks()
    } else {
      uni.showToast({ title: '评价提交失败', icon: 'error', duration: 3000 })
    }
  } catch (e) {
    uni.showToast({ title: '评价提交失败', icon: 'error', duration: 3000 })
  }
}

function cancelEvaluate() {
  isEvaluate.value = false
  evaluateRequest.value = { id: null, satisfactionContent: null, satisfactionEvaluation: '04' }
}

function sync() {
  staff.value = uni.getStorageSync('staff') || null
  isLoggedIn.value = !!staff.value
}

onMounted(async () => {
  sync()
  await initEnv()
  await loadTasks()
})

onShow(async () => {
  sync()
  await loadTasks()
})
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f7fb;
}
.card {
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.06);
}
.profile {
  margin: 32rpx;
  padding: 32rpx;
  display: flex;
  align-items: center;
  gap: 24rpx;
}
.avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
}
.info { display: flex; flex-direction: column; }
.name { font-size: 32rpx; color: #333; }
.sub { font-size: 24rpx; color: #999; }
.actions { margin-top: 16rpx; }
.btn { padding: 12rpx 20rpx; background: #3a5ddd; color: #fff; border-radius: 10rpx; font-size: 24rpx; }
.btn-danger { background: #ef5350; }
.btn-primary { background: #3a5ddd; }
.btn-text { background: transparent; color: #3a5ddd; padding: 6rpx 10rpx; }
.btn-text.red { color: #ef5350; }
.btn-text.blue { color: #3a5ddd; }
.btn-text.yellow { color: #f39c12; }

.section-title { padding: 0 32rpx 12rpx; color: #666; font-size: 26rpx; }
.task-list { padding: 0 32rpx 32rpx; }
.empty { text-align: center; color: #9a9aa0; padding: 40rpx 0; }
.list-wrap { display: flex; flex-direction: column; gap: 20rpx; }
.task { padding: 20rpx; }
.row { display: flex; align-items: center; padding: 8rpx 0; flex-wrap: wrap; }
.two-cols { justify-content: space-between; }
.two-cols .col { width: 48%; display: flex; }
.label { color: #666; font-size: 24rpx; }
.value { color: #333; font-size: 26rpx; }
.actions-inline { display: flex; justify-content: flex-end; gap: 16rpx; padding-top: 8rpx; }
.actions-inline .btn{ flex: 1;}

/* 简易弹层样式 */
.modal { position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.45); display: flex; align-items: center; justify-content: center; z-index: 999; }
.modal-content { width: 86%; max-height: 76vh; background: #fff; border-radius: 16rpx; overflow: hidden; display: flex; flex-direction: column; }
.modal-header { padding: 20rpx 24rpx; display: flex; align-items: center; justify-content: space-between; border-bottom: 1rpx solid #eee; }
.modal-title { font-size: 30rpx; color: #222; font-weight: 600; }
.modal-close { font-size: 40rpx; color: #999; }
.modal-body { padding: 16rpx 24rpx; max-height: 60vh; }
.modal-footer { padding: 16rpx 24rpx; display: flex; justify-content: flex-end; gap: 16rpx; border-top: 1rpx solid #eee; }
.modal-footer .btn { flex: 1; }
.form-row { margin-bottom: 20rpx; }
.radio-group { display: flex; gap: 24rpx; flex-wrap: wrap; }
.radio-item { display: flex; align-items: center; gap: 8rpx; }
.textarea { width: 100%; min-height: 160rpx; border: 1rpx solid #e5e6eb; border-radius: 12rpx; padding: 12rpx; font-size: 26rpx; }
</style>
