<template>
    <view class="order-create">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <!-- 地址选择 -->
        <view class="sticky-top">
            <order-choose-address class="sticky-top" :addressInfo="addressInfo"></order-choose-address>
        </view>
        <!-- 供应商商品列表 -->
        <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" v-if="receiveCouponList.length > 0">
            <tui-list-cell :arrow="true" :padding="cellPadding" :unlined="true">
                <view class="cell-content">
                    <text class="label">优惠券</text>
                    <text class="reduce tip">-￥{{ couponAmount | priceFormat }}</text>
                </view>
            </tui-list-cell>
        </view>
        <!-- 分享减免 -->
        <view class="cell-section" @click="onShare" v-if="reduction">
            <tui-list-cell :arrow="false" :padding="cellPadding" :unlined="true">
                <button class="cell-content share-btn">
                    <text v-if="!shareStatus" class="active label">
                        金额满￥{{ reduction.touchPrice }}元，分享可立减￥{{ reduction.reducedAmount }}元
                    </text>
                    <text class="label" v-else>分享减免</text>
                    <text class="reduce tip" v-if="!shareStatus">点击分享</text>
                    <text class="active" v-else>-￥{{ reduction.reducedAmount | priceFormat }}</text>
                </button>
            </tui-list-cell>
        </view>
        <!-- 运费 -->
        <view class="cell-section">
            <tui-list-cell :arrow="false" :padding="cellPadding" :unlined="true">
                <view class="cell-content">
                    <text class="label">运费</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" :data="posterData" type="normal" @close="onAfterShare"></cm-share-popup>
        <!-- 订单提交拦截 -->
        <tui-modal :show="preventModal" :content="preventText" @click="onPreventModalConfirm"></tui-modal>
        <!-- 安全区域 -->
        <cm-safe-area-bottom></cm-safe-area-bottom>
    </view>
</template>

<script>
import { orderConfirm, orderSubmit, orderReductionShare } from '@/services/api/order.js'
import { fetchAddressList } from '@/services/api/user.js'
import { initFormatCouponList, splitCouponList, chooseBestCoupon } from '@/common/business.helper.js'
import { queryStringify } from '@/common/utils.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,
                couponId: ''
            },

            // 订单提交参数
            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

            allCount: 0, // 全部商品数量
            // 统计价格(接口返回)
            totalPrice: 0,

            preventModal: false,
            preventText: '',

            // 分享数据
            posterData: {},

            shareStatus: false
        }
    },
    computed: {
        ...mapGetters(['userId']),
        cellPadding() {
            return '24rpx 24rpx'
        },
        // 优惠券金额
        couponAmount() {
            if (this.currentCoupon) {
                return this.currentCoupon.couponAmount
            } else {
                return 0
            }
        },
        // 分享减免金额
        shareReducedAmount() {
            return this.reduction && this.shareStatus ? this.reduction.reducedAmount : 0
        },
        // 减免金额
        discountedPrice() {
            return this.couponAmount + this.shareReducedAmount
        },
        // 支付金额
        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)
    },
    onShow() {
        this.resetAddress()
    },
    beforeDestroy() {
        uni.removeStorageSync('COMMIT_CART_INFO')
        uni.removeStorageSync('COMMIT_PRODUCT_INFO')
        uni.removeStorageSync('CHOOSE_ADDRESS')
    },
    onShareAppMessage() {
        // 加密
        const state_str = encodeURIComponent(this.$crypto.encrypt({ type: 0 }))
        return {
            title: '护肤上颜选，正品有好货~',
            path: `/pages/index/index?state_str=${state_str}`,
            imageUrl: this.staticUrl + 'icon-share.png'
        }
    },
    methods: {
        // 分享事件
        onShare() {
            this.posterData = { query: queryStringify({ type: 0 }) }
            this.$refs.sharePopup.open()
        },

        // 分享结束
        async onAfterShare() {
            try {
                if (!this.reduction) return
                const { reductionId } = this.reduction
                const res = await orderReductionShare({ reductionId, shareType: 1, userId: this.userId })
                this.reductionUserId = res.data
                this.$toast('以为您减免金额')
                this.shareStatus = true
            } catch (e) {
                this.$toast('分享失败')
            }
        },

        // 商品数量变化
        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.confirmParams.couponId = productInfo.couponId
                this.collageId = parseInt(productInfo.collageId) || 0 // 拼团id
                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()
        },

        // 提交订单
        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.num,
                    heUserId: product.heUserId
                }))
                return { shopId: shop.shopId, note: shop.note, productInfo, splitCode: shop.splitCode }
            })

            // 提交订单
            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.$router.redirectTo(`order/order-pay?orderId=${res.data.orderId}`)
                }
            } catch (e) {
                console.log(e)
                this.preventModal = true
                this.preventText = e.msg
            }
        },

        // 订单提交拦截确认
        onPreventModalConfirm() {
            this.preventModal = false
            uni.navigateBack({ delta: 1 })
        },

        // 优惠券，分享活动相关参数
        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.reduction = res.data.reduction
                this.shopList = this.bindNoteMessage(res.data.shopList)
                // 只有存在优惠券时才执行后续操作(阻止不必要的计算统计)
                if (res.data.receiveCouponList.length > 0) {
                    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;
            }

            .label {
                font-weight: bold;
            }

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

                .active {
                    color: #f83c6c;
                }

                .tip {
                    margin-right: 0;
                }

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