<template>
  <!-- 审核通过的modal -->
  <u-mask :show="data.mode !== 'HIDE'" @click="handleHide">
    <view class="modal-content-wrap p-2" @click.stop>
      <u-icon class="absolute close-btn" name="close" @click="data.mode = 'HIDE'"></u-icon>

      <scroll-view scroll-y="true" style="height: 100%;">
        <view class="modal-title">审核记录</view>

        <p-deliver-upload-second v-if="deliverData" @upload-success="getDeliverData" @edit-success="getDeliverData"></p-deliver-upload-second>

        <!-- 交付物名称 -->
        <view class="mt-4 px-2 flex justify-between">
          <view class="relative">
            {{ deliverData ? deliverData.deliverName : '' }}审核状态
          </view>
        </view>

        <view class="mt-1 px-2">
          <view class="flex justify-between items-center">
            <!-- 提交人和时间信息 -->
            <view class="text-gray-400 text-xs">
              <text class="mr-4" v-if="deliverData.submitMemberName">{{ deliverData.submitMemberName }}</text>
              <text v-if="deliverData.submitTime"> {{ dayjs(+deliverData.submitTime).format('MM-DD HH:mm') }}</text>
            </view>
          </view>

          <!-- 提交的链接信息 -->
          <DeliverLink :link="deliverData.details[0]" v-if="deliverData.details && deliverData.details[0]" />

          <!-- 审核人 标题 -->
          <view class="text-gray-400 flex justify-between mt-3">
            <text>审核</text>
          </view>

          <!-- 审核人 列表 -->
          <view v-if="deliverData.checkerList">
            <!-- 遍历审核人信息 -->
            <template v-for="item in deliverData.checkerList">
              <!-- 我 -->
              <template v-if="item.isMine === 1">
                <view class="mt-2 text-sm flex justify-between">
                  <view>
                    <view class="font-semibold">{{ item.checkerName }}</view>
                    <view class="text-xs text-gray-400">{{ item.remark }}</view>
                    <view class="text-xs text-gray-400" v-if="+item.checkTime > 0">{{ dayjs(+item.checkTime).format('MM-DD HH:mm') }}</view>
                  </view>

                  <view class="time-box" v-if="item.checkDuration">
                    <view class="initial-duration bg-yellow-400" :style="{width: item.initialPercent + '%'}"></view>
                    <view class="duration bg-blue-400" :style="{width: item.currPercent + '%'}"></view>
                    <view class="check-duration bg-green-400" :style="{width: item.checkPercent + '%'}"></view>
                  </view>

                  <!-- 自己是审核人 且审核过 当前审核人的审核状态并展示得分情况 -->
                  <view v-show="item.status > 0" class="text-xs">
                    <view class="mb-1">
                      <text v-if="item.status === 1" class="text-green-600"> 已通过 </text>
                      <text v-else-if="item.status === 2" class="text-red-600"> 已驳回 </text>
                    </view>
                    <zwp-ring-timing mode="chart" :value="item.score" active-color="#F59E0B" :radius="30" :bar-width="4" v-if="item.score">
                      <text class="text-yellow-500 font-medium">{{ item.score }}</text>
                    </zwp-ring-timing>
                  </view>
                </view>

                <view v-if="item.status === null || item.status === 0">
                  <view class="border border-solid border-gray-300 rounded-md mt-3 px-2" @click="collapsed = !collapsed">
                    <view class="top flex justify-between">
                      <view class="mr-3 py-2 text-sm">工作量时长</view>

                      <!-- 时长 -->
                      <view class="flex item-center justify-end flex-1 text-sm">
                        <u-input v-model="checkDuration" type="text" placeholder="请输入工作量时长" class="input" style="text-align: right;"></u-input>
                      </view>
                    </view>

                    <view class="foot mb-2 flex flex-wrap">
                      <u-button :type="checkedIndex === 0 ? 'primary' : 'default'" size="mini" class="my-1 ml-0 mr-3" @click="handleSelectTime(0)">
                        半小时
                      </u-button>
                      <u-button :type="checkedIndex === 1 ? 'primary' : 'default'" size="mini" class="my-1 ml-0 mr-3" @click="handleSelectTime(1)">
                        1小时
                      </u-button>
                      <u-button :type="checkedIndex === 2 ? 'primary' : 'default'" size="mini" class="my-1 ml-0 mr-3" @click="handleSelectTime(2)">
                        2小时
                      </u-button>
                    </view>
                  </view>

                  <view class="mt-3 flex justify-between items-center">
                    <view>交付物质量</view>

                    <view class="flex justify-end items-center">
                      <u-number-box v-model="score" size="30" :max="100" :min="0" :step="1"></u-number-box>
                      <view class="w-20 ml-2">
                        <u-slider v-model="score" active-color="#34D399" :max="100" :min="0" :step="1"></u-slider>
                      </view>
                    </view>
                  </view>

                  <view class="mt-3">
                    <u-input class="h-20" v-model="commit" type="textarea" :border="true" :auto-height="true" />
                  </view>

                  <view class="common-list">
                    <view v-for="item in words" class="leading-12" @click="commit = item">
                      {{ item }}
                    </view>
                  </view>

                  <view class="mt-4 flex justify-center items-center">
                    <u-button class="mx-4" type="primary" @click="handleSubmit(1)">
                      通过
                    </u-button>
                    <u-button class="mx-4" type="error" @click="handleSubmit(2)">
                      驳回
                    </u-button>
                  </view>
                </view>
              </template>
            </template>

            <template v-for="item in deliverData.checkerList">
              <!-- 不是我 -->
              <template v-if="item.isMine !== 1">
                <view class="mt-2 text-sm flex justify-between">
                  <view>
                    <view class="font-semibold">{{ item.checkerName }}</view>
                    <view class="text-xs text-gray-400">{{ item.remark }}</view>
                    <view class="text-xs text-gray-400" v-if="+item.checkTime > 0">{{ dayjs(+item.checkTime).format('MM-DD HH:mm') }}</view>
                  </view>

                  <view class="time-box" v-if="item.checkDuration">
                    <view class="initial-duration bg-yellow-400" :style="{width: item.initialPercent + '%'}"></view>
                    <view class="duration bg-blue-400" :style="{width: item.currPercent + '%'}"></view>
                    <view class="check-duration bg-green-400" :style="{width: item.checkPercent + '%'}"></view>
                  </view>

                  <!-- 不是自己 显示审核状态 -->
                  <view class="text-xs">
                    <text v-if="item.status === 1" class="text-green-600"> 已通过 </text>
                    <text v-else-if="item.status === 2" class="text-red-600"> 已驳回 </text>
                    <text v-else class="text-gray-400"> 待审核 </text>
                  </view>
                </view>
              </template>
            </template>
          </view>
        </view>

        <view class="py-5 px-2" v-if="listRef && listRef.length">
          <view>历史记录</view>

          <view class="bg-white my-2 rounded-md p-3 text-gray-400 border border-solid border-gray-300" v-for="item in listRef">
            <!-- 插件名称和提交时间显示 -->
            <view class="flex justify-between mb-2">
              <view class="text-gray-800">{{ deliverName }}</view>
              <view class="text-xs">{{ 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="item.checkDuration">
                <view class="initial-duration bg-yellow-400" :style="{width: item.initialPercent + '%'}"></view>
                <view class="duration bg-blue-400" :style="{width: item.currPercent + '%'}"></view>
                <view class="check-duration bg-green-400" :style="{width: item.checkPercent + '%'}"></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>

                  <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>
      </scroll-view>
    </view>
  </u-mask>
</template>

<script setup>
import { ref, computed, watch, inject } from 'vue';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import { quickWords } from '@/config/deliver';

const props = defineProps({
  data: { type: Object, default: {} },
  msgId: { default: '', type: String },
});

const emits = defineEmits(['hide', 'submit-end']);
const store = useStore();
// const words = computed(() => quickWords[props.data.mode]); // 快捷用语
const words = computed(() => quickWords['RESOLVE']); // 快捷用语
const projectId = computed(() => store.getters['project/projectId']);
const roleId = computed(() => store.state.role.roleId);
const task = inject('task');
const commit = ref(''); // 提交的信息
const score = ref(100); // 评分
const deliverData = inject('deliver');
const checkDuration = ref('2小时'); // 工作量时长
const checkedIndex = ref(2); // 默认选中
let maxDuration = ref(null);
const listRef = ref([]);
const deliverName = ref('');

watch(deliverData, () => {
  linkValue.value = deliverData.value.details[0]; // 交付物内容
  checkDuration.value = deliverData.value.duration; // 工作量时长
  checkedIndex.value = checkDuration.value === '半小时' ? 0 : checkDuration.value === '1小时' ? 1 : checkDuration.value === '2小时' ? 2 : -1;

  handleDataRender(deliverData.value.checkerList);
})

getHistory(); // 交付物历史

async function handleDataRender(data) {
  maxDuration.value = deliverData.value.initialDuration > deliverData.value.duration ? deliverData.value.initialDuration : deliverData.value.duration;

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

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

  return data;
}

/**
 * 提交评审信息
 * 提交成功后隐藏modal 重置表单控件
 * 给父组件信息 更新值
 * @param {string} mode 'RESOLVE'|'REJECT'
 */
async function handleSubmit(mode) {
  try {
    const deliverRecordId = props.data.deliverRecordId();
    const param = {
      projectId: projectId.value,
      roleId: roleId.value,
      deliverRecordId,
      type: mode,
      remark: commit.value,
      score: score.value,
      checkDuration: checkDuration.value,
      msgId: task.msgId,
    };

    await uni.$u.api.checkDeliver(param);
    handleHide(); // 隐藏 + 重置
    uni.$ui.showToast('审核信息提交成功');
    // 通知父组件评审成功 更新信息
    emits('submit-end', param);
  } catch (error) {
    console.error('error: ', error);
    uni.$ui.showToast('审核信息提交失败, 请稍后重试');
  }
}

// 隐藏及 重置
function handleHide() {
  emits('hide');
  // 重置相关数据
  score.value = 100;
  commit.value = '';
}

// 根据任务id获取交付物信息
async function getDeliverData() {
  try {
    const { id: taskId } = task;
    if (!taskId) return;
    const param = { taskId };
    const data = await uni.$u.api.getDeliverByTaskId(param);
    deliver.value = data;
  } catch (error) {
    console.log('error: ', error);
  }
}

// 交付物历史记录
async function getHistory() {
  try {
    const { deliverId } = deliverData.value;
    const param = { deliverId: deliverId };
    const data = await uni.$u.api.getDeliverHistory(param);
    deliverName.value = data.deliverName;

    data.deliverRecordList.forEach(deliver => {
      handleDataRender(deliver);
    })
    listRef.value = data.deliverRecordList;
  } catch (error) {
    console.log('error: ', error);
    uni.$ui.showToast('获取交付物历史失败');
  }
}

// 选择工作量时长
function handleSelectTime(data) {
  checkedIndex.value = data;
  checkDuration.value = data === 0 ? '半小时' : data === 1 ? '1小时' : '2小时';
}
</script>

<style scoped lang="scss">
  .modal-content-wrap {
    width: 100%;
    height: 100%;
    left: 0;
  }

  .close-btn {
    width: 30px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #FFFFFF;
    right: 10px;
    top: 10px;
    z-index: 9;
  }

  .modal-title {
    text-align: center;
    height: 50px;
    line-height: 50px;
    font-size: 17px;
    font-weight: bold;
  }

  .common-list {
    view {
      border-bottom: 1px solid #eee;
    }
  }

  .time-box {
    width: 100px;

    view {
      height: 15px;
    }
  }
</style>
