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

import { useRoute } from 'vue-router'
import { getCheckSubItemsByTaskId, getChecktItemsByTaskId } from '@/api/schedule/check'
import { getTaskDetail } from '@/api/schedule/task'

const route = useRoute()
const taskId = ref(Number(route.query.id))
const checkId = ref(Number(route.query.checkId))
const taskInfo = ref<any>({})
const checkSubItems = ref<any[]>([])
const activeArea = ref(0)
const popupShow = ref({
  centerShow: false,
  bottomShow: false,
})

const currentCheckItem = ref<any>({})

const statics = ref({
  score: 0,
  totalScore: 0,
  totalItems: 0,
  photoCount: 0,
})

function init() {
  // 并发获取数据
  Promise.all([
    getTaskDetail(taskId.value),
    getChecktItemsByTaskId({
      checkId: checkId.value,
      pageSize: 100,
    }),
    getCheckSubItemsByTaskId({
      checkId: checkId.value,
      pageSize: 100,
    }),
  ]).then(([taskDetailRes, checkItemsRes, checkSubItemsRes]: any) => {
    if (taskDetailRes.data) {
      taskInfo.value = taskDetailRes.data
    }
    // 处理检查项数据
    checkSubItems.value = checkSubItemsRes?.rows || []
    checkSubItems.value.forEach((item: any) => {
      item.statics = {
        score: 0,
        totalScore: 0,
        totalItems: 0,
        photoCount: 0,
      }
      item.items
        = checkItemsRes?.rows?.filter(
          (subItem: any) => subItem.subItemId === item.id,
        ) || []
      // 为每个任务添加 score 字段
      item.items.forEach((task: any) => {
        if (task.checkResult === 2) {
          item.statics.score += task.score || 0
          item.statics.totalScore += (task.limitScore || 0).length
        }
        if (task?.result === 2) {
          item.statics.totalItems += 1
        }
        if (task?.hasPhoto > 0 && (!task?.photoUrl || task?.photoUrl?.length === 0)) {
          item.statics.photoCount += 1
        }
        task.score = task.score || null
        task.photoUrl = (task.photoUrl || []).map((url: string, index: number) => ({
          url,
          name: task.photo.split(',')[index],
        }))
      })
      // 计算总得分
      statics.value.score += item.statics.score
      statics.value.totalScore += item.statics.totalScore
      statics.value.totalItems += item.statics.totalItems
      statics.value.photoCount += item.statics.photoCount
    })
    // 更新检查项数据
    activeArea.value = 0
    currentCheckItem.value = checkSubItems.value[0] || {}
  })
}
const toastHtml = ref('')
function helpClick(task: any) {
  toastHtml.value = task.checkDescription
  popupShow.value.centerShow = true
}

function helpClose() {
  toastHtml.value = ''
  popupShow.value.centerShow = false
}

async function changeTab({ index }: { index: number }) {
  currentCheckItem.value = checkSubItems.value[index] || {}
}

onMounted(async () => {
  await init()
})
</script>

<template>
  <view class="task-management">
    <view class="fixed-area">
      <view class="head-Card">
        <view class="head-Card-title">
          {{ taskInfo.stationName || '' }}
        </view>
        <view class="head-Card-tab">
          <view class="head-Card-tab-item">
            <view class="tab-item-num">
              {{ statics.photoCount || 0 }}
            </view>
            <view class="tab-item-text">
              无拍照
            </view>
          </view>
          <view class="head-Card-tab-item">
            <view class="tab-item-Middle">
              <view class="tab-item-num">
                {{ statics.totalItems || 0 }}
              </view>
              <view class="tab-item-text">
                异常总数
              </view>
            </view>
          </view>
          <view class="head-Card-tab-item">
            <view class="tab-item-num">
              {{ statics.score || 0 }} / {{ statics.totalScore || 0 }}
            </view>
            <view class="tab-item-text">
              总得分
            </view>
          </view>
        </view>
      </view>
      <view>
        <wd-tabs v-model="activeArea" @click="changeTab">
          <block v-for="(item, index) in checkSubItems" :key="index">
            <wd-tab :title="`${item.name}`" :name="index" />
          </block>
        </wd-tabs>
      </view>
    </view>

    <scroll-view class="task-container" scroll-y>
      <view class="task-top-left">
        <text>
          异常数 <text style="color: #31373d; font-weight: 600">
            {{ currentCheckItem?.statics?.totalItems || 0 }}
          </text>
        </text>
        <text style="color: #31373d; font-weight: 600"> | </text>
        <text>
          得分 <text style="color: #31373d; font-weight: 600">
            {{ currentCheckItem?.statics?.score || 0 }} / {{ currentCheckItem?.statics?.totalScore || 0 }}
          </text>
        </text>
      </view>
      <view class="tasks">
        <view
          v-for="(task, index) in currentCheckItem?.items || []"
          :key="index"
          class="task-item"
        >
          <!-- 任务描述 -->
          <view class="task-description">
            <text class="task-number">{{ +index + 1 }}.</text>
            <text class="task-text">
              {{ task.tagName ? `【${task.tagName.replace(/,/g, '|')}】` : '' }}
              {{ task.itemName }}
              <wd-icon v-if="task?.checkDescription" name="help-circle" size="16px" @click="helpClick(task)" />
            </text>
          </view>
          <!-- 操作说明-图片示例 -->
          <view
            v-if="task.exampleImageUrl.length > 0"
            class="task-instructions-example"
          >
            <view v-if="task.photoPrompt" class="task-instructions">
              <text class="instructions-text">{{ `拍照：${task.photoPrompt}` }}</text>
            </view>
            <view class="example-images">
              <view
                v-for="(example, idx) in task.exampleImageUrl"
                :key="idx"
                class="example-image"
              >
                <image :src="example" mode="aspectFill" />
                <text class="example-text">示例</text>
              </view>
            </view>
          </view>
          <!-- 已上传图片 -->
          <view v-if="task?.photoUrl?.length > 0" class="uploaded-images">
            <view
              v-for="(image, idx) in task.photoUrl"
              :key="idx"
              class="uploaded-image"
            >
              <!-- <image :src="image" mode="aspectFill" /> -->
              <wd-img style="width: 100%; height: 100%" :src="image.url" :enable-preview="true" />
            </view>
          </view>
          <!-- 几号枪 -->
          <view v-if="task?.inputItem" class="whichGun">
            <text class="whichGun-text">{{ task.inputItem }}</text>
          </view>
          <!-- 状态 -->
          <view class="task-status">
            <view>
              <text class="status-text">
                整体：{{ task.result === 1 ? '正常' : task.result === 2 ? '异常' : '不适用' }}
              </text>
            </view>
          </view>
          <view v-if="task?.formOperationIssue?.id" class="anomalyDescription">
            <view class="anomalyDescription-title">
              异常描述：
            </view>
            <view class="anomalyDescription-content">
              {{ task.formOperationIssue?.problemDescription || '' }}
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <wd-popup
      v-model="popupShow.centerShow"
      custom-style="border-radius:32rpx;"
      @close="helpClose"
    >
      <view class="popup-content">
        <view style="font-size: 36rpx; font-weight: 500; color: #020917">
          说明
        </view>
        <view style="font-size: 32rpx; font-weight: 400; color: #343a45" v-html="toastHtml" />
        <view style="width: 100%">
          <button class="btn" @click="helpClose">
            我 知 道 了
          </button>
        </view>
      </view>
    </wd-popup>
    <view class="confirm-btn">
      <button class="btn" @click="submitTasks">
        评 论
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.task-management {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  overflow: hidden;
  .fixed-area {
    flex-shrink: 0;
    background-color: #fff;
    position: sticky;
    top: 0;
    z-index: 10;
  }
  .head-Card {
    width: 100%;
    height: 240rpx;
    margin-top: 2px;
    background-color: #215acd;
    // border: 1px solid red;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    // align-items: center;
    justify-content: space-around;
    box-sizing: border-box;
    // padding-left: 32rpx;
  }

  .head-Card-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #fff;
    margin-left: 32rpx;
  }
  .head-Card-tab {
    width: 99%;
    height: 128rpx;
    // border: 1px solid red;
    display: flex;
    justify-content: space-around;
    .head-Card-tab-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .tab-item-Middle {
        width: 100%;
        // height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-left: 1px solid #edeef2;
        border-right: 1px solid #edeef2;
        // 减少边框高度，使其不要占满整个tab项
        padding: 20rpx 0;
        margin: 10rpx 0;
      }
      .tab-item-num {
        font-size: 36rpx;
        color: #fff;
        font-weight: 400;
      }
      .tab-item-text {
        font-size: 24rpx;
        color: #fff;
        font-weight: 600;
      }
    }
  }
  .task-container {
    flex: 1; // 占剩余高度
    overflow-y: auto; // 仅这里滚动
    // padding: 0 30rpx;
    .task-top-left {
      margin-left: 30rpx;
      width: 250rpx;
      height: 52rpx;
      background-color: #e8f3ff;
      border-radius: 12rpx;
      margin-top: 20rpx;
      margin-bottom: 40rpx;
      padding: 10rpx;
      box-sizing: border-box;
      color: #4e5969;
      font-size: 24rpx;
      font-weight: 400;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .tasks {
    display: flex;
    flex-direction: column;
    align-items: center;
    // 任务项
    .task-item {
      width: 670rpx;
      margin-bottom: 40rpx;
      // 任务描述
      .task-description {
        display: flex;
        margin-bottom: 16rpx;
        .task-number {
          font-size: 28rpx;
          color: #333;
          margin-right: 8rpx;
          font-weight: 500;
        }

        .task-text {
          font-size: 28rpx;
          font-weight: 400;
          color: #333;
          line-height: 44rpx;
        }
      }

      .task-instructions-example {
        width: 100%;
        background-color: #f5f5f5;
        padding: 10rpx;
        box-sizing: border-box;
        // 操作说明
        .task-instructions {
          margin-bottom: 20rpx;

          .instructions-text {
            font-size: 24rpx;
            color: #666;
            line-height: 36rpx;
          }
        }
        // 示例图片
        .example-images {
          display: flex;
          gap: 16rpx;
          margin-bottom: 20rpx;

          .example-image {
            width: 140rpx;
            height: 100rpx;
            position: relative;

            image {
              width: 100%;
              height: 100%;
              border-radius: 8rpx;
            }

            .example-text {
              position: absolute;
              bottom: 0;
              left: 0;
              right: 0;
              background-color: rgba(0, 0, 0, 0.5);
              color: white;
              font-size: 20rpx;
              text-align: center;
              padding: 4rpx 0;
              border-radius: 0 0 8rpx 8rpx;
            }
          }
        }
      }
      .whichGun {
        width: 100%;
        height: 96rpx;
        background-color: #f5f5f5;
        display: flex;
        align-items: center;
        gap: 10rpx;
        padding-left: 10rpx;
        padding-right: 10rpx;
        box-sizing: border-box;
        margin-bottom: 10rpx;
        border-radius: 20rpx;
        .whichGun-text {
          font-size: 28rpx;
          color: #4e5969;
          font-weight: 500;
        }
      }
      .task-status {
        width: 100%;
        // background-color: red;
        display: flex;
        justify-content: flex-end;
        margin-bottom: 10rpx;
        .status-text {
          font-size: 32rpx;
          font-weight: 500;
          color: #31373d;
        }
      }
      .anomalyDescription {
        width: 100%;
        border-bottom: 1px solid #eeeeee;
        font-size: 28rpx;
        padding-bottom: 40rpx;
        .anomalyDescription-title {
          font-weight: 500;
          color: #31373d;
        }
        .anomalyDescription-content {
          font-weight: 400;
          color: #4e5969;
        }
      }
      .uploaded-images {
        width: 100%;
        display: flex;
        gap: 16rpx;
        margin-bottom: 20rpx;
        overflow-x: auto;
        padding-bottom: 10rpx;
        .uploaded-image {
          flex-shrink: 0;
          width: 150rpx;
          height: 100rpx;
          image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }
        }
      }
    }
  }

  // 确定按钮
  .confirm-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    background-color: white;
    border-top: 1rpx solid #eee;
    z-index: 100;

    .btn {
      width: 100%;
      height: 80rpx;
      background-color: #215acd;
      color: white;
      font-size: 32rpx;
      border-radius: 12rpx;
      font-weight: 400;
      border: none;
      outline: none;
    }
  }
}

.custom-txt {
  width: 400rpx;
  height: 400rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 32rpx;
}
.popup-content {
  width: 600rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx;
  box-sizing: border-box;
  gap: 40rpx;
  .btn {
    width: 100%;
    height: 80rpx;
    background-color: #215acd;
    color: white;
    font-size: 32rpx;
    border-radius: 12rpx;
    font-weight: 400;
    border: none;
    outline: none;
  }
}
</style>
