<template>
    <view class="container order clearfix" :style="{ paddingBottom: isIphoneX ? '170rpx' : '134rpx' }">
        <tui-skeleton v-if="isRequest" loadingType="2"></tui-skeleton>
        <template v-else>
            <!-- 地址选择 v-if="isAddress" -->
            <choice-address ref="choiceAddress" :addressData="addressData"></choice-address>
            <!-- 商品 -->
            <goodsList ref="goods" :goodsData="goodsData" @handleGoodList="handChangeInputGoodsList"></goodsList>
            <!-- 选择优惠券 TODO-->
            <view class="select-coupon" @click="couponVisible = true" v-if="receiveCouponList.length > 0">
                <view class="left-title">优惠券</view>
                <view class="right-content">
                    <view class="coupon-amount">-￥{{ couponAmount | NumFormat }}</view>
                    <view class="iconfont icon-chakangengduo"></view>
                </view>
            </view>
            <!-- 优惠券列表 TODO-->
            <cm-coupon-list
                title="优惠券"
                listType="use"
                :visible="couponVisible"
                @close="closeCouponList"
                :chooseAble="true"
                :showStatus="false"
                :couponList="receiveCouponList"
                @chooseCoupon="chooseCoupon"
                @confirm="closeCouponList"
                :currentId="currentCouponId"
            ></cm-coupon-list>
            <!-- 运费 -->
            <seller-freight ref="freight" :freightDatas="freightData"> </seller-freight>
            <!-- 底部 -->
            <view class="footer" :style="{ paddingBottom: isIphoneX ? '68rpx' : '0rpx' }">
                <view class="footer-le">
                    <view class="footer-count">
                        <text>共{{ allCount }}件商品</text>
                    </view>
                    <view class="footer-price">
                        <view class="sum" :class="totalFullReduction == 0 ? 'none' : ''">
                            <view class="price">总价:￥{{ payAllPrice | NumFormat }}</view>
                            <view class="discount" v-if="discountedPrice > 0"
                                >共减 ￥{{ discountedPrice | NumFormat }}</view
                            >
                        </view>
                    </view>
                </view>
                <view class="footer-submit" @click.stop="orderSubmitMit">
                    <view class="btn" :class="isSubLoading ? 'disabled' : ''">提交订单</view>
                </view>
            </view>
        </template>
        <cm-loading :visible="isSubLoading" :text="loadingText"></cm-loading>
    </view>
</template>

<script>
import authorize from '@/common/authorize.js'
import choiceAddress from '@/components/cm-module/createOrder/address'
import goodsList from '@/components/cm-module/createOrder/goodsList'
import sellerFreight from '@/components/cm-module/createOrder/sellerFreight'
import CmCouponList from '@/components/cm-module/cm-coupon-list/cm-coupon-list'
import CmLoading from '@/components/cm-module/cm-loading/cm-loading.vue'
import { allProdoceUseCheck, someProductUseCheck, couponSort, setCouponUniqueId } from '@/common/couponUtil.js'
import { mapGetters } from 'vuex'
import wechatPay from '@/mixins/wechatPay.js'
export default {
    components: {
        choiceAddress,
        goodsList,
        sellerFreight,
        CmCouponList,
        CmLoading
    },
    // 混入
    mixins: [wechatPay],
    data() {
        return {
            couponVisible: false,
            productIds: '', //获取上一级页面商品信息
            productCount: '', //获取上一级页面商品数量
            allCount: 1, //订单提交总数量
            totalFullReduction: 0, //满减金额
            allPrice: 0.0, //订单总金额
            townId: '', //区ID
            isRequest: true, //是否加载完成渲染子组件
            isAddress: false, //是否加载完成地址
            addressData: {}, //初始化地址信息
            goodsData: [], //初始化商品信息
            freightData: {}, //邮费数据
            productList: [],
            params: {
                userId: 0
            },
            subParams: {
                userId: 0,
                orderInfo: [], //提交的商品信息
                addressId: 0,
                cartType: 0,
                payInfo: {
                    orderShouldPayFee: 0
                }
            },
            orderInfo: '',
            receiveCouponList: [],
            currentCouponId: -1,
            currentCoupon: null,
            loadingText: '正在创建订单',
            canUseCouponList: [],
            notUseCouponList: []
        }
    },
    onLoad(option) {
        //商品数据
        let data = JSON.parse(option.data)
        this.allCount = data.data.allCount
        if (option.type == 'prodcut') {
            this.subParams.cartType = 2
            this.params.productCount = data.data.productCount
            this.params.productId = data.data.productId
            this.params.heUserId = data.data.heUserId ? data.data.heUserId : 0
            this.productIds = data.data.productId.toString()
        } else {
            this.subParams.cartType = 1
            this.params.cartIds = data.data.cartIds
            this.productIds = data.data.productIds
        }
        this.params.userId = this.userId
        this.subParams.userId = this.userId
        this.getInitCrearOrder(this.params)
    },
    computed: {
        ...mapGetters(['userId', 'isIphoneX']),
        // 选中的优惠券的金额
        couponAmount() {
            return this.currentCoupon ? this.currentCoupon.couponAmount : 0
        },
        // 优惠价格
        discountedPrice() {
            return this.couponAmount
        },
        // 支付金额
        payAllPrice() {
            const payAllPrice = this.allPrice - this.couponAmount
            return payAllPrice < 0 ? 0 : payAllPrice
        },
        hanldOrder() {
            return {
                order: this.orderInfo
            }
        }
    },
    filters: {
        NumFormat(value) {
            //处理金额
            return Number(value).toFixed(2)
        }
    },
    methods: {
        // 获取可用优惠券
        fetchCouponList() {
            this.CouponService.GetCouponByProductIds({ userId: this.userId, productIds: this.productIds }).then(res => {
                this.receiveCouponList = setCouponUniqueId(res.data.receiveCouponList) // 去掉重复的优惠券
                this.filterCouponList()
            })
        },
        // 对优惠券进行分类排序
        filterCouponList() {
            this.goodsData.forEach(shop => this.productList.push(...shop.productList.map(prod => prod)))
            this.canUseCouponList = [] // 可以使用的优惠券
            this.notUseCouponList = [] // 需要凑单使用的优惠券
            this.receiveCouponList.forEach(coupon => {
                if (
                    coupon.noThresholdFlag === 1 ||
                    (coupon.productType === 1 && allProdoceUseCheck(this.productList, coupon)) ||
                    (coupon.productType === 2 && someProductUseCheck(this.productList, coupon))
                ) {
                    coupon.canSelect = true
                    this.canUseCouponList.push(coupon)
                } else {
                    coupon.canSelect = false
                    this.notUseCouponList.push(coupon)
                }
            })
            // 金额高的排前面
            this.receiveCouponList = [...couponSort(this.canUseCouponList), ...couponSort(this.notUseCouponList)]
            // 当有可用优惠券时 默认选取第一个最优惠的
            if (this.canUseCouponList.length > 0) {
                this.currentCouponId = this.receiveCouponList[0].uniqueId
                this.currentCoupon = this.receiveCouponList[0]
            }
            // 显示界面
            this.isRequest = false
        },
        // 处理优惠券列表
        resetCouponList() {
            // 2将当前选中的优惠券从列表中删除
            // 3将当前选中的优惠券放入最前面
            // 4返回最新的优惠券列表
            // 查找选中优惠券的索引
            const index = this.canUseCouponList.findIndex(coupon => coupon.uniqueId === this.currentCouponId)
            // 从列表中删除
            const currentCoupon = this.canUseCouponList.splice(index, 1)
            // 重新排序 将选中的优惠券放到最前面
            this.canUseCouponList = [...currentCoupon, ...couponSort(this.canUseCouponList)]
            // 重新生成receiveCouponList
            this.receiveCouponList = [...this.canUseCouponList, ...this.notUseCouponList]
        },
        // 确认选中
        closeCouponList() {
            this.couponVisible = false
            this.resetCouponList()
        },
        // 选中优惠券
        chooseCoupon(coupon) {
            if (coupon.couponId > -1) {
                this.currentCoupon = coupon
                this.currentCouponId = coupon.uniqueId
            } else {
                this.currentCoupon = null
                this.currentCouponId = -1
            }
            // this.couponVisible = false
        },
        //确认订单初始化信息
        getInitCrearOrder(params) {
            this.OrderService.QueryOrderConfirm(params)
                .then(response => {
                    let data = response.data
                    this.goodsData = data.shopList
                    this.allPrice = data.totalPrice

                    this.fetchCouponList()
                })
                .catch(error => {
                    this.$util.msg(error.msg, 2000)
                })
        },
        //获取地址信息
        getAddressData() {
            this.UserService.QueryAddressList({ pageNum: 1, pageSize: 1, userId: this.userId }).then(response => {
                this.isAddress = true
                this.addressData = {}
                if (response.data.list != '') {
                    this.subParams.addressId = response.data.list[0].addressId
                    this.townId = response.data.list[0].townId
                    this.addressData = response.data.list[0]
                } else {
                    this.addressData = this.addressData
                }
            })
        },
        handChangeInputGoodsList(data) {
            //对应供应商的留言信息
            this.goodsData = data
        },
        orderSubmitMit() {
            //提交订单
            if (this.isSubLoading) return
            if (this.subParams.addressId == '') return this.$util.msg('请先添加收货地址～', 2000)
            // 选中的优惠券id
            this.subParams.couponId = this.currentCouponId === -1 ? '' : this.currentCoupon.couponId
            this.subParams.couponShareId = this.currentCoupon ? this.currentCoupon.couponShareId : null
            this.subParams.payInfo.orderShouldPayFee = this.payAllPrice
            // 处理商品信息及留言
            this.subParams.orderInfo = this.goodsData.map(el => {
                let productInfo = []
                el.productList.forEach(pros => {
                    productInfo.push({
                        productId: pros.productId,
                        productNum: pros.productCount,
                        heUserId: pros.heUserId
                    })
                })
                return { shopId: el.shopId, note: el.note ? el.note : '', productInfo: productInfo }
            })
            this.isSubLoading = true
            this.loadingText = '正在创建订单...'
            this.OrderService.CreatedOrderSubmit(this.subParams)
                .then(response => {
                    const data = response.data
                    this.orderInfo = response.data
                    if (parseFloat(data.payableAmount) === 0) {
                        uni.setStorageSync('orderInfo', this.hanldOrder.order)
                        uni.redirectTo({ url: '/pages/user/order/success' })
                    } else {
                        this.miniWxPayFor(data)
                    }
                })
                .catch(error => {
                    this.isSubLoading = false
                    this.$util.msg(error.msg, 2000)
                    this.isSubLoading = false
                })
        }
    },
    onShow() {
        let pages = getCurrentPages()
        let currPage = pages[pages.length - 1]
        if (currPage.data.select == 'select') {
            this.isAddress = true
            let SelectData = uni.getStorageSync('selectAddress')
            this.subParams.addressId = SelectData.addressId
            this.addressData = SelectData
        } else {
            this.getAddressData()
        }
    }
}
</script>

<style lang="scss" scoped>
page {
    height: auto;
    background: #f7f7f7;
}
.container {
    height: initial;
}
.btn-hover {
    background: #ffffff;
}
.animation {
    /* transition: transform 0.3s ease;*/
    transition-property: transform;
    transition-duration: 0.3s;
    transition-timing-function: ease;
}
.invoice-freight {
    width: 702rpx;
    padding: 0 24rpx;
    height: 86rpx;
    line-height: 86rpx;
    font-size: $font-size-28;
    color: $text-color;
    background: #ffffff;
    float: left;
    font-weight: bold;
    .freight-left {
        float: left;
        .icon-yunfeishuoming {
            height: 100%;
            padding: 0 15rpx;
            color: $color-system;
            font-weight: normal;
        }
    }
    .freight-right {
        float: right;
        color: #2a81ff;
    }
}

.select-coupon {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24rpx;
    margin: 24rpx 0;
    height: 90rpx;
    background: #fff;
    .left-title {
        font-weight: bold;
        color: #333333;
        font-size: 28rpx;
    }
    .right-content {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .coupon-amount {
            font-size: 28rpx;
            color: #ff457b;
            margin-right: 12rpx;
        }
        .iconfont {
            font-size: 28rpx;
            color: #b2b2b2;
        }
    }
}

.invoice-balance {
    width: 702rpx;
    height: auto;
    padding: 0 24rpx;
    background: #ffffff;
    float: left;
    margin-top: 24rpx;
    margin-bottom: 24rpx;
    .balabce-t {
        width: 100%;
        height: 86rpx;
        line-height: 86rpx;
        font-size: $font-size-28;
        color: $text-color;
        float: left;
        .balabce-t-le {
            float: left;
            font-weight: bold;
        }
        .balabce-t-ri {
            float: right;
            display: flex;
            align-items: center;
            .money {
                display: flex;
                float: left;
            }
            .checkbox-box {
                display: flex;
                width: 60rpx;
                float: left;
                height: 100%;
                font-size: $font-size-24;
                .checkbox {
                    width: 40rpx;
                    text-align: right;
                    box-sizing: border-box;
                    text-align: center;
                    text-decoration: none;
                    border-radius: 0;
                    -webkit-tap-highlight-color: transparent;
                    overflow: hidden;
                    color: $color-system;
                    padding: 5rpx;
                }
            }
        }
    }
    .balabce-b {
        width: 100%;
        float: left;
        overflow: hidden;
        .balabce-b-text {
            width: 100%;
            line-height: 58rpx;
            font-size: $font-size-24;
            color: #ff457b;
            text-align: right;
            float: right;
        }
        &.balabce-b--hide {
            padding: 0 0;
            height: 0px;
            line-height: 0px;
        }
    }
}
.footer {
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 995;
    display: flex;
    align-items: center;
    width: 100%;
    height: 110rpx;
    justify-content: space-between;
    font-size: $font-size-28;
    background-color: #ffffff;
    z-index: 998;
    color: $text-color;
    border-top: 1px solid #f7f7f7;
    .footer-le {
        width: 570rpx;
        height: 100%;
        float: left;
    }
    .footer-count {
        float: left;
        padding-left: 24rpx;
        line-height: 110rpx;
        width: 170rpx;
        box-sizing: border-box;
        font-size: $font-size-26;
    }
    .footer-price {
        float: right;
        text-align: right;
        color: $text-color;
        padding-right: 20rpx;
        box-sizing: border-box;
        width: 370rpx;
        padding-left: 24rpx;
        .sum {
            display: flex;
            justify-content: center;
            flex-direction: column;
            align-items: flex-start;
            width: 100%;
            height: 110rpx;
            .price {
                font-size: $font-size-32;
                color: $color-system;
            }
            .discount {
                // margin-top: 32rpx;
                font-size: $font-size-24;
                color: #ff457b;
            }
        }
    }
    .footer-submit {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 210rpx;
        height: 100%;
        box-sizing: border-box;
        padding: 15rpx 5rpx;
        .btn {
            width: 100%;
            height: 100%;
            color: #ffffff;
            background: $btn-confirm;
            font-size: $font-size-26;
            text-align: center;
            line-height: 80rpx;
            border-radius: 40rpx;
            &.disabled {
                background: #e4e8eb;
                color: #999999;
            }
        }
    }
}
.Rebate {
    width: 702rpx;
    height: auto;
    padding: 0 24rpx;
    background: #ffffff;
    float: left;
    margin-bottom: 24rpx;
    margin-bottom: 24rpx;
    line-height: 86rpx;
    .rebate-title {
        float: left;
        font-weight: bold;
        color: #333333;
        font-size: $font-size-28;
    }
    .iconfont {
        float: right;
        color: #b2b2b2;
        font-size: 40rpx;
        &.icon-yixuanze {
            color: $color-system;
        }
    }
}
</style>
