<template>
  <theme class="min-h-full">
    <!-- 标题栏 -->
    <Title :titleName="deliverName" />

    <view class="tab-box fixed w-full flex justify-between items-center bg-white">
      <view class="tab-item text-center" :class="{'tab-curr': current === 0}" @click="changeTabs(0)">
        <view class="tab-title px-1 inline-block">提交</view>
      </view>
      <view class="tab-item text-center" :class="{'tab-curr': current === 1}" @click="changeTabs(1)">
        <view class="tab-title px-1 inline-block">审核</view>
      </view>
      <view class="tab-item text-center" :class="{'tab-curr': current === 2}" @click="changeTabs(2)">
        <view class="tab-title px-1 inline-block">历史记录</view>
      </view>
    </view>

    <view style="height: 44px;"></view>

    <view class="scroll-box">
    <!-- 提交 -->
    <view class="p-3 text-base scroll-0">当前提交</view>

    <view class="px-3">
      <p-deliver-upload-second class="pb-2" v-if="deliverData" :deliverData="deliverData" :task="task" :url="url" @upload-success="getDeliverData" @edit-success="getDeliverData"></p-deliver-upload-second>
    </view>

    <!-- 审核 -->
    <view class="p-3 text-base scroll-1">审核状态</view>

    <view class="px-3">
      <p-deliver-check-second-detail v-if="deliverData" :deliverData="deliverData" :task="task" :url="url" @submit-end="getDeliverData"></p-deliver-check-second-detail>
    </view>

    <!-- 历史记录 -->
    <view class="p-3 text-base scroll-2">历史记录</view>

    <view class="px-3" v-if="listRef && listRef.length">
      <view class="bg-white mb-3 rounded-md p-3 text-gray-400" v-for="item in listRef">
        <!-- 插件名称和提交时间显示 -->
        <view class="flex justify-between mb-2">
          <view class="text-gray-800">{{ deliverName }}</view>
          <view class="ml-1 text-xs w-24 text-right">{{ dayjs(+item.submitTime).format('MM-DD HH:mm') }}</view>
        </view>
        <!-- 提交的链接 -->
        <DeliverLink v-if="item.details[0]" :link="item.details[0]" />
        <!-- 该插件物的审核人 -->
        <view class="mb-1 mt-3">审核人</view>
        <view class="flex justify-between mb-2" v-for="checkItem in item.checkerList">
          <view>
            <view class="mb-1 text-gray-800 font-semibold">
              {{ checkItem.checkerName }}
            </view>
            <view class="mb-1 text-xs">
              {{ checkItem.remark }}
            </view>
            <view class="mb-1 text-xs" v-if="+checkItem.checkTime > 0">
              {{ dayjs(+checkItem.checkTime).format('MM-DD HH:mm') }}
            </view>
          </view>

          <view class="time-box" v-if="checkItem.checkDuration">
            <view class="relative">
              <view class="initial-duration bg-yellow-400" :style="{width: checkItem.initialPercent + '%'}"></view>
              <text class="absolute duration-value">默认值：{{ initialDuration / 3600000 }}小时</text>
            </view>
            <view class="relative">
              <view class="duration bg-blue-400" :style="{width: checkItem.currPercent + '%'}"></view>
              <text class="absolute duration-value">工作量时长：{{ item.duration / 3600000 }}小时</text>
            </view>
            <view class="relative">
              <view class="check-duration bg-green-400" :style="{width: checkItem.checkPercent + '%'}"></view>
              <text class="absolute duration-value">确认工作：{{ checkItem.checkDuration / 3600000 }}小时</text>
            </view>
          </view>

          <view class="text-center text-xs">
            <view v-if="checkItem.status == null" class="text-gray-400">待审核</view>
            <view v-else-if="checkItem.status === 1">
              <view class="text-green-600 mb-1">已通过</view>

              <view class="text-yellow-500 font-medium text-base">{{ checkItem.score }}</view>

              <!-- <zwp-ring-timing mode="chart" :value="checkItem.score" active-color="#F59E0B" :radius="30" :bar-width="4">
                <text class="text-yellow-500 font-medium">{{ checkItem.score }}</text>
              </zwp-ring-timing> -->
            </view>
            <view class="text-red-600" v-else>已驳回</view>
          </view>
        </view>
      </view>
    </view>

    <u-empty text="暂无记录" mode="history" style="padding-top: 120rpx" v-else></u-empty>
    </view>
  </theme>
</template>

<script setup>
import { ref, provide } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import dayjs from 'dayjs';
import pDeliverUploadSecond from "@/plugins/p-deliver-second/p-deliver-upload-second.vue"
import pDeliverCheckSecondDetail from "@/plugins/p-deliver-second/p-deliver-check-second-detail.vue"

const listRef = ref([]);
const deliverName = ref('');
const deliverData = ref(null);
const task = ref(null);
const checkers = ref(null);
const clickList = [
  {
    name: '提交'
  },
  {
    name: '审核'
  },
  {
    name: '历史记录'
  }
];
const current = ref(0);
const url = ref(null);
let maxDuration = ref(null);
let initialDuration = ref(null); // 历史交付物默认值

onLoad(options => {
  deliverData.value = JSON.parse(options.deliverData);
  provide('deliver', deliverData.value);
  task.value = JSON.parse(options.task);
  provide('task', task.value);
  checkers.value = options.checkers;
  url.value = options.url;

  // 根据交付物id获取上传记录
  (async function getHistory() {
    try {
      const param = { deliverId: options.deliverId };
      const data = await uni.$u.api.getDeliverHistory(param, options.url);
      deliverName.value = data.deliverName;
      initialDuration.value = data.initialDuration;
      listRef.value = data.deliverRecordList;

      listRef.value.forEach(item => {
        handleDataRender(item);
      })

    } catch (error) {
      console.log('error: ', error);
      uni.$ui.showToast('获取交付物历史失败');
    }
  })();
});

function changeTabs(index) {
  current.value = index;

  uni.createSelectorQuery().select('.scroll-' + index).boundingClientRect(data=>{//目标节点
    uni.createSelectorQuery().select('.scroll-box').boundingClientRect((res)=>{//最外层盒子节点 　　　　
      uni.pageScrollTo({ 　　　　　　
        duration: 0,//过渡时间必须为0，否则运行到手机会报错
        scrollTop: data.top - res.top //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离（如res.top - data.top）
      })
    }).exec()
  }).exec()
}

// 根据任务id获取交付物信息
async function getDeliverData() {

  try {
    const { id: taskId } = task.value;
    if (!taskId) return;
    const param = { taskId };
    const data = await uni.$u.api.getDeliverByTaskId(param, url.value);
    deliverData.value = data;

    getHistory();
  } catch (error) {
    console.log('error: ', error);
  }
}

// 处理审核记录数据
async function handleDataRender(data) {
  maxDuration.value = initialDuration.value > deliverData.value.duration ? initialDuration.value : deliverData.value.duration;

  data.checkerList.forEach(item => {
    if (item.checkDuration) {
      maxDuration.value = maxDuration.value > item.checkDuration ? maxDuration.value : item.checkDuration;

      if (maxDuration.value == initialDuration.value) {
        item.initialPercent = 100;
        item.currPercent = Math.floor(deliverData.value.duration / initialDuration.value * 100);
        item.checkPercent = Math.floor(item.checkDuration / initialDuration.value * 100);
      } else if (maxDuration.value == deliverData.value.duration) {
        item.currPercent = 100;
        item.initialPercent =  Math.floor(initialDuration.value / deliverData.value.duration * 100);
        item.checkPercent = Math.floor(item.checkDuration / deliverData.value.duration * 100);
      } else if (maxDuration.value == item.checkDuration) {
        item.checkPercent = 100;
        item.initialPercent = Math.floor(initialDuration.value / item.checkDuration * 100);
        item.currPercent = Math.floor(deliverData.value.duration / item.checkDuration * 100);
      }
    }
  })

  return data;
}
</script>

<style scoped lang="scss">
  .tab-box {
    height: 44px;
    z-index: 999;

    .tab-item {
      width: calc(100% / 3);
      height: 44px;
      line-height: 40px;
    }

    .tab-curr {
      .tab-title {
        color: #2979ff;
        border-bottom: 3px solid #2979ff;
      }
    }
  }

  .time-box {
    width: 120px;

    view {
      height: 15px;
      border-radius: 2px;
      margin: 2px 0;
    }

    .duration-value {
      height: 15px;
      line-height: 15px;
      font-size: 12px;
      top: 0;
      left: 0;
      color: #333;
    }
  }
</style>
