<template>
    <app-layout>
        <view class="page" v-if="previewData">
            <template v-if="previewData.show_address !== false">
                <view v-if="previewData.allZiti" class="address">
                    <app-order-submit-row :show-nav="false" :no-padding="true">
                        <view class="dir-left-nowrap px-12">
                            <view class="box-grow-1">
                                <app-input placeholder="请填写联系人" height="100"
                                           v-model="previewData.address.name"></app-input>
                            </view>
                            <view class="box-grow-1">
                                <app-input placeholder="请填写手机号" height="100"
                                           v-model="previewData.address.mobile"></app-input>
                            </view>
                        </view>
                        <view slot="footer">
                            <image class="bottom-image" :src="appImg.common.address_bottom"></image>
                        </view>
                    </app-order-submit-row>
                </view>
                <view v-else @click="navigateAddress" class="address">
                    <app-order-submit-row>
                        <view v-if="previewData.address">
                           <!--   <view class="dir-left-nowrap mb-12">
                                <view class="box-grow-1">参训人: {{previewData.address.name}}</view>
                                <view class="box-grow-0">电话: {{previewData.address.mobile}}</view>
                            </view>
                          <view class="mb-12">
                                收货地址:
                                {{previewData.address.province}}
                                {{previewData.address.city}}
                                {{previewData.address.district}}
                                {{previewData.address.detail}}
                            </view> -->
				<!-- 			<view class="dir-left-nowrap mb-12">
								<view class="box-grow-1">性别: {{previewData.address.name}}</view>
								<view class="box-grow-0">年龄: {{previewData.address.mobile}}</view>
                            </view>
							<view class="dir-left-nowrap mb-12">
								<view class="box-grow-1">体重: {{previewData.address.name}}</view>
								<view class="box-grow-0">年龄: {{previewData.address.mobile}}</view>
                            </view>				
							<view class="dir-left-nowrap mb-12">
								<view class="box-grow-1">身高: {{previewData.address.name}}</view>
								<view class="box-grow-0">身份证号码: {{previewData.address.mobile}}</view>
                            </view> -->
							<view class="felx-three">
								<view class="box-grow-2">
									参训人: {{verifyUndefined(previewData.address.name)}}
								</view>	
								<view class="box-grow-3">
									性别: {{verifyUndefined(previewData.address.sex) == ''? '':previewData.address.sex == 0 ?'未知':previewData.address.sex == 1? '男':'女'}}
								</view>	
								<view class="box-grow-4">
									联系电话: {{verifyUndefined(previewData.address.mobile)}}
								</view>
							</view>
							<view class="felx-three">
								<view class="box-grow-2">
									年龄: {{verifyUndefined(previewData.address.age)}}
								</view>	
								<view class="box-grow-3">
									体重: {{verifyUndefined(previewData.address.weight)}}
								</view>	
								<view class="box-grow-4">
									身高: {{verifyUndefined(previewData.address.height)}}
								</view>
							</view>
							<view class="felx-three">
								<view class="box-grow-5">
									身份证号码:{{previewData.address.idcard}}
								</view>	
							</view>
                        </view>
                        <view v-else>请选择收货地址</view>
                        <view v-if="previewData.has_ziti" class="ziti-tip" :class="[`${theme}-color`]">
                            (收货地址中的手机号码将用于自提信息)
                        </view>
                    <!--    <view slot="footer">
                            <image class="bottom-image" :src="appImg.common.address_bottom"></image>
                        </view> -->
                    </app-order-submit-row>
                </view>
            </template>

            <view class="mch-list">
                <view v-for="(mch, mchIndex) in previewData.mch_list"
                      :key="mchIndex"
                      class="mch-item">

                    <view class="mch-name">{{mch.mch.name}}</view>

<!--                    <view v-if="mch.show_delivery !== false" class="dir-left-nowrap cross-center delivery">
                        <view class="box-grow-1">配送方式</view>
                        <view class="box-grow-0">
                            <view v-for="(sendType, sendTypeIndex) in mch.delivery.send_type_list"
                                  :key="sendTypeIndex"
                                  class="send-type"
                                  :class="sendType.value == mch.delivery.send_type ? `${theme}-background` : 'weak-two-background'"
                                  @click="changeSendType(mchIndex,sendType.value)">
                                {{sendType.name}}
                            </view>
                        </view>
                    </view> -->

                    <view class="pick-up cross-center" v-if="!mch.pick_up_enable">
                        <view>以下商品满{{mch.pick_up_price}}元起送</view>
                    </view>

                    <view v-if="mch.delivery.send_type == 'offline'" class="store">
                        <app-order-submit-row v-if="mch.no_store && mch.no_store === true" :show-nav="false">
                            暂无门店，请选择其他配送方式
                        </app-order-submit-row>
                        <app-order-submit-row v-else @click="navigateStore(mchIndex)" :show-nav="mch.mch.id == 0">
                            <view slot="header" class="title">门店信息</view>
                            <template v-if="mch.store">
                                <view class="dir-left-nowrap mb-12">
                                    <view class="box-grow-1">{{mch.store.name}}</view>
                                    <view class="box-grow-0 location">
                                        <image class="icon" src="/static/image/icon/location.png"></image>
                                        <view v-if="getLocationFail" class="inline-block">
                                            <view class="inline-block">定位失败</view>
                                            <view class="inline-block open-location-setting"
                                                  @click.stop="openLocationSetting">
                                                <view class="open-location-btn" :class="[
                                                `${theme}-color`, `${theme}-border`,
                                                ]">获取位置
                                                </view>
                                            </view>
                                        </view>
                                        <view v-else class="inline-block">距离您{{mch.store.distance}}</view>
                                    </view>
                                </view>
                                <view class="store-address">{{mch.store.address}}</view>
                            </template>
                            <view v-else>请选择门店</view>
                        </app-order-submit-row>
                    </view>
                    <view v-else-if="mch.delivery.send_type == 'city' && mch.city" class="city">
                        <template v-if="mch.city.error">
                            <view class="dir-left-nowrap cross-center">
                                <view class="box-grow-1 t-omit error">{{mch.city.error}}</view>
                                <view class="box-grow-0 btn" @click="jump(mchIndex)">查看配送范围</view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="t-omit">发货地址：{{mch.city.address}}</view>
                            <view class="t-omit" v-if="mch.city.explain">{{mch.city.explain}}</view>
                            <view class="dir-left-nowrap cross-center">
                                <view class="box-grow-1 t-omit error" style="color: #353535;">该地址在配送范围内</view>
                                <view class="box-grow-0 btn" @click="jump(mchIndex)">查看配送范围</view>
                            </view>
                        </template>
                    </view>
                    <app-submit-goods v-on:updateList="updateList" :index="mchIndex" :plugin="plugin" :list="mch"></app-submit-goods>
                    <template v-if="mch.insert_rows && mch.insert_rows.length">
                        <view v-for="(insertRow, insertRowIndex) in mch.insert_rows" :key="insertRowIndex">
                            <app-order-submit-row :show-nav="false">
                                <view class="dir-left-nowrap">
                                    <view class="box-grow-1">{{insertRow.title}}</view>
                                    <view class="box-grow-0" :class="[`${theme}-color`]">{{insertRow.value}}</view>
                                </view>
                            </app-order-submit-row>
                        </view>
                    </template>

                    <view v-if="mch.coupon && mch.coupon.enabled" class="coupon" @click="navigateCoupon(mchIndex)">
                        <app-order-submit-row>
                            <view class="dir-left-nowrap">
                                <view class="box-grow-1">优惠券</view>
                                <view class="box-grow-0" v-if="mch.coupon.use" :class="[`${theme}-color`]">
                                    已优惠{{mch.coupon.coupon_discount}}元
                                </view>
                                <view class="box-grow-0 tip" v-else>选择优惠券</view>
                            </view>
                        </app-order-submit-row>
                    </view>

                    <view v-if="mch.integral && mch.integral.can_use" class="integral">
                        <app-order-submit-row
                                :show-nav="false">
                            <view class="dir-left-nowrap">
                                <view class="box-grow-1 dir-left-nowrap">
                                    <view>
                                        使用
                                        {{mch.integral.use_num}}
                                        积分抵扣
                                        <text :class="[`${theme}-color`]">{{mch.integral.deduction_price}}</text>
                                        元
                                    </view>
                                    <view class="tip-btn" @click="showIntegralTip">
                                        <image class="icon" src="/static/image/icon/warning.png"></image>
                                    </view>
                                </view>
                                <view class="box-grow-0">
                                    <app-radio type="round" :value="mch.integral.use" :theme="theme"
                                               @input="changeIntegral(mchIndex)"></app-radio>
                                </view>
                            </view>
                        </app-order-submit-row>
                        <!-- <view>

                        </view> -->
                    </view>

<!--                    <view v-if="mch.show_express_price !== false">
                        <app-order-submit-row :show-nav="false" :showBorder="false">
                            <view class="dir-left-nowrap">
                                <view class="box-grow-1">运费</view>
                                <view class="box-grow-0 express-price" :class="[`${theme}-color`]">
                                    <template v-if="mch.express_price_origin && mch.express_price_desc">
                                        <view>￥{{mch.express_price_origin}}元</view>
                                        <view class="express-price-desc">{{mch.express_price_desc}}
                                        </view>
                                    </template>
                                    <view v-else>￥{{mch.express_price}}元</view>
                                </view>
                            </view>
                        </app-order-submit-row>
                    </view> -->
                    <view v-if="mch.order_form && mch.order_form.status == '1'">
                        <app-diy-form :title="mch.order_form.name"
                                      :list="mch.order_form.value"
                                      @input="handleOrderFormInput"
                                      @validate="handleOrderFormValidate"
                                      :sign="mchIndex"
                                      label-position="top"
                                      :show-scroll-btn="mch.order_form.show_scroll"></app-diy-form>
                    </view>
                    <view v-else-if="mch.show_remark !== false && mch.has_goods_form !== true" class="remark">
                        <app-input @input="inputRemark(mchIndex)"
                                   v-model="mch.remark"
                                   placeholder="买家留言"
                                   height="100"></app-input>
                    </view>

                    <template v-if="mch.has_goods_form">
                        <view v-for="(goodsItem, goodsIndex) in mch.goods_list"
                              :key="goodsIndex"
                              v-if="goodsItem.form && !goodsItem.form.same_form"
                              style="margin-bottom: 20rpx">
                            <view style="padding: 24rpx; color: #666666">{{goodsItem.form.name}}</view>
                            <view class="goods-list" v-if="mch.diff_goods_form_count !== 1">
                                <view v-for="(subGoodsItem, subGoodsIndex) in mch.goods_list"
                                      :key="subGoodsIndex"
                                      v-if="subGoodsItem.form && subGoodsItem.form.id == goodsItem.form.id"
                                      class="dir-left-nowrap goods-item">
                                    <view class="box-grow-0">
                                        <image class="goods-image"
                                               :src="subGoodsItem.goods_attr.pic_url ? subGoodsItem.goods_attr.pic_url : subGoodsItem.cover_pic"></image>
                                    </view>
                                    <view class="box-grow-1">
                                        <view class="goods-name">{{subGoodsItem.name}}</view>
                                        <view class="dir-left-wrap attr-list">
                                            <view v-for="(attrItem,attrIndex) in subGoodsItem.attr_list"
                                                  :key="attrIndex"
                                                  class="attr-item">
                                                {{attrItem.attr_group_name}}:{{attrItem.attr_name}}
                                            </view>
                                        </view>
                                        <view class="dir-left-nowrap">
                                            <view class="box-grow-1 goods-num">×{{subGoodsItem.num}}</view>
                                            <view class="box-grow-0 goods-price-info" :class="[`${theme}-color`]">
                                                <view>
                                                    <text v-for="(customCurrency,customCurrencyIndex) in subGoodsItem.custom_currency"
                                                          :key="customCurrencyIndex">
                                                        {{customCurrency}}+
                                                    </text>
                                                    <text class="goods-price-unit">￥</text>
                                                    <text>{{subGoodsItem.total_original_price}}</text>
                                                </view>
                                                <view v-for="(discount,discountIndex) in subGoodsItem.discounts"
                                                      :key="discountIndex">
                                                    {{discount.name}}: {{discount.value}}
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </view>
                            <app-diy-form
                                    :list="goodsItem.form.value"
                                    @input="handleGoodsFormInput"
                                    @validate="handleGoodsFormValidate"
                                    :sign="`${mchIndex},${goodsIndex},${goodsItem.form.id}`"></app-diy-form>
                        </view>
                    </template>

                </view><!-- mch item end -->
            </view>
        </view>
        <view>
            <view class="submit-bar dir-left-nowrap" v-if="previewData">
                <view class="box-grow-1 cross-center order-info" :class="[`${theme}-color`]">
                    <view style="display: inline-block;">{{totalTitle}}:</view>
                    <view style="display: inline-block;"
                                v-for="custom_currency in previewData.custom_currency_all" :key="custom_currency">
                        {{custom_currency}}+
                    </view>
                    <view style="display: inline-block;white-space: nowrap;">￥{{previewData.total_price}}
                        <view style="content: '  ';display: inline-block;width: 20rpx;"></view>
                    </view>
                </view>
                <template v-if="previewData.address_enable && previewData.price_enable">
                    <view @click="subscribe" class="submit-btn box-grow-0 cross-center"
                                :class="[`${theme}-background`, submitLock?'lock':'']">
                        <view style="background-color: transparent;color:#ffffff;">提交</view>
                    </view>
                </template>
                <template v-else>
                    <view v-if="!previewData.address_enable" class="submit-btn box-grow-0 cross-center disabled"
                                :class="[`${theme}-background`]">
                        <view style="background-color: transparent;">该地区无货</view>
                    </view>
                    <view v-else class="submit-btn box-grow-0 cross-center disabled"
                                :class="[`${theme}-background`]">
                        <view style="background-color: transparent;">未达起送要求</view>
                    </view>
                </template>
            </view>
        </view>
    </app-layout>
</template>

<script>
    import {mapState} from 'vuex';
    import AppRadio from '../../components/basic-component/app-radio/app-radio.vue';
    import AppOrderSubmitRow from './app-order-submit-row.vue';
    import AppDiyForm from "../../components/page-component/app-diy-form/app-diy-form";
    import appSubmitGoods from '../../components/basic-component/app-submit-goods/app-submit-goods.vue';

    export default {
        name: 'order-submit',
        components: {AppDiyForm, AppRadio, AppOrderSubmitRow, appSubmitGoods},
        data() {
            return {
                totalTitle: '合计',
                check: false,
                previewData: null,
                getLocationFail: false,
                previewUrl: null,
                submitUrl: null,
                plugin: null,
                orderPageUrl: null,
                submitLock: false,
                getPayDataTimer: null,
                userTheme: null,
                payDataUrl: null,
                showPayResult: true,
                payCancelUrl: null,
            };
        },
        computed: {
            ...mapState({
                appImg: state => state.mallConfig.__wxapp_img,
            }),
            theme() {
                return this.userTheme ? this.userTheme : this.$store.state.mallConfig.theme;
            },
        },
        onLoad(options) {

            if (this.submitLock) return;
            this.setFormData(options);
            this.$event.on(this.$const.EVENT_USER_LOGIN).then(() => {
                this.loadPreviewData();
            });
        },
        onShow() {
            if (this.submitLock) return;
            // #ifdef MP-BAIDU
            setTimeout(() => {
                this.loadPreviewData();
            }, 50);
            // #endif
            // #ifndef MP-BAIDU
            this.loadPreviewData();
            // #endif
        },
        onHide() {
            console.log('onHide');
        },
        onUnload() {
            console.log('onUnload');
            if (this.getPayDataTimer) {
                clearTimeout(this.getPayDataTimer);
            }
        },
        watch: {
            'previewData.address.name': {
                handler() {
                    this.changeZitiAddress();
                },
            },
            'previewData.address.mobile': {
                handler() {
                    this.changeZitiAddress();
                },
            },
        },
        methods: {
			verifyUndefined(value){
				// if(value == 'undefined' || value == ''){
				// 	return ''
				// }else{
				// 	return value
				// }
				console.log(value)
				return (value == 'undefined' || value == '')? '': value
			},
            updateList(e,index) {
                this.previewData.mch_list[index] = e;
                console.log(this.previewData.mch_list)
                this.$forceUpdate();
            },
            setParams(options) {
                if (options.total_title) {
                    this.totalTitle = options.total_title;
                }
            },
            handleOrderFormInput(data, sign) {
                const result = [];
                for (let i in data) {
                    result[i] = {
                        key: data[i].key,
                        label: data[i].name,
                        value: data[i].value,
                        required: data[i].is_required,
                    };
                }
                const formData = this.$store.state.orderSubmit.formData;
                formData.list[sign].order_form = result;
                this.$store.commit('orderSubmit/mutSetFormData', formData);
            },
            handleOrderFormValidate(result, sign) {
                console.log('handleOrderFormValidate:', result, sign);
                const formData = this.$store.state.orderSubmit.formData;
                formData.list[sign].order_form_validate_result = result;
                this.$store.commit('orderSubmit/mutSetFormData', formData);
            },
            setFormData(options) {
                this.previewUrl = decodeURIComponent(options.preview_url || this.$api.order.preview);
                this.submitUrl = decodeURIComponent(options.submit_url || this.$api.order.submit);
                this.plugin = options.plugin || null;
                console.log(options.plugin);
                this.orderPageUrl = decodeURIComponent(options.order_page_url || '/pages/order/index/index?status=0');
                this.userTheme = options.theme || null;
                this.payDataUrl = decodeURIComponent(options.pay_data_url || this.$api.order.pay_data);
                this.payCancelUrl = options.pay_cancel_url ? decodeURIComponent(options.pay_cancel_url) : null;
                this.showPayResult = options.show_pay_result || true;
                if (this.showPayResult === 'true') this.showPayResult = true;
                if (this.showPayResult === 'false') this.showPayResult = false;
                const list = JSON.parse(options.mch_list);
                for (let i in list) {
                    list[i].distance = 0;
                    list[i].remark = '';
                    list[i].order_form = [];
                    list[i].use_integral = 0;
                    list[i].user_coupon_id = 0;
                    for (let j in list[i].goods_list) {
                        list[i].goods_list[j].cart_id = list[i].goods_list[j].cart_id || 0;
                    }
                }
                this.$store.commit('orderSubmit/mutSetFormData', {
                    list: list,
                    address_id: 0,
                });
            },
            loadPreviewData() {
                uni.showLoading({
                    mask: true,
                    title: '加载中',
                });
                this.$request({
                    url: this.previewUrl,
                    method: 'post',
                    data: {
                        form_data: JSON.stringify(this.$store.state.orderSubmit.formData),
                    },
                }).then(response => {
                    uni.hideLoading();
                    if (response.code === 0) {
                        if (response.data.allZiti && !response.data.address) {
                            response.data.address = {
                                name: '',
                                mobile: '',
                            };
                        }
                        this.previewData = response.data;
                        this.setDiyFormScrollStatus();
                        this.checkCouponError();
                        this.updateStoreDistance();
                    } else {
                        uni.showModal({
                            title: '提示',
                            content: response.msg,
                            showCancel: false,
                            success: () => {
                                uni.navigateBack();
                            },
                        });
                    }
                }).catch(() => {
                    uni.hideLoading();
                });
            },
            navigateAddress() {
                let url = '/pages/order-submit/address-pick';
                url += '?hasCity=' + this.previewData.hasCity;
                uni.navigateTo({
                    url: url,
                });
            },
            navigateStore(mchIndex) {
                if (this.previewData.mch_list[mchIndex].mch.id != 0) {
                    return;
                }
                let firstGoodsId = '';
                if (this.plugin === 'booking') {
                    firstGoodsId = this.previewData.mch_list[0].goods_list[0].id;
                }
                let plugin = this.plugin || '';
                uni.navigateTo({
                    url: `/pages/order-submit/store-pick?mchIndex=${mchIndex}&plugin=${plugin}&firstGoodsId=${firstGoodsId}`,
                });
            },
            navigateCoupon(mchIndex) {
                uni.navigateTo({
                    url: `/pages/order-submit/coupon-pick?mchIndex=${mchIndex}`,
                });
            },
            changeZitiAddress() {
                const formData = this.$store.state.orderSubmit.formData;
                formData.address = {
                    name: this.previewData.address.name,
                    mobile: this.previewData.address.mobile,
                };
                this.$store.commit('orderSubmit/mutSetFormData', formData);
            },
            changeSendType(mchIndex, value) {
                if (this.previewData.mch_list[mchIndex].delivery.send_type == value) return;
                const formData = this.$store.state.orderSubmit.formData;
                formData.list[mchIndex].send_type = value;
                this.$store.commit('orderSubmit/mutSetFormData', formData);
                this.previewData.mch_list[mchIndex].delivery.send_type = value;
                this.loadPreviewData();
            },
            updateStoreDistance() {
                if (!this.previewData) return;
                if (!this.previewData.has_ziti && this.plugin != 'booking') {
                    return;
                }
                uni.getLocation({
                    success: (res) => {
                        for (let i in this.previewData.mch_list) {
                            if (!this.previewData.mch_list[i].store) {
                                continue;
                            }
                            if (this.previewData.mch_list[i].store.distance
                                && this.previewData.mch_list[i].store.distance != '-m') {
                                continue;
                            }
                            const distance = this.$utils.earthDistance({
                                lat: res.latitude,
                                lng: res.longitude
                            }, {
                                lat: this.previewData.mch_list[i].store.latitude,
                                lng: this.previewData.mch_list[i].store.longitude
                            });
                            let distanceStr = '-m';
                            if (distance > 1000) {
                                distanceStr = (distance / 1000).toFixed(2) + 'km';
                            } else {
                                distanceStr = distance.toFixed(0) + 'm';
                            }
                            this.previewData.mch_list[i].store.distance = distanceStr;
                        }
                    },
                    fail: () => {
                        this.getLocationFail = true;
                    },
                });
            },
            openLocationSetting() {
                this.getLocationFail = false;
                uni.openSetting({});
            },
            showIntegralTip() {
                uni.showModal({
                    title: '积分抵扣说明',
                    content: this.$store.state.mallConfig.mall.setting.member_integral_rule,
                    showCancel: false,
                });
            },
            changeIntegral(mchIndex) {
                const formData = this.$store.state.orderSubmit.formData;
                const use = !this.previewData.mch_list[mchIndex].integral.use;
                formData.list[mchIndex].use_integral = use ? 1 : 0;
                this.previewData.mch_list[mchIndex].integral.use = use;
                this.loadPreviewData();
            },
            inputRemark(mchIndex) {
                const formData = this.$store.state.orderSubmit.formData;
                formData.list[mchIndex].remark = this.previewData.mch_list[mchIndex].remark;
                this.$store.commit('orderSubmit/mutSetFormData', formData);
            },
            submit() {
                uni.showLoading({
                    mask: true,
                    title: '提交中',
                });
                this.$request({
                    url: this.submitUrl,
                    method: 'post',
                    data: {
                        form_data: JSON.stringify(this.$store.state.orderSubmit.formData),
                    },
                }).then(response => {
                    if (response.code === 0) {
                        this.getPayOrderId(response.data.queue_id, response.data.token);
                    } else {
                        this.submitLock = false;
                        uni.hideLoading();
                        uni.showModal({
                            title: '提示',
                            content: response.msg,
                            showCancel: false,
                        });
                    }
                }).catch(e => {
                    this.submitLock = false;
                    uni.hideLoading();
                    uni.showModal({
                        title: '提示',
                        content: e.errMsg,
                        showCancel: false,
                    });
                });
            },
            getPayOrderId(queue_id, token) {
                this.$request({
                    url: this.payDataUrl,
                    method: 'post',
                    data: {
                        queue_id: queue_id,
                        token: token,
                    },
                }).then(response => {
                    if (response.code === 0) {
                        if (response.data.retry && response.data.retry === 1) {
                            this.getPayDataTimer = setTimeout(() => {
                                this.getPayOrderId(queue_id, token);
                            }, 1000);
                        } else {
                            console.log(response);
                            uni.hideLoading();
                            this.pay(response.data);
                        }
                    } else {
                        this.submitLock = false;
                        uni.hideLoading();
                        uni.showModal({
                            title: '提示',
                            content: response.msg,
                            showCancel: false,
                        });
                    }
                }).catch(e => {
                    this.submitLock = false;
                    uni.hideLoading();
                    uni.showModal({
                        title: '提示',
                        content: e.errMsg,
                        showCancel: false,
                    });
                });
            },
            pay(data) {
                this.$payment.pay(data.id).then(res => {
                    console.log('支付成功', res);
                    if (this.showPayResult) {
                        uni.redirectTo({
                            url: `/pages/order-submit/pay-result?payment_order_union_id=${data.id}&order_page_url=${encodeURIComponent(this.orderPageUrl)}`,
                        });
                    } else {

                        let page_url = this.orderPageUrl;
                        if (page_url.indexOf('?') === -1) {
                            page_url += '?'
                        } else {
                            page_url += '&';
                        }

                        delete data.id;

                        page_url += `pay_data=${JSON.stringify(data)}`;

                        uni.redirectTo({
                            url: page_url,
                        });
                    }
                }).catch(e => {
                    console.log('支付失败', e);
                    if (this.payCancelUrl) {
                        let page_url = this.payCancelUrl;
                        if (page_url.indexOf('?') === -1) {
                            page_url += '?'
                        } else {
                            page_url += '&';
                        }
                        page_url += `pay_data=${JSON.stringify(data)}`;
                        uni.redirectTo({
                            url: page_url,
                        });
                    } else {
                        uni.showModal({
                            title: '提交失败',
                            content: e.errMsg,
                            showCancel: false,
                            success: () => {
                                uni.redirectTo({
                                    url: this.orderPageUrl,
                                });
                            },
                        });
                    }
                });
            },
            jump(mchIndex) {
                uni.navigateTo({
                    url: `/pages/order-submit/map`,
                });
            },
            checkCouponError() {
                for (let i in this.previewData.mch_list) {
                    if (this.previewData.mch_list[i].coupon && this.previewData.mch_list[i].coupon.coupon_error) {
                        uni.showModal({
                            title: '',
                            content: this.previewData.mch_list[i].coupon.coupon_error,
                            showCancel: false,
                        });
                        return;
                    }
                }
            },
            setDiyFormScrollStatus() {
                console.log('this.previewData.mch_list--->', this.previewData.mch_list);
                for (let i in this.previewData.mch_list) {
                    if (
                        this.previewData.mch_list[i].order_form
                    ) {
                        if (
                            this.previewData.mch_list[i].order_form.value
                            && this.previewData.mch_list[i].order_form.value.length
                            && this.previewData.mch_list[i].order_form.value.length >= 5
                        ) {
                            this.previewData.mch_list[i].order_form.show_scroll = true;
                        } else {
                            this.previewData.mch_list[i].order_form.show_scroll = false;
                        }
                    }
                }
            },
            subscribe() {
                for (let i in this.$store.state.orderSubmit.formData.list) {
                    const item = this.$store.state.orderSubmit.formData.list[i];
                    if (!item.order_form_validate_result) continue;
                    if (item.order_form_validate_result.hasError) {
                        uni.showModal({
                            title: '提示',
                            content: item.order_form_validate_result.errors[0].msg,
                            showCancel: false,
                        });
                        return;
                    }
                }
                for (let i in this.$store.state.orderSubmit.formData.list) {
                    for (let j in this.$store.state.orderSubmit.formData.list[i].goods_list) {
                        const item = this.$store.state.orderSubmit.formData.list[i].goods_list[j];
                        if (!item.goods_form_validate_result) continue;
                        if (item.goods_form_validate_result.hasError) {
                            uni.showModal({
                                title: '提示',
                                content: item.goods_form_validate_result.errors[0].msg,
                                showCancel: false,
                            });
                            return;
                        }
                    }
                }
                if (this.submitLock) return;
                this.submitLock = true;
                this.$subscribe(this.previewData.template_message_list).then(res => {
                    this.submit();
                }).catch(res => {
                    this.submit();
                });
            },
            handleGoodsFormInput(data, sign) {
                const signArr = sign.split(',');
                const mchIndex = parseInt(signArr[0]);
                const goodsIndex = parseInt(signArr[1]);
                const formId = parseInt(signArr[2]);
                const result = [];
                for (let i in data) {
                    result[i] = {
                        key: data[i].key,
                        label: data[i].name,
                        value: data[i].value,
                        required: data[i].is_required,
                    };
                }
                const formData = this.$store.state.orderSubmit.formData;
                formData.list[mchIndex].goods_list[goodsIndex].form_data = result;
                this.$store.commit('orderSubmit/mutSetFormData', formData);
            },
            handleGoodsFormValidate(result, sign) {
                const signArr = sign.split(',');
                const mchIndex = parseInt(signArr[0]);
                const goodsIndex = parseInt(signArr[1]);
                const formData = this.$store.state.orderSubmit.formData;
                formData.list[mchIndex].goods_list[goodsIndex].goods_form_validate_result = result;
                this.$store.commit('orderSubmit/mutSetFormData', formData);
            },
        },
    }
</script>

<style scoped lang="scss">
    $submitBarHeight: #{110rpx};
    $borderColor: $uni-weak-color-one;
    $xWidth: #{24rpx};
    $yWidth: #{24rpx};
	.felx-three{
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding-bottom: 23rpx;
		.box-grow-2, .box-grow-3, .box-grow-4{
			font-size: 24rpx;
			font-family: Source Han Sans CN;
			font-weight: 400;
			color: rgba(100,100,100,1);
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}	
		.box-grow-2{
			width: 30%;
		}
		.box-grow-3{
			width: 30%;
		}
		.box-grow-4{
			width: 40%;
		}
		.box-grow-5{
			width: 100%;
			font-size: 24rpx;
			font-family: Source Han Sans CN;
			font-weight: 400;
			color: rgba(100,100,100,1);
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
    .pick-up {
        margin-top: #{20rpx};
        background: #fff4f3;
        height: #{80rpx};
        width: 100%;
        padding: 0 #{24rpx};
        font-size: #{28rpx};
        color: #353535;
    }

    .px-12 {
        padding-left: #{12rpx};
        padding-right: #{12rpx};
    }

    .mb-12 {
        margin-bottom: #{12rpx};
    }

    .page {
        min-height: 100%;
        border-top: #{1rpx} solid $borderColor;
        padding-bottom: $submitBarHeight;

        .address {
            margin-bottom: $yWidth;

            .bottom-image {
                width: 100%;
                height: #{8rpx};
                display: block;
            }
        }

        .mch-list {
            .mch-name {
				background-color: #fff;
                padding: $yWidth $xWidth;
            }

            .delivery {
                background: #fff;
                padding: $yWidth $xWidth;

                .send-type {
                    display: inline-block;
                    padding: #{8rpx} #{24rpx};
                    border-radius: #{100rpx};
                    margin-right: $xWidth;
                    font-size: $uni-font-size-general-one;
                }

                .send-type:last-child {
                    margin-right: 0;
                }

                .send-type.active {
                    color: #fff;
                }
            }

            .store {
                .title {
                    padding: $yWidth $xWidth 0;
                }

                .store-address {
                    color: $uni-general-color-two;
                }

                .location {
                    padding: 0 #{48rpx};

                    .icon {
                        width: #{22rpx};
                        height: #{26rpx};
                        margin-right: #{12rpx};
                    }

                    .inline-block {
                        display: inline-block;
                        vertical-align: top;
                    }

                    .open-location-setting {
                        margin-top: -#{2rpx};
                        padding-left: #{12rpx};
                    }

                    .open-location-btn {
                        font-size: $uni-font-size-weak-one;
                        height: #{44rpx};
                        line-height: #{42rpx};
                        padding: 0 #{16rpx};
                        border: #{1rpx} solid;
                        border-radius: #{1000rpx};
                    }
                }
            }

            .city {
                padding: #{32rpx} #{24rpx};
                background-color: #ffffff;
                margin-bottom: #{20rpx};
                font-size: $uni-font-size-general-one;

                .error {
                    color: #ff4544;
                    margin-right: #{24rpx};
                }

                .btn {
                    padding: #{10rpx} #{20rpx};
                    border-radius: #{100rpx};
                    border: #{1rpx} solid #cccccc;
                    font-size: $uni-font-size-general-two;
                    color: $uni-general-color-one;
                }
            }

            .goods-list {
                border-bottom: #{1rpx} solid $borderColor;

                .goods-item {
                    background: #fff;
                    padding: #{24rpx};

                    .goods-image {
                        width: #{200rpx};
                        height: #{200rpx};
                        display: block;
                        margin-right: #{24rpx};
                    }

                    .goods-name {
						font-size:24rpx;
						font-family:Source Han Sans CN;
						font-weight:400;
						color:rgba(72,72,72,1);
                        height: #{84rpx};
                        line-height: #{42rpx};
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 2;
                        overflow: hidden;
                        margin-bottom: #{22rpx};
                    }

                    .attr-list, .goods-num {
                        font-size: $uni-font-size-weak-one;
                        color: $uni-general-color-one;
                    }

                    .attr-item {
                        margin-right: #{24rpx};
                    }

                    .attr-item:last-child {
                        margin-right: 0;
                    }

                    .goods-price-info {
                        text-align: right;
                        font-size: $uni-font-size-general-one;
                    }
                }
            }

            .express-price {
                text-align: right;

                .express-price-desc {
                    font-size: $uni-font-size-weak-one;
                }
            }

            .coupon {

                .active {
                    color: $uni-important-color-red;
                }

                .tip {
                    color: $uni-general-color-two;
                }
            }

            .integral {
                .tip-btn {
                    font-size: 0;
                    padding: #{12rpx};
                    margin-top: -#{7rpx};
                    /* #ifdef MP-ALIPAY*/
                    margin-top: -#{14rpx};
                    /* #endif*/
                }

                .icon {
                    width: #{36rpx};
                    height: #{36rpx};
                    display: block;
                }
            }

            .remark {
                background: #fff;
                border-bottom: #{1rpx} solid $borderColor;
                padding: 0 #{12rpx};
            }
        }
    }

    .submit-bar {
        background: #fff;
        border-top: #{1rpx} solid $uni-weak-color-two;
        height: $submitBarHeight;
        position: fixed;
        left: 0;
        bottom: 0;
        width: 100%;
        z-index: 1000;

        .order-info {
            padding: 0 #{24rpx};
        }

        .submit-btn {
            height: 100%;
            padding: 0 #{50rpx};
        }

        .submit-btn:active {
            box-shadow: inset 0 0 #{500rpx} rgba(0, 0, 0, .15);
        }

        .submit-btn.lock {
            box-shadow: inset 0 0 #{500rpx} rgba(255, 255, 255, 0.35);
        }

        .submit-btn.disabled {
            background: $uni-general-color-two;
        }
    }
</style>
