<script lang="ts" setup>
import { cloneDeep, isArray } from 'lodash-es'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { getCheckSubItemsByTaskId, getChecktItemsByTaskId, handleCheckTask, submitCheckLogs } from '@/api/schedule/check'
import { getTaskDetail } from '@/api/schedule/task'
import useUpload from '@/hooks/useUpload'
import anomalyPop from '../popup/anomaly.vue'

const route = useRoute()
const taskId = ref(Number(route.query.id))
const checkId = ref(Number(route.query.checkId))
const anomalyPopRef = ref<any>(null)
const popShow = ref({
  centerShow: false,
  anomalyShow: false,
})
// const popShow = ref({})
const taskInfo: any = ref({})
const checkSubItems: any = ref([])

const currentCheckList: any = ref([])
const activeArea: any = ref(0)

// 定义任务类型
interface Task {
  id: string
  type: string
  description: string
  icon?: string
  instructions: string
  examples: string[]
  images: string[]
  status: 'normal' | 'abnormal'
  isimages: boolean
  details?: {
    name: string
    status: 'normal' | 'abnormal'
  }[]
}

// 选择图片
function chooseImage(index: number) {
  // 为每个上传请求创建独立的upload实例，确保能正确处理对应的任务索引
  const { run: uploadImage } = useUpload({
    fileType: 'image',
    success: (res) => {
      console.log('上传成功', res)
      const imageUrl = res.url || ''
      if (imageUrl) {
        console.log('currentCheckList.value[index]', currentCheckList.value[index], imageUrl)
        if (!currentCheckList.value[index]?.photoUrl) {
          currentCheckList.value[index].photoUrl = []
        }
        nextTick(() => {
          currentCheckList.value[index].photoUrl.push({
            url: imageUrl,
            name: res.fileName,
          })
        })
      }
    },
    error: (err) => {
      console.error('上传失败', err)
    },
  })
  uploadImage()
}
const selectTask = ref<any>({})
const anomalyData = ref<any>({})
// 切换任务状态
async function toggleTaskStatus(task: any) {
  selectTask.value = task
  // 初始化异常数据
  console.log('task.formOperationIssue', task.formOperationIssue)
  anomalyData.value = task.formOperationIssue || {}
  popShow.value.anomalyShow = true
  await nextTick()
  let problemPhoto = cloneDeep(anomalyData.value.problemPhoto)
  if (problemPhoto && !isArray(problemPhoto)) {
    problemPhoto = problemPhoto.split(',').map((url: string, index: number) => ({
      name: url.trim(),
      url: anomalyData.value.problemPhotoUrl[index],
    }))
  }
  const data = {
    ...anomalyData.value,
    problemPhoto,
  }
  console.log('data123', data)
  anomalyPopRef.value?.updateModelData(data)
}

// 处理异常信息提交
function handleAnomalySubmitted({ checkItemId, data }: { checkItemId: number, data: any }) {
  // 在 currentCheckList 中找到对应的任务
  const taskIndex = currentCheckList.value.findIndex((item: any) => item.id === checkItemId)
  console.log('taskIndex', taskIndex)
  if (taskIndex !== -1) {
    // 在任务对象中添加标记，表明异常信息已填写
    // currentCheckList.value[taskIndex].hasAnomalyInfo = true
    // 保存提交的异常数据
    currentCheckList.value[taskIndex].formOperationIssue = data
  }

  popShow.value.anomalyShow = false
}

// 处理 dealResult 变化
function handleDealResultChange(task: any) {
  // 当用户选择异常时，自动弹出异常信息填写抽屉
  if (task.result === 2) {
    anomalyData.value = task.formOperationIssue || {}
    toggleTaskStatus(task)
  }
}

// 切换分数选择
function toggleScore(taskIndex: number, score: number | null) {
  const task = currentCheckList.value[taskIndex]
  task.score = score
  // 当分数小于 5 时，设置任务状态为异常
  if (score !== null && score < 5) {
    task.status = 'abnormal'
  }
  else {
    task.status = 'normal'
  }
}

const lastIndex = ref(0)

async function saveCheckLog({ index }: { index: number }) {
  try {
    // 获取当前数据
    const logs = []
    const items = checkSubItems.value[index]?.items || []
    currentCheckList.value.forEach((item: any, index: number) => {
      let result = 1
      if (item.dealHasScore) {
        result = (item.dealScore || 0) === item.limitScore ? 1 : 2
      }
      else {
        result = item.result || 1
      }
      const logInfo = {
        inputItem: item.inputItem || '', // 输入内容
        itemId: item.id || '', // 检查项ID
        photo: item.photoUrl?.map((photo: any) => photo.name).join(',') || '', // 照片
        result, // 检查结果1正常2异常3不适用
        score: item.dealHasScore ? item.dealScore || 0 : 0, // 分数
      }

      // 做一些判断，比如必填项
      if (item.hasPhoto === 2 && !item.photoUrl?.length) {
        throw new Error('请上传照片')
      }

      if (item.hasInput === 1 && !item.inputItem) {
        throw new Error('请输入内容')
      }

      if (logInfo.result === 2) {
      // 判断是否输入异常项
      // if (!item.dealScore) {
      //   uni.showToast({
      //     title: '请输入分数',
      //     icon: 'none',
      //   })
      //   return
      // }
      }

      logs.push(logInfo)
    })

    const res: any = await submitCheckLogs(checkId.value, logs)
    console.log('提交检查子项日志', res)
    if (res.code === 200) {
      // uni.showToast({
      //   title: '提交成功',
      //   icon: 'success',
      // })
      lastIndex.value = index
      currentCheckList.value = checkSubItems.value[index]?.items || []
    }
    else {
      uni.showToast({
        title: '提交失败',
        icon: 'none',
      })
    }
  }
  catch (error) {
    uni.showToast({
      title: error.message || '提交失败',
      icon: 'none',
    })
    console.log('lastIndex.value', lastIndex.value)
    nextTick(() => {
      activeArea.value = lastIndex.value
    })
  }
}

// 提交任务
function submitTasks() {
  saveCheckLog({ index: activeArea.value }).then(() => {
    // 提交任务
    handleCheckTask(checkId.value).then(() => {
      uni.showToast({
        title: '提交成功',
        icon: 'success',
      })
    }).catch(() => {
      uni.showToast({
        title: '提交失败',
        icon: 'none',
      })
    })
  })
}

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.items
        = checkItemsRes?.rows?.filter(
          (subItem: any) => subItem.subItemId === item.id,
        ) || []
      // 为每个任务添加 score 字段
      item.items.forEach((task: any) => {
        task.score = task.score || null
        task.photoUrl = (task.photoUrl || []).map((url: string, index: number) => ({
          url,
          name: task.photo.split(',')[index],
        }))
      })
    })
    // 更新检查项数据
    console.log('checkSubItems', checkSubItems.value)
    activeArea.value = 0
    currentCheckList.value = checkSubItems.value[0]?.items || []
  })
}

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

<template>
  <view class="task-management">
    <view class="fixed-area">
      <view class="title">
        <text class="title-text">
          {{ taskInfo.stationName || '' }}
        </text>
      </view>
      <view>
        <wd-tabs v-model="activeArea" @click="saveCheckLog">
          <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="tasks">
        <view
          v-for="(task, index) in currentCheckList"
          :key="index"
          class="task-item"
        >
          <!-- 任务描述 -->
          <view class="task-description">
            <text class="task-number">{{ +index + 1 }}.</text>
            <text class="task-text">
              {{ task.itemName }}
              <wd-icon
                v-if="task?.icon"
                :name="task?.icon"
                size="32rpx"
                @click="() => (popShow.centerShow = true)"
              />
            </text>
          </view>

          <view v-if="task.hasInput > 0" class="input-container" style="margin-right: 1rem;">
            <wd-textarea v-model="task.inputItem" :placeholder="task.inputContent || '请输入内容'" :maxlength="100" show-word-limit />
          </view>

          <!-- 操作说明 -->
          <view v-if="task.hasPhoto > 0" class="task-instructions">
            <text v-if="task.photoPrompt" class="instructions-text">
              {{ `拍照：${task.photoPrompt}` || '' }}
            </text>
            <text v-if="task.hasPhoto === 2 && !task.photoPrompt" class="instructions-text">
              <span style="color: red;">*</span>必拍
            </text>
          </view>

          <!-- 示例图片 -->
          <view v-if="task.hasPhoto > 0" class="example-images">
            <view
              v-for="(img, idx) in task.exampleImageUrl"
              :key="idx"
              class="example-image"
            >
              <image :src="img" mode="aspectFill" />
              <text class="example-text">示例</text>
            </view>
          </view>

          <!-- 图片上传区域 -->
          <view v-if="task.hasPhoto > 0 || (task?.images?.length > 0)" class="image-upload-container">
            <!-- 上传按钮 -->
            <view
              v-if="task.hasPhoto > 0"
              class="upload-btn"
              @tap="chooseImage(+index)"
            >
              <view class="btn-content">
                <text class="btn-icon">+</text>
                <text class="btn-text">拍照</text>
              </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.url" mode="aspectFill" />
              </view>
            </view>
          </view>
          <view v-if="task.checkResult === 1" style="margin-left: 1rem;">
            <wd-radio-group v-model="task.result" shape="dot" inline @change="handleDealResultChange(task)">
              <wd-radio :value="1">
                正常
              </wd-radio>
              <wd-radio :value="2">
                异常
              </wd-radio>
              <wd-radio :value="3">
                不适用
              </wd-radio>
            </wd-radio-group>
            <view v-if="task.result === 2" style="margin-top: 8rpx;">
              <text class="link-text" @tap="toggleTaskStatus(task)">{{ task.formOperationIssue ? '点击查看异常' : '点击填写异常' }}</text>
            </view>
          </view>

          <!-- 打分组件 -->
          <view v-if="[2, 3].includes(task.checkResult)" class="score-container">
            <view class="score-row">
              <view class="score-label">
                打分
              </view>
              <wd-checkbox v-model="task.dealHasScore">
                不适用
              </wd-checkbox>
              <wd-input-number v-model="task.dealScore" :min="0" :max="task.limitScore" :disabled="task.dealHasScore" />
              <view class="score-tip">
                满分为{{ task.limitScore }}分
              </view>
            </view>
            <view v-if="task.dealScore !== null && task.dealScore < task.limitScore && !task.dealHasScore" class="abnormal-link">
              <text class="link-text" @tap="toggleTaskStatus(task)">{{ task.formOperationIssue ? '点击查看异常' : '点击填写异常（未满分必填）' }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <wd-popup
      v-model="popShow.anomalyShow"
      custom-style="border-radius: 32rpx 32rpx 0 0; height: 80%;z-index: 100;"
      position="bottom"
      :safe-area-inset-bottom="true"
      closable
    >
      <anomalyPop v-if="popShow.anomalyShow" ref="anomalyPopRef" :task-id="taskId" :station-id="taskInfo.stationId" :check-item-id="selectTask.id" :anomaly-data="anomalyData.value" @anomaly-submitted="handleAnomalySubmitted" />
    </wd-popup>
    <!-- 确定按钮 -->
    <view class="confirm-btn">
      <button class="btn" @click="submitTasks">
        提交
      </button>
      <button class="btn" @click="saveCheckLog({ index: activeArea.value })">
        保存
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.task-management {
  display: flex;
  flex-direction: column;
  height: 1500rpx;
  overflow: hidden;

  // 全局链接文本样式
  .link-text {
    font-size: 24rpx;
    color: red;
    text-decoration: underline;
    cursor: pointer;
  }

  .fixed-area {
    flex-shrink: 0; // 不让它被压缩
    background-color: #fff;
    position: sticky; // 若想随外层滚就 sticky；想完全固定用 fixed 即可
    top: 0;
    z-index: 10;
  }
  .title {
    width: 100%;
    height: 128rpx;
    background-color: #4a80c3;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    padding-left: 46rpx;
  }

  .title-text {
    font-size: 36rpx;
    font-weight: 500;
    color: #fff;
  }

  // // 任务容器
  // .task-container {
  //   flex: 1;
  //   padding: 0 30rpx;

  //   .tasks {
  //     padding: 20rpx 0;
  //   }
  // }
  .task-container {
    flex: 1; // 占剩余高度
    overflow-y: auto; // 仅这里滚动
    padding: 0 30rpx 120rpx; // 为底部固定按钮留出空间
  }
  // 任务项
  .task-item {
    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 {
      margin-bottom: 20rpx;
      margin-left: 1rem;

      .instructions-text {
        font-size: 24rpx;
        color: #666;
        line-height: 36rpx;
      }
    }

    // 示例图片
    .example-images {
      display: flex;
      gap: 16rpx;
      margin-bottom: 20rpx;
      margin-left: 1rem;

      .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;
        }
      }
    }

    // 已上传图片
    .uploaded-images {
      display: flex;
      gap: 16rpx;
      margin-bottom: 20rpx;

      .uploaded-image {
        width: 140rpx;
        height: 100rpx;

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

    // 图片上传区域容器
    .image-upload-container {
      display: flex;
      gap: 16rpx;
      margin-bottom: 24rpx;
      margin-left: 1rem;
      overflow-x: auto;
      padding-bottom: 8rpx;
      white-space: nowrap;
      -webkit-overflow-scrolling: touch;

      &::-webkit-scrollbar {
        height: 4rpx;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 2rpx;
      }

      &::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 2rpx;
      }
    }

    // 上传按钮
    .upload-btn {
      width: 140rpx;
      height: 100rpx;
      border: 2rpx dashed #ccc;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      .btn-content {
        display: flex;
        flex-direction: column;
        align-items: center;

        .btn-icon {
          font-size: 40rpx;
          color: #999;
          line-height: 40rpx;
        }

        .btn-text {
          font-size: 24rpx;
          color: #999;
          margin-top: 4rpx;
        }
      }
    }

    // 已上传图片
    .uploaded-images {
      display: flex;
      gap: 16rpx;
      flex-shrink: 0;

      .uploaded-image {
        width: 140rpx;
        height: 100rpx;
        flex-shrink: 0;

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

    // 状态选择
    .status-select {
      margin-bottom: 20rpx;

      .radio-group {
        display: flex;
        gap: 40rpx;
      }
    }

    // 带详情的状态选择
    .detail-status {
      margin-bottom: 20rpx;

      .detail-name {
        font-size: 28rpx;
        color: #333;
        margin-right: 20rpx;
        // margin-bottom: 10rpx;
      }

      .radio-group {
        display: flex;
        gap: 40rpx;
      }

      .detail-items {
        margin-top: 16rpx;
        display: flex;
        flex-wrap: wrap;
        gap: 40rpx;
      }
    }

    // 单选按钮
    .radio-group {
      .radio-item {
        // margin-top: 50rpx;
        display: flex;
        align-items: center;
        gap: 8rpx;

        .radio {
          width: 32rpx;
          height: 32rpx;
          border: 2rpx solid #ccc;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;

          &.selected {
            border-color: #215acd;
            // background-color: #4a80c3;

            &::after {
              content: '';
              width: 16rpx;
              height: 16rpx;
              border-radius: 50%;
              background-color: #215acd;
            }
          }
        }

        .radio-text {
          font-size: 28rpx;
          color: #333;
        }
      }
    }

    // 打分组件
    .score-select {
      margin-bottom: 20rpx;

      .score-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 12rpx;
      }

      .score-container {
        display: flex;
        align-items: center;
        gap: 40rpx;
        margin-bottom: 16rpx;
      }

      .score-buttons {
        display: flex;
        gap: 20rpx;
      }

      .score-button {
        width: 60rpx;
        height: 60rpx;
        border: 2rpx solid #ccc;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #333;
        background-color: #fff;
        transition: all 0.2s ease;

        &.selected {
          border-color: #215acd;
          background-color: #215acd;
          color: #fff;
        }
      }

      .abnormal-link {
        margin-top: 12rpx;
      }

      .link-text {
        font-size: 24rpx;
        color: red;
        text-decoration: underline;
        cursor: pointer;
      }
    }

    // 新打分组件样式
    .score-container {
      margin-bottom: 20rpx;
      margin-left: 1rem;
      .score-row {
        display: flex;
        align-items: center;
        gap: 20rpx;
        margin-bottom: 12rpx;
      }

      .score-label {
        font-size: 28rpx;
        color: #333;
        white-space: nowrap;
      }

      .score-tip {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 12rpx;
      }

      .abnormal-link {
        margin-top: 8rpx;
      }

      .link-text {
        font-size: 24rpx;
        color: red;
        text-decoration: underline;
        cursor: pointer;
      }
    }
  }

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

    .btn {
      flex: 1;
      height: 80rpx;
      background-color: #215acd;
      color: white;
      font-size: 32rpx;
      border-radius: 12rpx;
      font-weight: 400;
      border: none;
      outline: none;
    }
  }
}
</style>
