<template>
    <view class="book-info">
        <template v-if="isShow">
            <view class="font-bold mt-12 mb-10" style="padding: 0 20rpx">
                {{ bookList.length }}条记录，共{{ detail.totalNum }}本，已审{{ auditNum || 0 }}本
            </view>
            <view class="font-light" style="padding: 0 20rpx">
                其中已审：良好{{ getAuditCateNum(1) }}本，一般0本，极差{{ getAuditCateNum(3) }}本
            </view>
        </template>

        <view
            class="book-info-item bg-white mt-12"
            :style="{ backgroundColor: item.backgroundColor }"
            v-for="item in formatList"
            :key="item.title"
            :id="item.id"
            v-show="item?.title"
        >
            <view class="book-info-item-title">{{ item.title }}</view>
            <view class="book-info-item-list">
                <BookItem v-for="book in item.list" :key="book.bookId" :item="book" @click="handleBookClick(book)" />
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, watch, computed } from "vue";
import BookItem from "./BookItem.vue";
import toPinyin from "@/utils/toPinyin.js";
const props = defineProps({
    bookList: {
        type: Array,
        default: () => [],
    },
    detail: {
        type: Object,
        default: () => ({}),
    },
    isShow: {
        type: Boolean,
        default: true,
    },
});

const emit = defineEmits(["get-all-firstLetter"]);

//计算已审书籍数量
const auditNum = computed(() => {
    return props.bookList.reduce((total, item) => {
        let num = item.auditCommentList?.filter((v) => v.sts != 0).length || 0;
        return total + num;
    }, 0);
});

function handleBookClick(book) {
    if (props.detail.status >= 10) {
        uni.$u.ttsModule.speak("订单已审核完成");
        return;
    }

    uni.redirectTo({
        url: `/pages/index/detail/book-audit?isbn=${book.isbn}&orderId=${props.detail.orderId}`,
    });
    uni.setStorageSync("auditBook", book);
}

function getAuditCateNum(cate) {
    let auditList = [];
    props.bookList.forEach((v) => {
        auditList.push(...(v.auditCommentList || []));
    });
    return auditList.filter((v) => v.sts == cate).length;
}

//格式化书籍列表
const formatBookList = (list) => {
    const poorBooks = { title: "极差", list: [], backgroundColor: "#de868f", id: "poor" };
    const goodBooks = { title: "良好", list: [], backgroundColor: "#81b337", id: "good" };
    const otherBooks = [];
    //获取所有的首字母
    const allFirstLetter = [];

    const handleBookCategorization = (book) => {
        let firstLetter;
        // 找到第一个中文
        let firstChineseChar = null;
        for (let i = 0; i < book.bookName.length; i++) {
            const char = book.bookName.charAt(i);
            if (/^[\u4E00-\u9FA5]$/.test(char)) {
                // 检查是否为中文
                firstChineseChar = char;
                break;
            }
        }

        // 如果找到中文，使用其拼音首字母
        if (firstChineseChar) {
            firstLetter = toPinyin.chineseToInitials(toPinyin.chineseToPinYin(firstChineseChar));
        } else {
            // 如果没有找到中文，使用第一个字符
            const char = book.bookName.charAt(0);
            if (/^[A-Za-z]$/.test(char)) {
                firstLetter = char.toUpperCase();
            } else {
                firstLetter = char;
            }
        }

        let bool = otherBooks.some((item) => item.title == firstLetter);
        if (!bool) {
            otherBooks.push({ id: firstLetter, title: firstLetter, list: [{ ...book }] });
            allFirstLetter.push(firstLetter);
            emit("get-all-firstLetter", allFirstLetter);
        } else {
            otherBooks.find((item) => item.title == firstLetter).list.push(book);
        }
    };

    list.forEach((book) => {
        book.goodNum = book.auditCommentList?.filter((v) => v.sts == 1).length || 0;
        book.badNum = book.auditCommentList?.filter((v) => v.sts == 3).length || 0;

        // Check if book is fully audited (all items have been reviewed)
        const totalAudited = book.auditCommentList?.filter((v) => v.sts !== 0).length || 0;
        const isFullyAudited = totalAudited === book.num;

        if (isFullyAudited) {
            // If any audit result is poor (sts === 3), push to poorBooks
            if (book.auditCommentList.some((v) => v.sts === 3)) {
                poorBooks.list.push(book);
            } else if (book.auditCommentList.every((v) => v.sts === 1)) {
                // If all audit results are good (sts === 1), push to goodBooks
                goodBooks.list.push(book);
            } else {
                handleBookCategorization(book);
            }
        } else {
            handleBookCategorization(book);
        }
    });

    return { poorBooks, goodBooks, otherBooks };
};

const formatList = ref([]);
watch(
    () => props.bookList,
    (newVal) => {
        let { poorBooks, goodBooks, otherBooks } = formatBookList(newVal);

        // 按照首字母排序 A-Z
        otherBooks.sort((a, b) => a.id.localeCompare(b.id));

        let poor = poorBooks.list.length > 0 ? poorBooks : {};
        let good = goodBooks.list.length > 0 ? goodBooks : {};
        formatList.value = [...otherBooks, poor, good];
    },
    { immediate: true, deep: true }
);
</script>

<style scoped>
.book-info-item-title {
    padding: 10rpx 30rpx;
    font-size: 28rpx;
    font-weight: 600;
    border-bottom: 1px solid #e5e5e5;
}
</style>
