<template>
  <view class="page-container">
    <!-- 页面级加载组件 -->
    <up-loading-page
        v-if="loading"
        :loading="true"
        title="加载中..."
        color="#3c9cff"
    ></up-loading-page>

    <!-- 主内容容器 -->
    <view v-else class="main-content">
      <!-- 顶部固定Tabs -->
      <up-sticky :bgColor="'#fff'">
        <up-tabs
            v-model="activeTopTab"
            :list="topTabList"
            :scrollable="false"
            sticky
            active-color="#3c9cff"
            inactive-color="#666"
            class="top-tabs"
            @click="activeTopTabClick"
        ></up-tabs>
      </up-sticky>


      <!-- 顶部Tab内容区 -->
      <view class="tab-content">
        <!-- 1. 工单详情Tab -->
        <view v-show="activeTopTab == 0" class="detail-content">
          <up-cell-group :border="false" class="detail-cell-group">
            <!-- 工单编号 -->
            <up-cell title="工单编号" :value="orderDetail.orderNo || '--'" align="middle"></up-cell>

            <!-- 工单位置 -->
            <up-cell align="middle">
              <template #title>
                <view style="min-width: 200rpx">工单位置</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.roadName || '--' }}</view>
              </template>
            </up-cell>

            <!-- 工单名称 -->
            <up-cell title="工单名称" :value="orderDetail.orderName || '--'" align="middle"></up-cell>

            <!-- 情况描述 -->
            <up-cell>
              <template #title>
                <view style="min-width: 200rpx">情况描述</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.remark || '--' }}</view>
              </template>
            </up-cell>

            <!-- 紧急程度 -->
            <up-cell
                title="紧急程度"
                :value="uni.$dict.getDictLabel('workorder_pressing_type', orderDetail.pressingType) || '--'"
                align="middle"
            ></up-cell>

            <!-- 提交人 -->
            <up-cell title="提交人" :value="orderDetail.userName || '--'" align="middle"></up-cell>

            <!-- 提交时间 -->
            <up-cell
                title="提交时间"
                :value="timeFormat(orderDetail.createTime, 'yyyy-mm-dd hh:MM:ss') || '--'"
                align="middle"
            ></up-cell>

            <!-- 处理结果 -->
            <up-cell>
              <template #title>
                <view style="min-width: 200rpx">处理结果</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.handleResult || '--' }}</view>
              </template>
            </up-cell>

            <!-- 街道名称 -->
            <up-cell title="街道名称" :value="orderDetail.streetName || '--'" align="middle"></up-cell>

            <!-- 问题照片 -->
            <up-cell title="问题照片">
              <template #value>
                <view class="cell-content-wrap">
                  <up-album
                      v-if="!!orderDetail.problemsImgs?.length"
                      :urls="orderDetail.problemsImgs.slice(0, 3)"
                      singleSize="70"
                      :preview-full-image="true"
                  ></up-album>
                  <text v-else class="empty-text">暂无问题照片</text>
                </view>
              </template>
            </up-cell>

            <!-- 希望完成时间 -->
            <up-cell
                title="希望完成时间"
                :value="orderDetail.finishDate === 0 ? '未设置' : timeFormat(orderDetail.finishDate, 'yyyy-mm-dd hh:MM:ss')"
                align="middle"
                :border="false"
            ></up-cell>
          </up-cell-group>


          <!-- 图片分类Tabs区块 -->
          <view class="img-tabs-block" v-if="orderDetail.startImgs.length>0">
            <up-cell-group :border="false">
              <up-cell>
              <template #title>
                <view style="min-width: 200rpx">共同处理人</view>
              </template>
              <template #value>
                <view class="common-text-color up-line-1">{{ orderDetail.coHandlersName || '--' }}</view>
              </template>
              </up-cell>
            </up-cell-group>
            <!--            coHandlersName-->
            <up-tabs
                @change='imgTabChange'
                v-model="activeImgTab"
                :list="imgTabList"
                :scrollable="false"
                active-color="#3c9cff"
                inactive-color="#666"
                class="img-tabs"
            ></up-tabs>

            <!-- 图片Tab内容区 -->
            <view class="img-tab-content">
              <up-album
                  v-if="currentImgList.length"
                  :urls="currentImgList.slice(0, 3)"
                  singleSize="80"
                  multipleSize="80"
                  :preview-full-image="true"
                  class="img-album"
              ></up-album>
              <text v-else class="empty-img-text">暂无图片</text>
            </view>
          </view>
        </view>

        <!-- 2. 流程节点Tab -->
        <view v-show="activeTopTab == 1" class="process-content">
          <!--          <up-empty-->
          <!--              mode="data"-->
          <!--          ></up-empty>-->
          <!--          &lt;!&ndash; 可根据实际需求补充流程节点展示逻辑 &ndash;&gt;-->
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref, computed} from 'vue';
import {onLoad, onShow} from '@dcloudio/uni-app';
import {timeFormat} from '@/uni_modules/uview-plus';
import {
  getMyTaskDetail,
  getDoneTaskDetail,
  getTodoTaskDetail,
  getApprovalDetail
} from '@/api/work-order-manage/work-order-manage';

// 状态管理
const loading = ref(true);
const activeTopTab = ref(0); // 顶部Tab激活索引
const activeImgTab = ref(0); // 图片分类Tab激活索引

// 顶部Tab列表
const topTabList = ref([
  {name: '工单详情'},
  {name: '流程节点'}
]);

const activeTopTabClick = async (item: any) => {
  console.log(item)
  activeTopTab.value = item.index
  if (activeTopTab.value == 1) {
    let getData = {
      processInstanceId: processInstanceId.value,
    }
    const res = await getApprovalDetail(getData)
    console.log(res)
  }
}

// 图片分类Tab列表（带角标配置）
const imgTabList = ref([
  {name: '开始', badge: {isDot: true}},
  {name: '进行中'},
  {name: '结束', badge: {isDot: true}},
  {name: '人员'},
  {name: '材料'}
]);

// 工单详情数据（初始化赋值，可被接口数据覆盖）
const orderDetail = ref<any>({
  id: 0,
  busiLine: '',
  orderNo: '',
  orderName: '',
  sourceId: 0,
  sourceName: '',
  roadId: 0,
  roadName: '',
  streetId: '',
  streetName: '',
  curingLevelId: 0,
  curingLevelName: '',
  commitDate: 0,
  finishDate: 0,
  pressingType: 0,
  userId: 0,
  userName: '',
  companyId: 0,
  latLonType: 0,
  lat: 0,
  lon: 0,
  lonLatAddress: '',
  thirdWorkNo: '',
  thirdPushState: 0,
  buzStatus: null,
  status: 0,
  processInstanceId: '',
  remark: '',
  handleResult: '',
  createTime: 0,
  fileNames: null,
  coHandlers: null,
  coHandlersName: null,
  companyName: null,
  userMobile: null,
  taskId: '',
  taskName: '',
  taskKey: '',
  processDefinitionName: '',
  startTime: 0,
  endTime: 0,
  key_: '',
  problemsImgs: [],
  startImgs: [],
  processingImgs: [],
  endImgs: [],
  personImgs: [],
  materialImgs: []
});

/**
 * 当前激活的图片列表（无需函数调用，直接访问）
 */
const currentImgList = ref([])

const tabKeyMap = ['startImgs', 'processingImgs', 'endImgs', 'personImgs', 'materialImgs'];
const imgTabChange = (({index}) => {
  console.log(index)
  const currentKey = tabKeyMap[index]
  console.log(currentKey)
  console.log(orderDetail.value[currentKey])
  currentImgList.value = orderDetail.value[currentKey]
})


/**
 * 获取工单详情
 */
const DetailQuery = async (taskIdStr: string) => {
  console.log('当前工单ID：', taskIdStr)
  try {
    loading.value = true;
    // 转换activeTab为数字类型，避免类型不一致导致接口调用失败
    const tabType = Number(activeTab.value);
    let res: any;

    if (tabType === 0) {
      res = await getTodoTaskDetail({taskId: taskIdStr});
    } else if (tabType === 1) {
      res = await getMyTaskDetail({taskId: taskIdStr});
    } else if (tabType === 2) {
      res = await getDoneTaskDetail({taskId: taskIdStr});
    } else {
      uni.showToast({title: '无效的工单类型', icon: 'none'});
      return;
    }

    // 覆盖工单详情数据
    if (res) {
      orderDetail.value = res;
      currentImgList.value = orderDetail.value.startImgs
    }
  } catch (error) {
    console.error('获取工单详情失败：', error);
    uni.showToast({title: '加载失败，请重试', icon: 'none'});
  } finally {
    loading.value = false;
  }
};

// 页面加载参数
const taskId = ref('')
const activeTab = ref('')
const processInstanceId = ref('')
onLoad((options: any) => {
  console.log('页面入参：', options)
  const {taskId: taskIdOpt, activeTab: activeTabOpt, processInstanceId: processInstanceIdOpt} = options;
  // 0-待办 1-我发起的 2-已办
  taskId.value = taskIdOpt || '';
  activeTab.value = activeTabOpt || '0';
  processInstanceId.value = processInstanceIdOpt;
  DetailQuery(taskId.value);
});

onShow(() => {
  // if (taskId.value) {
  //   DetailQuery(taskId.value);
  // } else {
  //   loading.value = false;
  //   uni.showToast({title: '缺少工单ID参数', icon: 'none'});
  // }
});
</script>

<style scoped lang="scss">
// 全局样式
.page-container {
  min-height: 100vh;
}

// 主内容容器
.main-content {
  padding-bottom: 20rpx;
}

// 顶部Tabs
.top-tabs {
  //background-color: #fff;
}

// Tab内容区
.tab-content {
  //padding: 16rpx;
}

// 工单详情内容
.detail-content {
  .detail-cell-group {
    background-color: #fff;
    margin-bottom: 20rpx;
  }

  .cell-content-wrap {
    // 保持原有样式，兼容up-album布局
  }

  .empty-text {
    color: #999;
    font-size: 26rpx;
  }
}

// 图片分类Tabs区块
.img-tabs-block {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 16rpx;

  //// 图片Tabs样式（平均分配空间）
  //.img-tabs {
  //  --u-tabs-item-flex: 1; // 平均分配空间
  //  --u-tabs-item-font-size: 26rpx;
  //  --u-tabs-item-height: 72rpx;
  //  margin-bottom: 16rpx;
  //}

  // 图片内容区
  .img-tab-content {
    padding: 10rpx 0;
    min-height: 120rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .img-album {
      width: 100%;
    }

    .empty-img-text {
      height: 100px;
      line-height: 100px;
      color: #999;
      font-size: 28rpx;
    }
  }
}

// 流程节点空状态
.process-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400rpx;

  .empty-process {
    margin-top: 100rpx;
  }
}
</style>