<template>
    <view class="orderDetailNewView">

        <view class="page-item" v-show="activeIndex === 0">
            <pageOne @handleNextClick="handleNextClick" :orderDetail="detail" :orderId="orderId"
                :currentReceipt="currentReceiptInner" />
        </view>
        <view class="page-item" v-show="activeIndex === 1">
            <pageTwo @handleNextClick="handleNextClick" :orderDetail="detail" :orderId="orderId"
                :currentReceipt="currentReceiptInner" :followUpList="followUpList" />
        </view>
        <view class="page-item" v-show="activeIndex === 2">
            <pageThree @handleNextClick="handleNextClick" :orderDetail="detail" @handleNeedSave="handleNeedSave"
                :currentReceipt="currentReceiptInner" @handleConfirmPay="handleConfirmPay" ref="pageThreeComp"
                :orderId="orderId" />
        </view>
        <view class="page-item" v-show="activeIndex === 3">
            <pageFour @confirmInterStore="confirmInterStore" @handleNextClick="handleNextClick" :orderDetail="detail"
                :currentReceipt="currentReceiptInner" />
        </view>

        <ul class="page">
            <li @click="handleTabClick(index)" v-for="(tab, index) in tabs" :key="index"
                :class="{ 'active': activeIndex === index }">{{ tab }}</li>
        </ul>
    </view>
</template>

<script>
import pageOne from './pageOne.vue'
import pageTwo from './pageTwo.vue'
import pageThree from './pageThree.vue'
import pageFour from './pageFour.vue'
export default {
    props: {
        detail: {
            type: Object,
            default: () => { },
        },
        topInfo: {
            type: Object,
            default: () => { },
        },
        orderId: {
            type: String,
            default: ''
        },
        currentReceipt: {
            type: Object,
            default: () => { },
        },
    },
    components: {
        pageOne,
        pageTwo,
        pageThree,
        pageFour
    },
    data() {
        return {
            activeIndex: 0,
            tabs: ['一', '二', '三', '四'],
            allFroms: {
                formOne: {},
                formTwo: {},
                formThree: {},
                formFour: {},
            },
            pageThreeForm: {},
            fileIds: '',
            //收件信息page4,page3
            receiptList: [],
            //订单细节
            orderDetail: {},
            // 跟进记录
            followUpList: [],

            //当前选中的收单订单
            currentReceiptInner: {},
        }
    },
    name: 'OrderDetailNewView',
    watch: {
        orderId: {
            handler(newVal) {
                if (newVal) {
                    // this.fetchReceiptList();
                }
            }, immediate: true
        },
        detail: {
            handler(newVal) {
                if (newVal) {
                    this.orderDetail = newVal;
                    this.getFollowUpList();
                }
            },
            deep: true,
        },
        currentReceipt: {
            handler(newVal) {
                if (newVal) {
                    this.currentReceiptInner = newVal;
                    console.log('当前选中的收单订单里面', this.currentReceiptInner)
                }
            }
        }

    },
    methods: {
        handleNextClick({ nowPage, form }) {
            this.activeIndex++
            this.allFroms[nowPage] = form
            console.log("all page data:", this.allFroms[nowPage])
            // 当点击到第三页时，更新第三页的图片列表
            if (nowPage === 'formTwo') {
                this.$refs.pageThreeComp.getList('2', '3', this.currentReceiptInner.id, this.detail.itemBrand);
            }
        },
        // 没有recepitid就新增
        async saveData(params) {
            await uni.$u.api.addReceiptForm(params);
        },
        // 有recepitid就更新
        async updateData(params) {
            await uni.$u.api.updateReceiptForm(params);
        },

        handleNeedSave({ nowPage, form, fileIds }) {
            this.pageThreeForm = form;
            this.fileIds = fileIds;

            const params = {
                "searchValue": this.detail.searchValue,
                "createBy": this.detail.createBy,
                "createTime": this.detail.createTime,
                "updateBy": this.detail.updateBy,
                "updateTime": this.detail.updateTime,
                // "remark": ,    //发单备注，先不传
                "params": this.detail.params,     //看接口文档
                "id": this.currentReceiptInner.id,
                "sendFormId": this.orderId, //接单中心的id，就是接单中心列表的id（发单id）
                "clueId": this.detail.clueId,
                "item": this.detail.item,
                // "brand": this.topInfo.brand,
                // "needCheckCode": 1,   //先不传
                // "code": null,         //先不传
                // "paymentAmount": null, //支付总额page3 先不传
                "phone": this.detail.phone,
                "tableFee": this.pageThreeForm.paymentAmount,//page3支付总额
                // "benefitFee": 200,     //好处费page4加上
                // "freight": 30,         //运费page4加上
                // "checkCodeFee": null,  //查码费
                // "totalCost": "60230.00",   // 成本合计 =   运费 + 好处费 + 查码费 + 表款(支付总额) + 维修费。
                "sellingPrice": this.topInfo.price,   //实际价格（售价）顶上tab里面的第三栏
                // "performance": "29772.00",  //sellingPrice - totalCost
                // "receiptRemark":     //"收单之后还需再跟进", 先不传
                // "repairAmount": null, //维修总金额 ，先不传
                // "grossPerformance": "7443.00",   //毛利 performance*splitRatio
                // "expressOrderNo": null,   //快递单号+后续加上一个键加上图url
                "fileIds": this.fileIds,  //传第三部里面排序完成之后的id的数组，参考编辑收单里面的附件传的方法
                // "model": this.detail.model,
                // "splitRatio": "25",   //分成比例，先不传
                "customerServiceName": "1", //默认传1，判断入库的类型，回收类入库，销售类入库，维保类入库，第四步传，增加选项下拉
                "deptId": this.detail.deptId,
                "category": this.detail.category,
                "delFlag": this.detail.delFlag,
                "idCard": this.pageThreeForm.idNumber,
                "paymentMethod": '小葫芦线上支付',     //支付方式，如果是app里面默认传‘小葫芦线上支付’
                "bankCardNumber": this.pageThreeForm.bankAccount,
                "bankName": this.pageThreeForm.bankName,
                "customName": this.pageThreeForm.customName,
            }

            // //调用接口保存收单表单
            // if (this.detail.receiptId) {
            //     this.updateData(params);
            // } else {
            //     this.saveData(params);
            // }
        },
        // 确认支付
        handleConfirmPay() {
            // 调用支付接口
            this.pay();
        },
        //支付
        async pay() {
            // 开始支付
            console.log('开始支付')
            try {
                const response = await uni.$u.api.saveOrderFileAndTransfer({
                    id: this.orderId,
                    clueId: this.detail.clueId//线索id
                })
                uni.$u.toast(response.msg || '支付成功')
            } catch (error) {
                uni.$u.toast(`支付失败：${error}`)
            }
        },
        //确认入库
        confirmInterStore({ warehouseInfo }) {
            console.log(warehouseInfo)
            const paramsInterStore = {
                "searchValue": this.detail.searchValue,
                "createBy": this.detail.createBy,
                "createTime": this.detail.createTime,
                "updateBy": this.detail.updateBy,
                "updateTime": this.detail.updateTime,
                // "remark": ,    //发单备注，先不传
                "params": this.detail.params,     //看接口文档
                "id": this.currentReceiptInner.id,
                "sendFormId": this.orderId, //接单中心的id，就是接单中心列表的id（发单id）
                "clueId": this.detail.clueId,
                "item": warehouseInfo.item || '',
                // "brand": this.detail.brand,
                // "needCheckCode": 1,   //先不传
                "code": warehouseInfo.codeStorage || '',         //先不传
                // "paymentAmount": null, //支付总额page3 先不传
                "phone": this.detail.phone,
                "tableFee": warehouseInfo.watchPrice || '',//page3支付总额
                "benefitFee": warehouseInfo.benefitFee || '',     //好处费page4加上
                "freight": warehouseInfo.freight || '',         //运费page4加上
                "checkCodeFee": warehouseInfo.checkCodeFee || '',  //查码费
                // "totalCost": "60230.00",   // 成本合计 =   运费 + 好处费 + 查码费 + 表款(支付总额) + 维修费。
                // "sellingPrice": this.topInfo.price,   //实际价格（售价）顶上tab里面的第三栏
                // "performance": "29772.00",  //sellingPrice - totalCost
                "receiptRemark": warehouseInfo.remarks + ';' + warehouseInfo.uploadedImage || '',//"收单之后还需再跟进", 先不传
                "repairAmount": warehouseInfo.repairAmount || '', //维修总金额 ，先不传
                "grossPerformance": warehouseInfo.grossPerformance || '',   //毛利 performance*splitRatio
                "expressOrderNo": warehouseInfo.expressOrderNo,   //快递单号+后续加上一个键加上图url
                "fileIds": this.fileIds,  //传第三部里面排序完成之后的id的数组，参考编辑收单里面的附件传的方法
                // "model": this.detail.model,
                // "splitRatio": "25",   //分成比例，先不传
                "customerServiceName": "1", //默认传1，判断入库的类型，回收类入库，销售类入库，维保类入库，第四步传，增加选项下拉
                "deptId": this.detail.deptId,
                "category": this.detail.category,
                "delFlag": this.detail.delFlag,
                "idCard": this.pageThreeForm.idNumber,
                "paymentMethod": '小葫芦线上支付',     //支付方式，如果是app里面默认传‘小葫芦线上支付’
                "bankCardNumber": this.pageThreeForm.bankAccount,
                "bankName": this.pageThreeForm.bankName,
                "customName": this.pageThreeForm.customName,
            }
            //调用接口保存物流消息
            if (this.detail.receiptId) {
                this.updateData(paramsInterStore);
            } else {
                this.saveData(paramsInterStore);
            }




        },
        // 获取收单列表
        // async fetchReceiptList() {
        //     try {
        //         const res = await uni.$u.api.clueReceiptFormListByOrderId(this.orderId);
        //         console.log('这里是收件列表', res.data)
        //         this.receiptList = res.data || [];
        //     } catch (error) {
        //         console.error("获取收单列表失败:", error);
        //         uni.$u.toast("获取收单列表失败");
        //     }
        // },

        //获取跟进记录
        async getFollowUpList() {
            try {
                const res = await uni.$u.api.getDuplicateOrderFollowListByClueId({ clueId: this.orderDetail.clueId });
                const data = res.data || {};

                const followUpList = [];
                for (const key in data) {
                    const element = data[key];
                    followUpList.push(...element)
                }
                this.followUpList = followUpList;



            } catch (error) {
                console.error("获取跟进记录失败:", error);
                uni.$u.toast("获取跟进记录失败");
            }
        },
        handleTabClick(index) {
            this.activeIndex = index;
            this.$refs.pageThreeComp.getList('2', '3', this.currentReceiptInner.id, this.detail.itemBrand);
        }
    },

}


</script>

<style scoped>
.orderDetailNewView {
    padding: 20rpx;
}

.page {
    position: fixed;
    right: 20rpx;
    top: 40%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    list-style: none;
    color: #000;
    font-size: 20rpx;
    font-weight: 800;

    li {
        opacity: 0.7;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fff;
        border-radius: 50%;
        width: 70rpx;
        height: 70rpx;
        line-height: 80rpx;
        text-align: center;
        margin-bottom: 20rpx;
        transition: all 0.3s ease-in-out;
        font-weight: 800;
        /* 阴影 */
        box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
    }

    li.active {
        color: #fff;
        opacity: 1;
        background-color: rgb(37 99 235 / 1);
    }
}
</style>
