<!-- 使用示例 -->
<!-- 
<n-spin :show="loading">
  <div ref="el" class="scroll"></div>
  <PictureWall :taskDetailInfo="taskDetailInfo" :loading="loading" :el="el" @toggle="toggleLoading"></PictureWall>
</n-spin> 
-->
<script lang="ts" setup>
import { audit } from '@/api/task/task';
import {
getPictureSimilarityList
} from "@/api/work/work";
import NotPassed from '@/components/Approval/NotPassed.vue';
import { useWorkOrder } from "@/store/modules/workOrder";
import { isEmpty } from "@/utils";
import { formatToDateHMS } from "@/utils/dateUtil";
import emitter from '@/utils/mitt';
import { useInfiniteScroll } from "@vueuse/core";
import imagesloaded from "imagesloaded";
import { clone, debounce } from "lodash-es";
import { useDialog, useMessage } from "naive-ui";
import { onMounted, onUnmounted, onUpdated, reactive, ref, toRefs, unref, watch } from "vue";
import ConfrimModal from "../modal/ConfrimModal.vue";
import type { ApprovalParam, SimilarityPictureSortParam } from "/#/api";

const props = defineProps({
  taskDetailInfo: {
    type: Object,
    default: () => ({}),
  },
  el: {
    type: Object as () => HTMLDivElement | null,
    default: () => (null),
  },
  loading: {
    type: Boolean,
    default: () => (false),
  },
});

const emit = defineEmits<{
  (e: 'toggle', loading: boolean)
}>()

const { taskDetailInfo, el, loading } = toRefs(props)

const batch = ref(false); // 批量审批状态
const selectItems = ref<any[]>([]);
const message = useMessage();
const dialog = useDialog();
const totalCount = ref(0);
let _imagesload: any;

function setBatch(value: boolean) {
  if (value && batch.value) {
    batch.value = !value;
  } else {
    batch.value = value;
  }
  if (value === false) {
    selectItems.value.forEach((item) => (item.checked = false));
    selectItems.value.length = 0;
  }
}

function onCheckChange(checked: any, item: any) {
  const index = selectItems.value.indexOf(item);
  item.checked = checked;

  if (index === -1 && checked) selectItems.value.push(item);
  else selectItems.value.splice(index, 1);
}


const taskpagination = reactive({
  pageNo: 1,
  pageSize: 10,
});
const sortBy: SimilarityPictureSortParam = {
  orderType: "desc",
  orderName: "similarityScore",
};
const workStore = useWorkOrder();
const selectTask = ref<any>(null);
const overTask = ref<any>(null);
const confrimModalRef = ref(null);
const listData = ref<any[]>([]);
const selectedSortName = ref('');
const notPassModalRef = ref(null)
const canLoadMore = ref(true);

let processItems: any[] = [];

function validate(items: any[]) {
  if (items.length === 0) return "至少选中一个任务";

  return null;
}

function reset() {
  taskpagination.pageNo = 0;
  taskpagination.pageSize = 20;
  listData.value.length = 0;
  emit('toggle', false)
  canLoadMore.value = true;
}

async function refreshHandler() {
  reset();
  console.log('refreshHandler')
  useInfiniteScroll(
    el as any,
    () => {
      console.log(el)
      console.log(11111111)
      loadMore();
    },
    { distance: 10, interval: 1500, canLoadMore: () => canLoadMore.value }
  );
}

async function loadMore() {
  if (loading.value || el.value == null) return;
    const more = await fetchList();
    listData.value.push(...more);
}

async function fetchList() {
  console.log(3333)
  emit('toggle', true)
  try {
    taskpagination.pageNo += 1;
    const { data, total, pageCount } = await getPictureSimilarityList(
      { ...taskpagination, ...sortBy, checkDuplicateId: workStore.activeId, pictureId: taskDetailInfo.value.id }
    );
    totalCount.value = total;
    canLoadMore.value = pageCount >= taskpagination.pageNo && pageCount > 0;

    return data;
  } catch (error) {
    canLoadMore.value = false;
    return [];
  }
}

const layout = debounce(() => {
  if (el.value == null) return;

  _imagesload = imagesloaded(".grid-item");

  _imagesload.on("done", (instance) => {
    if (!el.value) return;
    emit('toggle', false)
  });

  _imagesload.on("fail", (instance) => {
    message.error("图片错误");
    emit('toggle', false)
  });
}, 300);


watch(
  () => taskDetailInfo.value.id,
  async (newValue, oldValue) => {
    if (newValue !== oldValue) {
      if (isEmpty(taskDetailInfo.value.id)) {
        listData.value.length = 0;
        totalCount.value = 0;
        return;
      }
      refreshHandler()
    }
  }, { deep: true, immediate: true }
);


// 点击任务包图片，查看详情
async function handleSelect(item: any) {
  const packageid = workStore.getActiveId;
  if (isEmpty(packageid)) {
    listData.value.length = 0;
    totalCount.value = 0;
    return;
  }

}

async function sortHandler(orderby: "similarityScore" | "createdate") {
  selectedSortName.value = orderby;
  sortBy.orderName = orderby;
  sortBy.orderType = sortBy.orderType === "asc" ? "desc" : "asc";
  refreshHandler();
}

function overTaskHandelr(item: any) {
  if (item?.historyStates === 2 || item?.historyStates == 3) {
    overTask.value = null;
    return;
  }

  if (validate([item]) == null && batch.value === false) overTask.value = item;
}

function leaveTaskHandler() {
  overTask.value = null;
}


function singleRejectHandler(item) {
  const modal = unref(notPassModalRef)! as any
  modal.showModal([item])
}

function approvalHandler(items?: any) {
  let cloneItem: any
  if (batch.value) {
    processItems = selectItems.value
  }
  else if (overTask.value) {
    cloneItem = clone(overTask.value)
    processItems = [cloneItem]
  }
  //  任务包图片 => 点击 => 通过/不通过按钮
  if (items !== undefined && !(items instanceof PointerEvent))
    processItems = [items]

  const msg = validate(processItems)

  if (msg !== null) {
    message.error(msg)
    return
  }

  const list: any = []
  processItems.forEach((item) => {
    list.push({
      formId: item.id,
      taskId: item.taskId,
      taskName: item.fromTaskName,
    })
  })

  const param = {
    result: true,
    comment: '',
    disposeType: '',
    disposeTypeId: '',
    failCauseId: '',
    failCauseName: '',
    flowTaskInfoList: list,
  }

  dialog.info({
    title: '确认提示',
    content: '确认给该任务审批为【通过】吗?',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      doAudit(param)
    },
    onNegativeClick: () => { },
  })
}

function doAudit(param: any) {
  audit(param).then((res) => {
    const { code } = res
    setBatch(false)
    if (code === 'OK') {
      message.info(res.message)
      emitter.emit('refresh')
      refreshHandler()
    }
    else message.error(res.message)
  })
}

function reloadList() {
  setBatch(false)
  refreshHandler()
}
function reject(idOrDesc: string, backId: string, isOther: boolean) {
  const formIds: string[] = processItems.map(item => item.id)
  const taskIds: string[] = processItems.map(item => item.taskId)
  const tasknames: string[] = processItems.map(item => item.taskname)

  const param: ApprovalParam = {
    formid: formIds,
    taskId: taskIds,
    approvd: false,
    taskComment: idOrDesc,
    taskname: isOther ? tasknames : ['其他'],
  }

  doAudit(param)
}

onMounted(async () => {

})

onUpdated(() => {
  layout();
});

onUnmounted(() => {
  workStore.reset();
});
</script>

<template>
  <div>
    <div style="display: flex; justify-content: space-between; padding: 12px 0px 3px 0">
      <div>
        <span
          style="font-size: 18px; font-weight: Medium;color: #333333;font-family: PingFang SC, PingFang SC-Medium;">任务包图片</span>
      </div>
      <div style="display: flex; align-items: center;font-size: 14px;margin-right: 25px;color:#323233">
        <div style="cursor: pointer" @click="sortHandler('createdate')">
          <span>时间排序</span>
          <SvgIcon style="margin-left: 5px" name="sort" size="12" v-show="selectedSortName !== 'createdate'" />
          <SvgIcon style="margin-left: 5px" name="active-sort" size="12" v-show="selectedSortName === 'createdate'" />
        </div>
        <div style="margin-left: 15px; cursor: pointer" @click="sortHandler('similarityScore')">
          <span>相似度排序</span>
          <SvgIcon style="margin-left: 5px" name="sort" size="12" v-show="selectedSortName !== 'similarityScore'" />
          <SvgIcon style="margin-left: 5px" name="active-sort" size="12"
            v-show="selectedSortName === 'similarityScore'" />
        </div>
      </div>
    </div>
    <div class="wrapper-list">
      <div v-for="(item, index) in listData" :key="index" :class="{ 'item-selected': item === selectTask }"
        class="grid-item" @click="handleSelect(item)" @mouseover="overTaskHandelr(item)" @mouseleave="leaveTaskHandler">
        <div class="img-wrapper" :style="{ 'background-image': `url(${item.imgurl})` }" />
        <div class="time-wrapper">
          <div class="time">
            <SvgIcon color="#FFF" size="16" name="camera" />
            <span class="current-time">{{ item.photoDateTimestamp ? formatToDateHMS(Number(item.photoDateTimestamp) ||
              0) : '-'
            }}</span>
          </div>
          <div class="time">
            <SvgIcon color="#FFF" size="16" name="save" />
            <span class="current-time">{{ item.submitDateTimestamp ? formatToDateHMS(Number(item.submitDateTimestamp)
              || 0) : '-'
            }}</span>
          </div>
        </div>
        <div class="check">
          <n-checkbox v-show="batch && item.historyStates !== 2 && item.historyStates !== 3"
            v-model:checked="item.checked" @click.stop @update:checked="onCheckChange($event, item)" />
        </div>
        <div class="percent" :class="{ 'percent-red': item?.maxSimilarity >= 100 }">
          <div class="val">
            {{ item?.maxSimilarity && Number(item?.maxSimilarity).toFixed(0) }}<span class="percent-unit">%</span>
          </div>
        </div>

        <div class="pass-status" v-if="item.historyStates === 2">
          <SvgIcon name="pass-icon" style="width:52;height:24px" />
        </div>
        <div class="pass-status" v-else-if="item.historyStates === 3">
          <SvgIcon name="no-pass-icon" style="width:52;height:24px" />
        </div>
        <div v-show="overTask && overTask.id === item.id" class="action">
          <SvgIcon style="cursor: pointer" name="t1" @click.stop="approvalHandler" />
          <SvgIcon style="cursor: pointer;margin-left: 40px;" name="t2" @click.stop="singleRejectHandler(item)" />
        </div>
      </div>
    </div>
    <NotPassed ref="notPassModalRef" @success="reloadList" />
    <ConfrimModal ref="confrimModalRef" @commit="reject" />

  </div>
</template>

<style lang="less" scoped>
.wrapper-list {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: flex-start;
  flex-shrink: 0;

  .item-selected {
    box-shadow: 0px 2px 8px 0px rgba(0, 65, 207, 0.28);
    background-color: #fff;
  }

  .grid-item {
    box-sizing: border-box;
    border-radius: 8px;
    padding: 9px 5px;
    position: relative;

    .img-wrapper {
      width: 230px;
      height: 130px;
      overflow: hidden;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
    }

    .time-wrapper {
      position: absolute;
      bottom: 9px;
      width: calc(100% - 11px);
      height: 58px;
      background: linear-gradient(180deg, rgba(0, 0, 0, 0.01), rgba(0, 0, 0, 0.71) 100%);
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      font-weight: Medium;
      padding-left: 12px;
      color: white;

      .time .current-time {
        margin-left: 9px;
        font-weight: Medium;
      }
    }

    .check {
      position: absolute;
      z-index: 3;
      left: 12px;
      top: 12px;
    }

    .percent {
      position: absolute;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 35px;
      height: 18px;
      opacity: 0.9;
      background: #6f92fd;
      border-radius: 6px 0px 6px 0px;
      z-index: 5;
      right: 12px;
      top: 15px;
      color: #fff;
      font-size: 14px;
    }

    .percent-unit {
      font-size: 8px;
      margin-top: 4px;
    }

    .percent-red {
      background: #ff4e4f;
    }

    .pass-status {
      position: absolute;
      left: 0px;
      top: 15px;
    }

    .mark {
      position: absolute;
      z-index: 3;
      right: 62px;
      top: 9px;
      width: 64px;
      height: 40px;
      overflow: hidden;
      overflow: hidden;

      svg {
        position: absolute;
        top: -20px;
      }
    }


    .action {
      position: absolute;
      z-index: 5;
      left: 4px;
      top: 9px;
      width: 230px;
      height: 130px;
      display: flex;
      border-radius: 8px;
      align-items: center;
      justify-content: center;
      background-color: rgba(0, 0, 0, 0.48);
    }


  }
}


::v-deep(.n-divider:not(.n-divider--vertical)) {
  margin-top: 12px;
  margin-bottom: 12px;
}
</style>
