<script>
// import orderCard from "./compounts/orderCard.vue";

export default {
    components: {
        // orderCard,
    },
    data() {
        return {
            orderList: [],
            page: {
                pageSize: 10,
                pageNum: 1,
                total: 0
            },
            tagModalVisible: false,
            tagList: [],
            currentTags: [],
            currentOrder: {},
            followUpModelShow: false,
            followUpNotes: '',
            countdown: 3000,
            countdownIntervals: null
        }
    },
    onLoad() {
        //初始调用
        this.getOrderList();
        this.countdownInterval()
        // uni.navigateTo({
        //     url: `/pages/orderDetailNew/index?orderId=5464&item=测试发单&type=undefined&clueId=1973381744953516033`,
        // })
    },
    onUnload() {
        clearInterval(this.countdownInterval);
    },
    watch: {
        countdown: {
            handler(newVal, oldVal) {
                if (newVal <= 0) {
                    this.orderList.forEach(order => {
                        if(order.status == 1){
                            this.handleBtnClick('isBusy',order)
                        }
                    })
                }
            },
            immediate: true
        }
    },
    methods: {
        countdownInterval(){
            this.countdownInterval = setInterval(() => {
                this.countdown--
            }, 1000);
        },
        //获取列表数据
        async getOrderList() {
            try {
                const result = await uni.$u.api.selectClueOrderFormList({
                    pageSize: this.page.pageSize,
                    pageNum: this.page.pageNum,
                });

                console.log('接单列表', result);
                // 把数组按照status的大小排序，从小到大
                result.rows.sort((a, b) => {
                    return a.status - b.status;
                })


                this.orderList.push(...result.rows);
                this.page.total = result.total;

            } catch (error) {
                console.error('接单列表接口调用失败:', error);
                // 添加用户友好的错误提示
                uni.$u.toast('获取订单列表失败，请稍后重试');
            }
        },

        // 处理按钮点击事件
        handleBtnClick(btnType, order) {

            if (btnType == 'acceptOrder') {
                //去接单
                console.log('去接单', order)

                //打开模态窗二次确认，确认后跳转接单form
                uni.showModal({
                    title: '确认接单',
                    content: `是否确认接单订单：${order.item}？`,
                    success: async (res) => {
                        if (res.confirm) {
                            await uni.$u.api.oderForm({
                                status: "2",
                                id: order.id,
                            });
                            uni.navigateTo({
                                url: `/pages/orderDetailNew/index?orderId=${order.id}&item=${order.item}&type=${this.type}&clueId=${order.clueId}`,
                            })
                        } else if (res.cancel) {
                            // 用户点击了取消，不执行任何操作
                            uni.$u.toast('已取消接单');
                        }
                    }
                })
            } else if (btnType == 'isBusy') {
                //在忙
                console.log('在忙', order)


                //当前订单移动到末尾
                this.orderList.push(this.orderList.splice(this.orderList.indexOf(order), 1)[0]);


            } else if (btnType == 'willFollow') {
                //待跟进
                console.log('待跟进', order)
                //打开模态窗
                this.followUpModelShow = true;
                this.currentOrder = order
            } else if (btnType == 'tag') {
                //打标签
                console.log('打标签', order)
                //打开模态窗
                this.tagModalVisible = true;
                this.getAllTags();
                this.currentTags = order.tags.map(tag => tag.id);
                this.currentOrder = order
            } else if (btnType == 'share') {
                //一键分享
                console.log('一键分享', order)
            } else if (btnType == 'oneFollow') {
                //待跟进
                console.log('待跟进', order)
                this.followUpModelShow = true;
                this.currentOrder = order
            }
        },
        // 跳转订单详情
        toOrderDetail(order) {
            //点卡片看详情
            // if (order.status == '1' || order.status == '2') {
            uni.navigateTo({
                url: `/pages/orderDetailNew/index?orderId=${order.id}&item=${order.item}&type=${this.type}&clueId=${order.clueId}`,
            })
            // } else {
            //     uni.$u.toast('当前订单无法查看详情');
            //     return;
            // }


        },

        //滑动加载
        scrolltolower() {
            console.log('到底了');
            // if (this.orderList.length >= this.page.total) {
            //     return uni.$u.toast('没有更多了');
            // }
            this.page.pageNum++;
            this.getOrderList();
        },

        //获取全部标签
        async getAllTags() {
            const res = await uni.$u.api.getClueTagGroupVoList({ tagGroupApplication: '2' })
            console.log('全部标签', res.data[0].clueTagDataList)
            this.tagList = res.data[0].clueTagDataList;
        },
        cancelTag() {
            this.tagModalVisible = false;
        },
        async confirmTag() {
            console.log('确认打标签', this.currentTags)
            // 这里可以添加打标签的逻辑
            const allTags = this.currentTags.map(tag => tag).join(',');
            console.log('allTags', allTags)
            await uni.$u.api.updateTags({
                id: this.currentOrder.id,
                allTags: allTags,
            })
            this.tagModalVisible = false;
            uni.$u.toast('标签更新成功');
            //更新当前订单的标签
            this.currentOrder.tags = this.tagList.filter(tag => this.currentTags.includes(tag.id));
        },

        // 确认跟进细节按钮点击事件
        async confirmFollowUp() {
            console.log('确认跟进细节：', this.followUpNotes);
            this.followUpModelShow = false;
            // 可以在这里添加提交跟进细节的逻辑
            // 未收的时候，提交一个跟进记录     待跟进_内容
            const res = await uni.$u.api.addOrderFollow({
                orderId: this.currentOrder.id,
                content: `待跟进_${this.followUpNotes}`,
            })
            if (res.code == 200) {
                uni.$u.toast('提交待跟进记录成功');
            }
        },
    }
}
</script>

<template>
    <view class="container">
        <u-navbar title="接单中心" :autoBack="true" :placeholder="true" v-hideNav></u-navbar>

        <view class="scrollViewContainer">
            <scroll-view class="scrollView" scroll-y @scrolltolower="scrolltolower">
                <transition-group name="order-move" tag="div">
                    <!-- <orderCard v-for="item in orderList" :key="item.receiptId + item.id" :order="item"
                        @handleBtnClick="handleBtnClick">
                    </orderCard> -->
                    <view class="orderCard" v-for="item in orderList" :key="item.receiptId + item.id"
                        @click.stop="toOrderDetail(item)">
                        <view class="bandAndPrice">
                            <view class="bandName">{{ item.itemBrand || '暂无品牌' }}</view>
                            <view class="price">￥{{ item.priceRange || '?' }}</view>
                        </view>

                        <view class="mainLind">
                            <!-- <view class="mainLindImg">
                                <image :src="'/static/acceptOrder/orderCardPic.jpg'" v-if="item.src" />
                            </view> -->
                            <view class="mainLindInfo">
                                <view class="itemName">{{ item.item || '暂无项目' }}</view>
                                <view>发单人:{{ item.createNickName || '未知' }}</view>
                                <view>机构：{{ item.orgName || '暂无机构' }}</view>
                                <view>电话：{{ item.phone || '暂无电话' }}</view>
                                <view>所属人：{{ item.clueOwnerName || '暂无所属人' }}</view>
                                <view>运营人：{{ item.clueOperationName || '暂无运营人' }}</view>
                                <view>发单日期：{{ item.sendDate || '暂无时间' }}</view>
                            </view>
                        </view>

                        <view class="tags">
                            <view class="tag" v-for="(tag, index) in item.tags" :key="index"
                                :style="{ backgroundColor: tag.color, opacity: 0.8 }">
                                {{ tag.name }}</view>

                        </view>

                        <view class="Btns">

                            <view class="btnGroup"
                                v-if="item && (item.status == '1')">
                                <view class="card-button" @click.stop="handleBtnClick('acceptOrder', item)">立即接单</view>
                                <view class=" card-button isBusy" @click.stop="handleBtnClick('isBusy', item)">在忙（{{countdown}}s）</view>
                            </view>

                            <view class="btnGroup"
                                v-if="item && (item.status == '2')">
                                <view class="card-button willFollow" @click.stop="handleBtnClick('willFollow', item)">
                                    待跟进
                                </view>
                                <view class="card-button isBusy" @click.stop="handleBtnClick('tag', item)">打标签</view>
                            </view>

                            <view class="btnGroup"
                                v-if="item && (item.status == '3')">
                                <view class="card-button share" @click.stop="handleBtnClick('share', item)">一键分享</view>
                            </view>

                            <view class="btnGroup"
                                v-if="item && (item.status == '4')">
                                <view class="card-button oneFollow" @click.stop="handleBtnClick('oneFollow', item)">待跟进
                                </view>
                            </view>

                        </view>
                    </view>
                </transition-group>
                <view class="hasMore">
                    <!-- {{ orderList.length >= page.total ? '没有更多了~' : '向下滑动加载更多~' }} -->
                </view>
            </scroll-view>
        </view>




        <!-- 打标签模态窗 -->
        <u-modal :show="tagModalVisible" title="选择标签" @confirm="confirmTag" @cancel="cancelTag">
            <view class="slot-content">
                <u-checkbox-group v-model="currentTags" placement="column">
                    <u-checkbox :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in tagList" :key="item.id"
                        :label="item.name" :name="item.id">
                    </u-checkbox>
                </u-checkbox-group>
            </view>
        </u-modal>

        <u-modal :show="followUpModelShow" :title="'填写跟进细节'" :showConfirmButton="false">
            <view class="modal-content">
                <u--textarea v-model="followUpNotes" placeholder="请输入情况" confirm-type="done"
                    style="width: 400rpx; margin-bottom: 30rpx;"></u--textarea>

                <u-button type="primary" size="large" @click="confirmFollowUp">确认</u-button>
            </view>
        </u-modal>
    </view>
</template>

<style scoped lang="scss">
.hasMore {
    text-align: center;
    padding: 20rpx 0;
    font-size: 24rpx;
    color: #999;
}

.scrollViewContainer {
    height: calc(100vh - 44px);
}

.scrollView {
    height: 100%;
}

/* 订单移动动画 */
.order-move-enter-active,
.order-move-leave-active {
    transition: all 0.5s ease;
}

.order-move-enter-from,
.order-move-leave-to {
    opacity: 0;
    transform: translateY(30px);
}

.order-move-move {
    transition: transform 0.5s ease;
}










/* 订单卡片主容器 */
.orderCard {
    box-sizing: border-box;
    width: 95%;
    background-color: #fff;
    margin: 20rpx auto;
    border-radius: 20rpx;
    padding: 20rpx;
}

/* 品牌和价格区域 */
.orderCard .bandAndPrice {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 品牌名称 */
.orderCard .bandAndPrice .bandName {
    font-size: 20rpx;
    font-weight: 700;
    border: 2px solid #2563EB;
    padding: 6rpx 12rpx;
    border-radius: 15rpx;
    background-color: #EFF6FF;
    color: #2563EB;
}

/* 价格 */
.orderCard .bandAndPrice .price {
    font-size: 30rpx;
    font-weight: 700;
}

/* 主要内容行 */
.orderCard .mainLind {
    margin-top: 10rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20rpx;
}

/* 主要内容行图片容器 */
.orderCard .mainLind .mainLindImg image {
    width: 150rpx;
    height: 150rpx;
    border-radius: 20rpx;
}

/* 主要内容行信息容器 */
.orderCard .mainLind .mainLindInfo {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10rpx;
    font-size: 24rpx;
    color: #6b7280;
}

/* 商品名称 */
.orderCard .mainLind .mainLindInfo .itemName {
    font-size: 30rpx;
    font-weight: 700;
    color: #374751;
}

/* 标签区域 */
.orderCard .tags {
    display: flex;
    gap: 10rpx;
}

/* 单个标签 */
.orderCard .tags .tag {
    font-size: 20rpx;
    font-weight: 700;
    padding: 6rpx 12rpx;
    border-radius: 15rpx;
    background-color: #EFF6FF;
    color: #fff;
}

/* 按钮区域 */
.orderCard .Btns {
    margin-top: 10rpx;
}

/* 按钮组 */
.orderCard .Btns .btnGroup {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20rpx;
}

/* 卡片按钮基础样式 */
.orderCard .Btns .btnGroup .card-button {
    font-size: 24rpx;
    font-weight: 700;
    border: 2rpx solid #2563EB;
    padding: 6rpx 12rpx;
    border-radius: 15rpx;
    background-color: #2563EB;
    color: #fff;
    width: 45%;
    text-align: center;
    cursor: pointer;
    height: 60rpx;
    line-height: 60rpx;
}

/* 忙碌状态按钮 */
.orderCard .Btns .btnGroup .card-button.isBusy {
    background-color: #fff;
    color: #6B7280;
    border-color: #6B7280;
}

/* 待跟进状态按钮 */
.orderCard .Btns .btnGroup .card-button.willFollow {
    background-color: #EFF6FF;
    color: #2563EB;
}

/* 分享按钮 */
.orderCard .Btns .btnGroup .card-button.share {
    width: 100%;
}

/* 单独跟进按钮 */
.orderCard .Btns .btnGroup .card-button.oneFollow {
    width: 100%;
    background-color: #EFF6FF;
    color: #2563EB;
}
</style>
