<template>
    <view class="order-create">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <!-- 地址选择 -->
        <order-choose-address class="sticky-top" :addressInfo="addressInfo"></order-choose-address>
        <!-- 供应商商品列表 -->
        <view class="shop-list">
            <view class="section" v-for="(shopInfo, index) in shopList" :key="shopInfo.shopId">
                <order-supplier-area
                    :shopInfo="shopInfo"
                    :submitType="submitType"
                    @countChange="onCountChange"
                ></order-supplier-area>
                <view class="comment">
                    <text>留言：</text>
                    <input placeholder="请输入内容" placeholder-class="placeholder" v-model="shopInfo.note" />
                </view>
                <tui-divider :height="48" v-if="index < shopList.length - 1"></tui-divider>
            </view>
        </view>
        <!-- 优惠券 -->
        <view class="cell-section" @click="couponVisiable = true">
            <tui-list-cell :arrow="true" :padding="cellPadding" :unlined="true">
                <view class="cell-content">
                    <text>优惠券</text> <text class="reduce tip">-￥{{ couponAmount | priceFormat }}</text>
                </view>
            </tui-list-cell>
        </view>
        <!-- 分享减免 -->
        <view class="cell-section" @click="$refs.sharePopup.open()">
            <tui-list-cell :arrow="false" :padding="cellPadding" :unlined="true">
                <button class="cell-content share-btn">
                    <text>金额满99元，分享可立减20元</text> <text class="reduce tip">点击分享</text>
                </button>
            </tui-list-cell>
        </view>
        <!-- 运费 -->
        <view class="cell-section">
            <tui-list-cell :arrow="false" :padding="cellPadding" :unlined="true">
                <view class="cell-content"> <text>运费</text> <text class="tip postage">免邮</text> </view>
            </tui-list-cell>
        </view>
        <!-- 提交订单 -->
        <order-submit :orderInfo="orderInfo" @submit="onSubmit"></order-submit>
        <!-- 优惠券列表 -->
        <cm-coupon-popup
            :visiable="couponVisiable"
            :list="receiveCouponList"
            :hasTabs="false"
            :hasConfirm="true"
            :hasSafeArea="true"
            :hasCheckedNone="true"
            :checkedNone="checkedNone"
            @close="onCouponPopupClose"
            @couponClick="onCouponClick"
            @checkedNone="onCheckedNone"
        ></cm-coupon-popup>
        <!-- 分享 -->
        <cm-share-popup ref="sharePopup"></cm-share-popup>
    </view>
</template>

<script>
import { orderConfirm, orderSubmit } from '@/services/api/order.js'
import { fetchAddressList } from '@/services/api/user.js'
import { initFormatCouponList, splitCouponList, chooseBestCoupon } from '@/common/business.helper.js'
import { mapGetters } from 'vuex'
import wechatPayMixins from '@/pages/views/order/mixins/wechatPay.js'
export default {
    mixins: [wechatPayMixins],
    data() {
        return {
            isRequest: true,
            submitType: 'cart', // 订单提交来源 cart  product  shareBuy
            // 确认订单参数信息
            confirmParams: {
                userId: '',
                cartIds: '',
                productId: '',
                productCount: '',
                heUserId: '',
                collageFlag: 0
            },

            // 订单提交参数
            submitParams: {
                userId: 0,
                orderInfo: [], //提交的商品信息
                addressId: 0,
                cartType: 0,
                payInfo: {
                    orderShouldPayFee: 0
                },
                discountInfo: null
            },

            // 地址
            addressList: [],
            addressInfo: null,

            // 商品信息
            shopList: [],

            // 优惠券
            couponVisiable: false,
            receiveCouponList: [],
            currentCoupon: null,
            checkedNone: true,
            notUseCouponList: [],
            canUseCouponList: [],

            // 拼团
            collageFlag: 0, //拼团标识：0不参与拼团，1参与拼团
            collageId: 0, //拼团id：参与拼团，若拼团id为空则发起拼团，不为空则与他人拼团

            // 分享抵扣
            shareReductStatus: false,
            reduction: null,
            reductionUserId: 0, //分享抵扣用户id
            shareData: {
                type: 0
            },

            allCount: 0, // 全部商品数量
            // 统计价格(接口返回)
            totalPrice: 0
        }
    },
    computed: {
        ...mapGetters(['userId']),
        cellPadding() {
            return '24rpx 24rpx'
        },
        // 优惠券金额
        couponAmount() {
            if (this.currentCoupon) {
                return this.currentCoupon.couponAmount
            } else {
                return 0
            }
        },
        // 减免金额
        discountedPrice() {
            return this.couponAmount
        },
        // 支付金额
        payAllPrice() {
            const price = this.totalPrice - this.discountedPrice
            if (price < 0) {
                return 0
            }
            return price
        },
        orderInfo() {
            return {
                payAllPrice: this.payAllPrice,
                discountedPrice: this.discountedPrice,
                allCount: this.allCount
            }
        }
    },
    onLoad(options) {
        this.initOptions(options)
        this.orderPaySuccess() // 支付回调
    },
    onShow() {
        this.resetAddress()
    },
    beforeDestroy() {
        uni.removeStorageSync('COMMIT_CART_INFO')
        uni.removeStorageSync('COMMIT_PRODUCT_INFO')
        uni.removeStorageSync('CHOOSE_ADDRESS')
    },
    methods: {
        // 支付成功回调
        orderPaySuccess() {
            this.$on('orderPaySuccess', orderInfo => {
                if (this.collageFlag === 1) {
                    uni.redirectTo({ url: `share-buy/share-buy-detail?collageId=${this.collageId}` })
                } else {
                    uni.setStorageSync('PAY_ORDER_INFO', orderInfo)
                    this.$router.redirectTo('order/pay-success')
                }
            })
        },

        // 商品数量变化
        onCountChange(value) {
            this.confirmParams.productCount = value
            this.initOrderInfo()
        },
        // 初始化参数信息
        initOptions(options) {
            this.submitType = options.type
            this.confirmParams.userId = this.userId
            if (this.submitType === 'product' || this.submitType === 'shareBuy') {
                const productInfo = uni.getStorageSync('COMMIT_PRODUCT_INFO')
                this.submitParams.cartType = 2 // 从商品详情 / 拼单入口提交
                this.confirmParams.productCount = productInfo.productCount
                this.confirmParams.productId = productInfo.productId
                this.confirmParams.heUserId = productInfo.heUserId || 0
                this.confirmParams.collageFlag = this.collageFlag = productInfo.collageFlag
                this.collageId = parseInt(productInfo.collageId) || 0
                this.allCount = productInfo.allCount
            } else {
                const cartInfo = uni.getStorageSync('COMMIT_CART_INFO')
                this.submitParams.cartType = 1 // 从购物车提交
                this.confirmParams.cartIds = cartInfo.cartIds.join()
                this.allCount = cartInfo.allCount
            }
            this.initOrderInfo()
            // this.getUserAddress()
        },

        // 提交订单
        async onSubmit() {
            // 用户id
            this.submitParams.userId = this.userId

            // 校验地址信息
            if (!this.addressInfo) {
                this.$toast('请先添加收货地址～')
                return
            }
            this.submitParams.addressId = this.addressInfo.addressId

            // 优惠券，分享活动相关参数
            this.submitParams.discountInfo = this.getDiscountInfo()

            // 要支付的金额
            this.submitParams.payInfo.orderShouldPayFee = this.payAllPrice

            // 处理商品及留言信息
            this.submitParams.orderInfo = this.shopList.map(shop => {
                const productInfo = shop.productList.map(product => ({
                    productId: product.productId,
                    productNum: product.productCount,
                    heUserId: product.heUserId
                }))
                return { shopId: shop.shopId, note: shop.note, productInfo }
            })

            // 提交订单
            console.log(this.submitParams)

            try {
                const res = await orderSubmit(this.submitParams)
                this.collageId = res.data.collageId
                if (parseFloat(res.data.payableAmount) === 0) {
                    uni.setStorageSync('PAY_ORDER_INFO', res.data)
                    this.$router.redirectTo('order/pay-success')
                } else {
                    this.miniWxPayFor(res.data)
                }
            } catch (e) {
                console.log(e)
            }
        },

        // 优惠券，分享活动相关参数
        getDiscountInfo() {
            return {
                //优惠券ID
                couponId: this.currentCoupon ? this.currentCoupon.couponId : 0,
                //优惠券分享ID
                couponShareId: this.currentCoupon ? this.currentCoupon.couponShareId : 0,
                //拼团标识：0不参与拼团，1参与拼团
                collageFlag: this.collageFlag,
                //拼团id：参与拼团，若拼团id为空则发起拼团，不为空则与他人拼团
                collageId: this.collageId,
                //分享抵扣用户id
                reductionUserId: this.reductionUserId
            }
        },

        // 优惠券操作
        onCouponClick(coupon) {
            if (coupon.controlType === 'choose') {
                this.receiveCouponList.forEach(el => {
                    if (coupon.couponId === el.couponId) {
                        this.$set(el, 'checked', true)
                        this.currentCoupon = el
                    } else {
                        this.$set(el, 'checked', false)
                    }
                })
                this.checkedNone = false
                // this.couponVisiable = false
                // this.sortCouponList()
            }
        },
        // 不使用优惠券
        onCheckedNone() {
            this.receiveCouponList.forEach(el => {
                this.$set(el, 'checked', false)
            })
            this.currentCoupon = null
            this.checkedNone = true
            // this.sortCouponList()
        },

        // 优惠券列表关闭
        onCouponPopupClose() {
            this.couponVisiable = false
            this.sortCouponList()
        },

        // 初始化商品信息
        async initOrderInfo() {
            try {
                const res = await orderConfirm(this.confirmParams)
                this.totalPrice = res.data.totalPrice
                this.shopList = this.bindNoteMessage(res.data.shopList)
                this.initCouponList(res.data.receiveCouponList)
            } catch (e) {
                console.log(e)
            } finally {
                this.isRequest = false
            }
        },

        // 处理优惠券列表
        sortCouponList() {
            // 1将当前选中的优惠券从列表中删除
            // 2将当前选中的优惠券放入最前面
            // 3返回最新的优惠券列表
            // 4查找选中优惠券的索引
            if (this.currentCoupon) {
                const uniqueId = this.currentCoupon.uniqueId
                const index = this.canUseCouponList.findIndex(coupon => coupon.uniqueId === uniqueId)
                // 从列表中删除
                this.canUseCouponList.splice(index, 1)
                // 重新排序 将选中的优惠券放到最前面
                this.canUseCouponList = [
                    this.currentCoupon,
                    ...this.canUseCouponList.sort((a, b) => b.couponAmount - a.couponAmount)
                ]
            } else {
                this.canUseCouponList = this.canUseCouponList.sort((a, b) => b.couponAmount - a.couponAmount)
            }

            // 重新生成receiveCouponList
            this.receiveCouponList = [...this.canUseCouponList, ...this.notUseCouponList]
            console.log(this.receiveCouponList)
        },

        // 初始化优惠券列表
        initCouponList(couponList) {
            const allProductList = this.getAllProductList()
            let { canUseCouponList, notUseCouponList } = splitCouponList(couponList, allProductList)
            this.canUseCouponList = initFormatCouponList(canUseCouponList, 'choose', true)
            this.notUseCouponList = initFormatCouponList(notUseCouponList, 'buy', true)
            this.currentCoupon = this.canUseCouponList[0]
            if (this.currentCoupon) {
                this.checkedNone = false
                this.$set(this.currentCoupon, 'checked', true)
            }
            this.receiveCouponList = [...this.canUseCouponList, ...this.notUseCouponList]
        },

        // 获取全部商品
        getAllProductList() {
            const list = []
            this.shopList.forEach(shop => {
                list.push(...shop.productList)
            })
            return list
        },

        // 为共供应商绑定留言信息
        bindNoteMessage(shopList) {
            return shopList.map(item => {
                item.note = ''
                return item
            })
        },

        // 获取收货地址
        async getUserAddress() {
            try {
                const res = await fetchAddressList({ userId: this.userId })
                this.addressList = res.data.list
                if (res.data.list.length > 0) {
                    this.addressInfo = res.data.list[0]
                    console.log(this.addressInfo)
                }
                return res
            } catch (e) {
                console.log(e)
            }
        },

        // 初始化用户选中地址
        async resetAddress() {
            await this.getUserAddress()
            if (this.$router.checkRefreshType('chooseAddress') || this.$router.checkRefreshType('createAddressBack')) {
                const addressInfo = uni.getStorageSync('CHOOSE_ADDRESS')
                if (addressInfo) {
                    this.addressInfo = this.addressList.find(address => address.addressId === addressInfo.addressId)
                }
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.placeholder {
    font-size: 20rpx;
}
.order-create {
    padding-bottom: 100rpx;
    color: #333;

    .shop-list {
        background-color: #fff;
        padding: 24rpx;

        .section {
            .comment {
                @extend .cm-flex-between;
                margin-top: 24rpx;
                text {
                    width: 80rpx;
                    font-size: 24rpx;
                }
                input {
                    flex: 1;
                    background-color: #f7f7f7;
                    padding: 4rpx 10rpx;
                    font-size: 24rpx;
                }
            }
        }
    }

    .cell-section {
        margin: 16rpx 0;

        .cell-content {
            @extend .cm-flex-between;

            .tip {
                margin-right: 40rpx;
            }

            .reduce {
                color: #f83c6c;
            }

            .postage {
                color: #0062cc;
                margin-right: 0;
            }

            &.share-btn {
                padding: 0;
                margin: 0;
                background-color: transparent;
                font-size: 26rpx;
                line-height: inherit;

                .tip {
                    margin-right: 0;
                }

                &::after {
                    border: 0;
                }
            }
        }
    }
}
</style>
