<script setup lang="ts">
import dayjs from 'dayjs'
import { keyBy } from 'lodash-es'
import { storeToRefs } from 'pinia'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage, useToast } from 'wot-design-uni'
import { closeTask, confirmDoneTask, getTaskDetail, setPlanTime, transferTask } from '@/api/schedule/task'
import { getAllUsers } from '@/api/system/users'

import AttachmentList from '@/components/AttachmentList.vue'
import { useUserStore } from '@/store'
import { authStatusOptions, taskLevelOptions, taskStatusOptions } from '@/utils/dicts'

const userStore = useUserStore()

const { userInfo } = storeToRefs(userStore)

const wotMessage = useMessage()
const toast = useToast()

// 定义页面配置，注册路由
definePage({
  excludeLoginPath: true,
})

// 状态管理
const isExpanded = ref(false)
const router = useRouter()

const route = useRoute()
const taskId = ref(Number(route.query.id))

const taskInfo: any = ref({})
const taskOther: any = ref({})
const taskResult: any = ref({})

// 转交功能相关
const users = ref<any[]>([])
const value = ref<string[]>([])
const customShow = ref<string>('')

// 计划时间修改相关
const planTimeValue = ref('')

// 切换更多内容显示/隐藏
function toggleMore() {
  isExpanded.value = !isExpanded.value
}

async function dealConfirmTaskEvent() {
// 二次弹框确认
  wotMessage.confirm({
    msg: `确认完成任务 ${taskInfo.value.taskName} 吗？`,
    title: '确认完成',
  }).then(async () => {
    try {
      await confirmDoneTask(taskInfo.value.id || 0)

      toast.success('确认完成任务成功')
      await init()
    }
    catch {
      toast.error('操作失败')
    }
  }).catch(() => {
    return
  })
}

// 查看详情按钮点击事件
async function dealTaskEvent() {
  // 根据任务类型进行判断
  let params: any = {}
  let isModelPage = false
  switch (taskInfo.value.formType) {
    case 'inspection': {
      uni.navigateTo({
        url: `/pages/schedule/details/deal/inspection?id=${taskId.value}&checkId=${taskInfo.value.taskList[0].id}`,
      })
      return
    }
    case 'photo': {
      uni.navigateTo({
        url: `/pages/schedule/details/deal/photo?id=${taskInfo.value.taskList?.[0]?.id}`,
      })
      return
    }
    case 'confirm': {
      await dealConfirmTaskEvent()

      return
    }
    case 'form': {
      if (
        ['annualExamination_task', 'replacement_task'].includes(
          taskInfo.value.subFormType,
        )
      ) {
        try {
          // await dealAnnualExaminationTask()
        }
        catch {
          // ElMessage.error('处理任务失败')
        }
        return
      }

      params = {
        taskId: taskInfo.value.taskList?.[0]?.id || '',
        taskName: taskInfo.value.taskName,
        taskList: taskInfo.value.taskList || [],
        remark: taskResult.value.content,
        stationId: taskInfo.value.stationId || 0,
        subFormType: taskInfo.value.subFormType,
        attachmentUrl: taskResult.value.images,
      }

      if (
        [
          'ambulance_check',
          'emergency_protection_monthly_check',
          'filter_maintenance',
          'fire_extinguisher_check',
        ].includes(taskInfo.value.subFormType)
      ) {
        isModelPage = true
      }

      break
    }
    case 'upload': {
      uni.navigateTo({
        url: `/pages/schedule/details/deal/upload?id=${taskInfo.value.taskList?.[0]?.id}`,
      })
      return
    }
    default: {
      // return ElMessage.error('当前任务无法处理')
    }
  }
  // if (isModelPage) {
  //   pageModalApi.open()
  // }
  // else {
  //   dealDrawerApi.setData(params).open()
  // }
}
// 查看详情按钮点击事件2
function viewDetails2() {
  uni.navigateTo({
    url: '/pages/schedule/details/taskmanagement/index2',
  })
}
function viewDetails3() {
  uni.navigateTo({
    url: '/pages/schedule/details/taskdetails/index',
  })
}

// 获取用户列表
async function getUserList() {
  console.log('调用getAllUsers时的stationId:', taskInfo.value.stationId)
  const res: any = await getAllUsers({
    pageNum: 10000,
    stationId: taskInfo.value.stationId,
  })
  if (res.code === 200) {
    users.value = res.data.map((item: any) => ({
      label: item.nickName,
      value: item.userId,
    }))
  }
}

// 选择器确认事件
function handleTransferTask({ value, selectedItems }: any) {
  console.log('value:', value[0], taskInfo.value.executorId)
  if (value.length === 0) {
    toast.error('请选择执行人')
    return
  }

  if (value[0] === taskInfo.value.executorId) {
    toast.error('不能将任务转交给当前执行人')
    console.log('不能将任务转交给当前执行人', toast)

    return
  }

  wotMessage.confirm({
    msg: `确认将任务 ${taskInfo.value.taskName} 转交给 ${selectedItems.map((item: any) => item.label).join(', ')} 吗？`,
    title: '确认转交',
  }).then(async () => {
    try {
      const res: any = await transferTask({
        id: taskInfo.value.id || 0,
        executorId: value[0],
      })
      if (res.code !== 200) {
        toast.error(res.msg || '操作失败')
        return
      }

      toast.success('转交任务成功')
      await init()
    }
    catch {
      toast.error('操作失败')
    }
  }).catch(() => {
    return
  })
}

/**
 * 获取任务时间
 * @returns 任务时间字符串
 */
function getTaskTime() {
  return `${dayjs(taskInfo.value.startTime).format('MM-DD HH:mm')}~${dayjs(taskInfo.value.endTime).format('MM-DD HH:mm')}`
}

/**
 * 下载文件
 * @param file 文件对象或链接
 * @param fileName 文件名
 */
function downloadFile(file: any, fileName: string) {
  // 这里实现文件下载逻辑
  console.log('downloadFile:', file, fileName)
}

const buttons = ref({
  deal: false,
  transfer: false,
  close: false,
})

async function init() {
  const res: any = await getTaskDetail(taskId.value)
  taskInfo.value = res.data || {}
  if (!taskInfo.value.status) {
    taskInfo.value.status = 0
  }
  console.log(userInfo.value)

  if (taskInfo.value.status === 1) {
    const userId = Number(userInfo.value?.user?.userId)
    const isExecutor = taskInfo.value.executorId === userId
    const isCreator = userInfo.value?.user?.username === taskInfo.value.createBy
    const isHeadquarters = userInfo.value?.user?.post?.type === '"headquarters"'
    const isMobileTask = [].includes(taskInfo.value.formType)

    if (isExecutor && !isMobileTask) {
      buttons.value.deal = true
    }

    if (isCreator || isHeadquarters || isExecutor) {
      if (taskInfo.value.executorId !== userId) {
        buttons.value.close = true
      }

      if (taskInfo.value.taskTemplate?.isMust === 0) {
        buttons.value.close = true
      }

      if (taskInfo.value.authStatus === 0 && taskInfo.value.isLicensable) {
        buttons.value.transfer = true
      }
    }
  }

  // 假设从接口返回数据中获取taskOther和taskResult
  taskOther.value.taskTypeName = taskInfo.value?.formTypeName || '-'

  if (!taskInfo.value.executorName && taskInfo.value.taskList?.length) {
    taskInfo.value.executorName = taskInfo.value.taskList[0].executorName
  }

  if (taskInfo.value.formType === 'photo') {
    const result = taskInfo.value?.taskList?.[0] || {}
    if (result.remark) {
      taskResult.value.content = result.remark
    }
    if (result?.attachmentUrl?.length) {
      taskResult.value.images = result.attachmentUrl
    }
  }
  else if (taskInfo.value.formType === 'upload') {
    // attachmentUrl
    const result = taskInfo.value?.taskList?.[0] || {}
    if (result.remark) {
      taskResult.value.content = result.remark
    }
    if (result?.attachmentUrl?.length) {
      taskResult.value.files = result.attachmentUrl
      taskResult.value.fileNames = result.attachmentName.split(',')
    }
  }
  else {
    // taskResult.value = taskInfo.value?.taskList?.[0] || {};
  }

  if (taskInfo.value?.taskTemplate) {
    taskOther.value.taskFrequencyName
      = taskInfo.value?.taskTemplate?.taskFrequencyName || '-'
  }

  // 获取用户列表
  if (taskInfo.value.stationId) {
    await getUserList()
  }
}

// 状态标签配置
const statusConfig: any = keyBy(taskStatusOptions, 'value')

// 优先级标签配置
const priorityConfig: any = keyBy(taskLevelOptions, 'value')

// 授权状态标签配置
const authStatusConfig: any = keyBy(authStatusOptions, 'value')

function goDetail() {
  uni.navigateTo({
    url: `/pages/schedule/details/detail/inspection?id=${taskId.value}&checkId=${taskInfo.value.taskList[0].id}`,
  })
}

/**
 * 关闭任务按钮点击事件
 */
async function closeTaskEvent() {
  // 二次弹框确认
  wotMessage.confirm({
    msg: `确认关闭任务 ${taskInfo.value.taskName} 吗？`,
    title: '确认关闭',
  }).then(async () => {
    try {
      await closeTask({
        id: taskInfo.value.id || 0,
      })

      toast.success('关闭任务成功')
      await init()
    }
    catch {
      toast.error('操作失败')
    }
  }).catch(() => {
    return
  })
}

/**
 * 处理计划时间变更
 * @param value 选中的时间值
 */
async function handlePlanTimeChange({ value }: any) {
  console.log('选择的计划时间:', value, new Date(taskInfo.value.startTime).getTime(), new Date(taskInfo.value.endTime).getTime())

  // 判断时间比如大于任务开始时间，小于任务结束时间
  if (value < new Date(taskInfo.value.startTime).getTime() || value > new Date(taskInfo.value.endTime).getTime()) {
    toast.error('计划时间必须在任务开始时间和结束时间之间')
    return
  }

  // 这里可以添加更新计划时间的API调用
  try {
    const res: any = await setPlanTime(taskInfo.value.id || 0, {
      planTime: dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
    })
    if (res.code !== 200) {
      toast.error(res.msg || '操作失败')
      return
    }
    toast.success('计划时间修改成功')
    // 重新初始化任务信息
    init()
  }
  catch {
    toast.error('操作失败')
    return
  }
}

onShow(async () => {
  await init()
})

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

<template>
  <view class="details-box">
    <!-- 标题区域 -->
    <view class="details-box-title">
      <view class="details-box-title-text">
        {{ taskInfo.taskName || '任务详情' }}
      </view>
    </view>

    <!-- 标签区域 -->
    <view class="tags-box">
      <view class="tag">
        {{ priorityConfig[taskInfo.level]?.label || taskInfo.level }}
      </view>

      <view class="tag">
        {{ statusConfig[`${taskInfo.status || 0}`]?.label || taskInfo.status }}
      </view>
      <view class="tag">
        {{ authStatusConfig[taskInfo.authStatus || 0]?.label || taskInfo.authStatus }}
      </view>
    </view>

    <!-- 任务描述 -->
    <view class="section">
      <view class="section-title">
        任务描述
      </view>
      <view class="task-description" v-html="taskInfo.description || '暂无'" />
    </view>

    <!-- 标准指引 -->
    <view class="section">
      <view class="section-title">
        基础信息
      </view>
      <view class="standard-guide">
        <view class="guide-item">
          <view class="guide-label">
            场站
          </view>
          <view class="guide-value">
            {{ taskInfo.stationName || '-' }}
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            标准指引
          </view>
          <view class="guide-value">
            {{ taskInfo.standardGuide || '-' }}
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            执行人
          </view>
          <view class="guide-value flex items-center justify-between">
            {{ taskInfo.executorName || '-' }}
            <wd-select-picker
              v-model="value"
              title="选择转交人"
              filterable :max="1" use-default-slot :columns="users" style="z-index:101" @confirm="handleTransferTask"
            >
              <wd-button v-if="buttons.transfer" type="text">
                转交
              </wd-button>
            </wd-select-picker>
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            计划时间
          </view>
          <view v-if="buttons.deal" class="guide-value flex items-center justify-between">
            {{ taskInfo.displayDate || '-' }}
            <wd-datetime-picker
              v-model="planTimeValue"
              type="datetime"
              title="选择计划时间"
              :min-date="new Date().getTime()"
              :max-date="new Date(taskInfo.endTime).getTime()"
              @confirm="handlePlanTimeChange"
            >
              <wd-button type="text">
                修改
              </wd-button>
            </wd-datetime-picker>
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            创建
          </view>
          <view class="guide-value">
            {{ taskInfo.createBy || '' }}
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            任务类型
          </view>
          <view class="guide-value">
            {{ taskInfo.subFormTypeName || taskOther.taskTypeName || '-' }}
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            任务负责人
          </view>
          <view class="guide-value">
            {{ taskInfo.taskLeaderName || '-' }}
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            任务频率
          </view>
          <view class="guide-value">
            {{ taskOther.taskFrequencyName || '-' }}
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            任务时间
          </view>
          <view class="guide-value">
            {{ getTaskTime() || '-' }}
          </view>
        </view>

        <view v-if="taskInfo.descriptionFilesUrl && taskInfo.descriptionFilesUrl.length > 0" class="guide-item attachment-guide-item">
          <view class="guide-label">
            详情附件
          </view>
          <view class="guide-value">
            <!-- 使用附件列表组件显示附件 -->
            <AttachmentList
              :files="taskInfo.descriptionFilesUrl"
              :size="30"
            />
          </view>
        </view>
      </view>
    </view>

    <view v-if="taskInfo.status === 3" class="section">
      <view class="section-title">
        处理结果
      </view>
      <view class="standard-guide">
        <view v-if="taskResult.handleContent || taskInfo.cancelReason" class="guide-item">
          <view class="guide-label">
            处理情况
          </view>
          <view class="guide-value">
            {{ taskResult.handleContent || taskInfo.cancelReason || '' }}
          </view>
        </view>
        <view class="guide-item">
          <view class="guide-label">
            处理时间
          </view>
          <view class="guide-value">
            {{ taskInfo.completeTime || taskInfo.cancelTime || '-' }}
          </view>
        </view>
        <view v-if="taskResult.files && taskResult.files.length > 0" class="guide-item attachment-guide-item">
          <view class="guide-label">
            处理附件
          </view>
          <view class="guide-value">
            <!-- 使用附件列表组件显示附件 -->
            <AttachmentList
              :files="taskResult.files"
              :file-names="taskResult.fileNames"
              :size="30"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 查看更多 -->
    <!-- <view class="more-btn" @tap="toggleMore">
      <text class="arrow">点击查看更多</text>
      <wd-icon
        class="arrow"
        :name="isExpanded ? 'arrow-up' : 'arrow-down'"
        size="20px"
      />
    </view> -->

    <!-- 更多内容（默认隐藏） -->
    <view v-if="isExpanded" class="more-content">
      <view class="section">
        <view class="section-title">
          注意事项
        </view>
        <view class="notice-content">
          <view class="notice-item">
            • 巡视过程中请注意安全，佩戴好防护装备
          </view>
          <view class="notice-item">
            • 发现异常情况请及时记录并上报
          </view>
          <view class="notice-item">
            • 确保所有检查项目都已完成并签字确认
          </view>
        </view>
      </view>
    </view>

    <!-- 按钮容器 -->
    <view class="btn-container">
      <!-- 关闭任务按钮 -->
      <wd-button
        v-if="buttons.close"
        type="error"
        class="close-btn"
        @click="closeTaskEvent"
      >
        关闭任务
      </wd-button>
      <!-- 处理任务按钮 -->
      <wd-button
        v-if="buttons.deal"
        type="primary"
        class="deal-btn"
        @click="dealTaskEvent"
      >
        处理任务
      </wd-button>
    </view>

    <!-- 查看详情按钮 -->
    <view class="view-detail-container">
      <wd-button
        v-if="[3].includes(taskInfo.status)"
        type="primary"
        class="view-detail-btn"
        @click="goDetail"
      >
        查看详情
      </wd-button>
    </view>
    <!-- <view class="detail-btn" @tap="viewDetails2">
      <text>查 看 详 情2</text>
    </view>
    <view class="detail-btn" @tap="viewDetails3">
      <text>查 看 详 情3</text>
    </view> -->
    <wd-message-box />
    <wd-toast />
  </view>
</template>

<style lang="scss" scoped>
.details-box {
  display: flex;
  flex-direction: column;
  padding: 30rpx 24rpx 160rpx;
  background-color: #ffffff;

  .details-box-title {
    margin-bottom: 24rpx;

    .details-box-title-text {
      font-size: 48rpx;
      font-weight: 500;
      color: #31373d;
    }
  }

  // 标签样式
  .tags-box {
    display: flex;
    gap: 12rpx;
    margin-bottom: 24rpx;

    .tag {
      padding: 8rpx 16rpx;
      border-radius: 14rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: #215acd;
      background-color: #e8f3ff;
    }
  }

  // 通用区块样式
  .section {
    margin-bottom: 32rpx;

    .section-title {
      font-size: 36rpx;
      font-weight: 500;
      color: #31373d;
      margin-bottom: 20rpx;
    }
  }

  // 任务描述样式
  .task-description {
    padding: 0 0 24rpx 0;
    border-bottom: 1rpx solid #e5e5e5;

    // 针对HTML内容的样式
    & :deep(ol),
    & :deep(ul) {
      padding-left: 32rpx;
      margin: 0;
    }

    & :deep(li) {
      font-size: 28rpx;
      font-weight: 400;
      color: #31373d;
      line-height: 52rpx;
      margin-bottom: 8rpx;
    }

    & :deep(p) {
      font-size: 28rpx;
      font-weight: 400;
      color: #31373d;
      line-height: 52rpx;
      margin: 0 0 12rpx 0;
    }
  }

  // 标准指引样式
  .standard-guide {
    .guide-item {
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .guide-label {
        width: 160rpx;
        font-size: 28rpx;
        color: #6c757d;
        font-weight: 400;
        line-height: 52rpx;
      }

      .guide-value {
        flex: 1;
        font-size: 28rpx;
        font-weight: 400;
        color: #31373d;
        line-height: 52rpx;
      }

      // 调整转交按钮样式，确保不改变行高
      .guide-value :deep(.wd-button) {
        margin: 0;
        padding: 0;
        height: auto;
        line-height: 52rpx;
      }

      .guide-value :deep(.wd-button__text) {
        margin: 0;
        padding: 0;
        line-height: 52rpx;
      }
    }

    // 附件列表特殊样式
    .attachment-guide-item {
      flex-direction: column;
      align-items: flex-start;

      .guide-label {
        margin-bottom: 12rpx;
      }

      .guide-value {
        width: 100%;
      }
    }
  }

  // 查看更多按钮
  .more-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    margin: 32rpx 0;

    text {
      font-size: 32rpx;
      color: #3498db;
    }

    .arrow {
      font-size: 24rpx;
      color: #215acd;
    }
  }

  // 按钮容器
  .btn-container {
    display: flex;
    gap: 16rpx;
    position: fixed;
    bottom: 32rpx;
    left: 24rpx;
    right: 24rpx;
    z-index: 100;
  }

  // 并排放置的按钮样式
  .btn-container .wd-button {
    flex: 1;
    height: 96rpx;
    font-size: 32rpx;
  }

  // 查看详情按钮容器
  .view-detail-container {
    position: fixed;
    bottom: 32rpx;
    left: 24rpx;
    right: 24rpx;
    z-index: 100;
  }

  // 查看详情按钮样式
  .view-detail-btn {
    width: 100%;
    height: 96rpx;
    font-size: 32rpx;
  }

  // 更多内容样式
  .more-content {
    margin-bottom: 32rpx;

    .notice-content {
      background-color: #f8f9fa;
      padding: 24rpx;
      border-radius: 12rpx;

      .notice-item {
        font-size: 32rpx;
        color: #31373d;
        line-height: 52rpx;
        margin-bottom: 12rpx;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  // 附件列表样式
  .attachment-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;

    .attachment-tag {
      margin-bottom: 12rpx;
    }
  }
}
:deep(.attachment-tag) {
  margin-right: 12rpx;
  margin-bottom: 12rpx;
}
</style>
