<template>
    <div
        class="page"
        :class="{ 'page--iphoneX': iphoneX, bTip: minChaPrice > 0 }"
    >
        <img
            class="page__parting-line"
            src="/static/order/parting-line.jpg"
            alt
        />
        <div
            class="tab"
            v-if="
                deliveryConfig.deliveryMethod.homeDelivery ||
                deliveryConfig.deliveryMethod.storePickUp
            "
        >
            <a
                v-if="deliveryConfig.deliveryMethod.homeDelivery"
                class="tab__item"
                :class="{ on: curTab === 2 }"
                @click="tabChange(2)"
                >{{ productSource === "1" ? "快递到家" : "配送到家" }}</a
            >
            <a
                v-if="
                    deliveryConfig.deliveryMethod.storePickUp &&
                    productSource !== '1'
                "
                class="tab__item"
                :class="{ on: curTab === 1 }"
                @click="tabChange(1)"
                >门店自提</a
            >
        </div>
        <p class="address__warn" v-if="curTab === 0">
            店铺配置错误，请至少选择一种配送方式
        </p>
        <!-- <div class="shop" v-if="curTab === 1">
            <i class="iconfont icondizhi dizhi"></i>
            <div class="con">
                <div class="shop__name">提货地址：{{ activeShop.name }}</div>
                <p class="shop__des">
                    {{
                        activeShop.province +
                        activeShop.city +
                        activeShop.county +
                        activeShop.address
                    }}
                </p>
            </div>
        </div> -->
        <div v-if="curTab === 1">
            <div class="address">
                <i class="iconfont icondizhi address__dizhi"></i>
                <div class="address__content">
                    <div class="address__left">
                        <div class="address__name">
                            门店：{{ activeShop.name }}
                        </div>
                        <div class="address__text">
                            提货地址：{{
                                selfPickUpAddress.province +
                                selfPickUpAddress.city +
                                selfPickUpAddress.county +
                                selfPickUpAddress.address
                            }}
                        </div>
                    </div>
                    <!-- <i class="iconfont iconarrow address__arrows"></i> -->
                </div>
            </div>
            <div class="my-address">
                <span>提货人：</span>
                <input
                    class="my-address__input"
                    type="text"
                    v-model="address2.userName"
                    placeholder="提货人姓名"
                />
            </div>
            <div class="my-address">
                <span>手机号：</span>
                <input
                    class="my-address__input"
                    type="text"
                    v-model="address2.telNumber"
                    placeholder="联系方式"
                />
            </div>
        </div>
        <div v-if="curTab === 2">
            <div
                class="address"
                v-if="address.id || address.errMsg || address.lastAddress"
                :class="{ readdress: address.reAddress }"
                @click="setAddress"
            >
                <i class="iconfont icondizhi address__dizhi"></i>
                <div class="address__content">
                    <div class="address__left">
                        <div class="address__name" v-if="!address.reAddress">
                            {{
                                "收货人：" +
                                (address.userName || "") +
                                " " +
                                (address.telNumber || "")
                            }}
                        </div>
                        <div
                            class="address__text"
                            :class="{ black: address.reAddress }"
                            v-if="address.regionInfo"
                        >
                            {{
                                "收货地址：" +
                                (address.regionInfo || "") +
                                (address.detailInfo || "")
                            }}
                        </div>
                        <div
                            class="address__text"
                            :class="{ black: address.reAddress }"
                            v-else
                        >
                            {{
                                "收货地址：" +
                                (address.provinceName || "") +
                                (address.cityName || "") +
                                (address.countyName || "") +
                                (address.detailInfo || "")
                            }}
                        </div>
                    </div>
                    <i class="iconfont iconarrow address__arrows"></i>
                </div>
            </div>
            <!-- v-else -->
            <div class="address-null" v-else @click="openAddress">
                <div class="address-null__title">请填写收货地址</div>
                <i class="iconfont iconarrow address-null__arrows"></i>
            </div>
            <div class="my-address" v-if="address && address.reAddress">
                <span>门牌号：</span>
                <input
                    class="my-address__input"
                    type="text"
                    v-model="myAddress"
                    placeholder="详细地址，例1层101室"
                />
            </div>
            <div class="my-address" v-if="address && productSource != '1'">
                <span>收货人：</span>
                <input
                    class="my-address__input"
                    type="text"
                    v-model="address.userName"
                    placeholder="收货人"
                />
            </div>
            <div class="my-address" v-if="address && productSource != '1'">
                <span>手机号：</span>
                <input
                    class="my-address__input"
                    type="text"
                    v-model="address.telNumber"
                    placeholder="11位手机号"
                />
            </div>
            <p class="address__warn" v-if="distance">{{ distanceTxt }}</p>
        </div>
        <div class="page__title" v-if="curTab === 2 && productSource !== '1'">
            <!-- <div class="text">配送时间</div>
            <div class="val" @click="showTime">
                {{ selectTime }}
                <i class="iconfont iconarrow arrows"></i>
            </div> -->
            <div class="text">订单详情</div>
        </div>
        <!-- <div class="page__title" v-if="productSource==='1'">
            <div class="text">订单详情</div>
            <div class="val" >
            </div>
        </div> -->
        <!-- <div class="deliveryTips" v-if="curTab === 2 && deliveryConfig.deliveryTips && productSource!=='1'">
            说明：{{deliveryConfig.deliveryTips}}
        </div> -->
        <div class="page__title" v-if="curTab === 1">
            <div class="text">提货时间</div>
            <div class="val" @click="showTime">
                {{ selectTime }}
                <i class="iconfont iconarrow arrows"></i>
            </div>
        </div>
        <ul class="goods">
            <li
                class="goods__item"
                v-for="(item, index) in goodsList"
                :key="index"
            >
                <div class="goods__img">
                    <my-image :src="item.productImage"></my-image>
                </div>
                <div class="goods__title">{{ item.productName }}</div>
                <div class="goods__right">
                    <div class="goods__price">
                        ¥{{ item.price | minuteToRmb }}
                    </div>
                    <f-input-number
                        v-model="item.count"
                        :initVal="item.count"
                        :max="item.stock"
                        @change="setCaetNum(item)"
                    ></f-input-number>
                </div>
            </li>
        </ul>
        <ul class="list">
            <li class="list__item">
                <div class="list__left">
                    <div class="list__title">商品总和：</div>
                </div>
                <div class="list__right">
                    <div class="list__price">
                        {{ "¥" + (shopAmount || "0.00") }}
                    </div>
                </div>
            </li>
            <li class="list__item" v-if="orderData.pointInfo.canUsePoints">
                <div class="list__left">
                    <div class="list__title">积分抵扣：</div>
                    <div
                        class="list__text"
                        :class="{ price_color: orderData.pointInfo.points }"
                    >
                        {{ integralDeductionStr }}
                    </div>
                </div>
                <div class="list__right">
                    <switch
                        :checked="deduction"
                        :disabled="integral < 1 || totalAmount < 0"
                        @change="switchChange"
                    />
                </div>
            </li>
            <!-- <li class="list__item">
                <div class="list__left">
                    <div class="list__title">快递运费：</div>
                    <div class="list__text">{{ express.expressName }}</div>
                </div>
                <div class="list__right">
                    <div class="list__price">{{ '¥' + (express.postage || '0.00') }}</div>
                </div>
            </li>-->
            <li
                class="list__item"
                v-if="curTab === 2 && deliveryConfig.deliveryFee"
            >
                <div class="list__left">
                    <div class="list__title">配送费：</div>
                    <!-- <div class="list__text">{{ deliveryConfig.deliveryFee }}</div> -->
                </div>
                <div class="list__right">
                    <div class="list__price">
                        + ¥{{ deliveryConfig.deliveryFee }}
                    </div>
                </div>
            </li>
            <li class="list__item" v-if="deliveryConfig.packageFee">
                <div class="list__left">
                    <div class="list__title">打包费：</div>
                    <!-- <div class="list__text">{{ deliveryConfig.packageFee }}</div> -->
                </div>
                <div class="list__right">
                    <div class="list__price">
                        + ¥{{ deliveryConfig.packageFee }}
                    </div>
                </div>
            </li>
            <li class="list__item" @click="openCoupon">
                <div class="list__left">
                    <div class="list__title">选择优惠：</div>
                    <div class="list__text">
                        {{ coupon.name || "不使用优惠券" }}
                    </div>
                </div>
                <div class="list__right" v-if="coupon">
                    <div class="list__price price_color">
                        - ¥{{ coupon.value | minuteToRmb }}
                    </div>
                </div>
            </li>
            <li class="list__item">
                <div class="list__left">
                    <div class="list__title">店铺合计：</div>
                </div>
                <div class="list__right">
                    <!-- <div class="list__price">{{ '¥' + (totalAmount2 || '0.00') }}</div> -->
                    <div class="list__price">
                        {{ "¥" + (payAmount || "0.00") }}
                    </div>
                </div>
            </li>
        </ul>
        <div class="remark">
            <input
                class="remark__input"
                type="text"
                v-model="remark"
                placeholder="选填：给卖家留言"
            />
        </div>
        <div
            class="bottom"
            :class="{ 'bottom--iphoneX': iphoneX, bTip: minChaPrice > 0 }"
        >
            <div class="bottom__tip" v-if="minChaPrice > 0">
                <block v-if="curTab === 2">
                    最低{{ minPrice }}元起送，还差{{ minChaPrice }}元，
                </block>
                <block v-else>
                    最低{{ minPrice }}元打包，还差{{ minChaPrice }}元，
                </block>
                <a @click="jump({ isTabBer: true, path: '/pages/goods/index' })"
                    >去凑单</a
                >
            </div>
            <div class="bottom__left">
                <div class="bottom__price">
                    <span>总价：</span>
                    <span class="bottom__big price_color">{{
                        "¥" + (payAmount || "0.00")
                    }}</span>
                </div>
                <div class="bottom__num">
                    {{ "共" + (goodsNum || "1") + "件商品" }}
                </div>
            </div>
            <div
                class="bottom__btn"
                :class="{ disable: btnDisable }"
                @click="submit"
            >
                {{
                    curTab === 2 &&
                    !address.id &&
                    !address.errMsg &&
                    !address.lastAddress
                        ? "填写地址"
                        : "提交订单"
                }}
            </div>
        </div>
        <o-coupon
            ref="coupon"
            :coupon-ids="couponIds"
            :coupon="coupon"
            @change="couponChange"
        ></o-coupon>

        <div class="time-picker" v-if="timePickerVisible">
            <div class="bg" @click.stop="timePickerVisible = false"></div>
            <div class="body">
                <div class="head">
                    <span class="close" @click.stop="timePickerVisible = false"
                        >×</span
                    >
                    选择时间
                </div>
                <div class="mian">
                    <div class="left">
                        <scroll-view class="day-list" :scroll-y="true">
                            <ul class="a-list">
                                <li
                                    class="item"
                                    :class="{ on: curDay === 'toDay' }"
                                    v-if="timePickerData.toDay.length"
                                    @click="curDay = 'toDay'"
                                >
                                    今天
                                </li>
                                <li
                                    class="item"
                                    :class="{ on: curDay === 'twoDay' }"
                                    v-if="timePickerData.twoDay.length"
                                    @click="curDay = 'twoDay'"
                                >
                                    明天
                                </li>
                            </ul>
                        </scroll-view>
                    </div>
                    <div class="right">
                        <scroll-view class="time-list" :scroll-y="true">
                            <ul class="a-list">
                                <li
                                    class="item"
                                    v-if="
                                        curTab === 2 &&
                                        curDay === 'toDay' &&
                                        !dateExternal
                                    "
                                    @click="timeClick('0')"
                                >
                                    尽快送达 |
                                    {{ deliveryConfig.instantDelivery }}分钟
                                </li>
                                <li
                                    class="item"
                                    v-if="
                                        curTab === 1 &&
                                        curDay === 'toDay' &&
                                        !dateExternal
                                    "
                                    @click="timeClick('0')"
                                >
                                    立即提货
                                </li>
                                <li
                                    class="item"
                                    v-for="item of timePickerData[curDay]"
                                    :key="item"
                                    @click="timeClick(item)"
                                >
                                    {{ item.name }}
                                </li>
                            </ul>
                        </scroll-view>
                    </div>
                </div>
            </div>
        </div>
        <address-select ref="addressSelect"></address-select>
    </div>
</template>

<script>
import MyImage from "../../components/image/index";
import FInputNumber from "../../components/form/inputNumber";
import OCoupon from "./coupon";
import AddressSelect from "../../components/address-select/index";

export default {
    name: "",
    components: { FInputNumber, MyImage, OCoupon, AddressSelect },
    // 数据
    data() {
        return {
            ids: "",
            address: {},
            goodsList: [],
            integral: "",
            deduction: false,
            express: "",
            remark: "",
            coupon: "",
            isSubmit: true,
            curTab: 2, // 2配送到家 1到店自提
            timePickerVisible: false,
            timePickerData: {
                toDay: [],
                twoDay: [],
            },
            curDay: "toDay",
            curTime: "", // 等于'0' 时表示立即 其他为{name:date}
            activeShop: {},
            distance: false, //距离超出
            distanceTxt: "",
            orderData: {},
            dateExternal: false, // 当前时间是否在营业时间段外
            myAddress: "", // 详细地址
            address2: {}, // 门店自提用
            productSource: "0", // 0-商家商品1-优选商品
        };
    },

    onLoad() {
        const self = this;

        self.ids = self.$mp.query.ids;
        if (self.$mp.query.productSource) {
            self.productSource = self.$mp.query.productSource;
        }
        if (self.$mp.query.deliveryType === "1") {
            this.curTab = 1;
        }

        this.initDelivery();
        self.getInfo();
    },

    onShow() {
        if (this.$store.state.common.addressData) {
            let address = this.$store.state.common.addressData;
            this.address = {
                // provinceName: address.province,
                // cityName: address.city,
                // countyName: address.county,
                detailInfo: address.address,
                userName: address.name,
                telNumber: address.mobile,
                postalCode: address.zipCode,
                regionInfo: address.regionInfo,
                ...address,
            };
            if (this.address.regionInfo && this.address.regionInfo) {
                this.calDistance();
            }
            this.$store.commit("common/update", {
                addressData: null,
            });
            if (this.$refs.addressSelect) {
                this.$refs.addressSelect.close();
            }
        }
    },

    // 函数
    methods: {
        // 初始化配送相关
        initDelivery() {
            this.activeShop = this.$store.state.common.activeShop;

            const config = this.deliveryConfig;

            // tab判断
            if (this.productSource === "0") {
                if (!config.deliveryMethod.homeDelivery) {
                    this.curTab = 1;
                    if (!config.deliveryMethod.storePickUp) {
                        this.curTab = 0;
                        this.fn.showToast(
                            "店铺配置错误，请至少选择一种配送方式"
                        );
                    }
                } else {
                    if (this.curTab === 1) {
                        if (!config.deliveryMethod.storePickUp) {
                            this.curTab = 2;
                        }
                    }
                }
            }
            // 自提地址获取
            // if (config.deliveryMethod.storePickUp) {
            // }
            this.getLastAddress();

            // 初始化时间范围 [h,m]
            let gapMs = config.specifyTimeInterval * 1000 * 60;
            let sDate = config.deliveryTime.startTime.split(":");
            let eDate = config.deliveryTime.endTime.split(":");

            // 判断是否在时间段内
            let currentDate = new Date();
            let currentH = currentDate.getHours();
            let currentM = currentDate.getMinutes();
            if (currentH < Number(sDate[0])) {
                this.dateExternal = true;
            } else if (currentH === Number(sDate[0])) {
                if (currentM < Number(sDate[1])) {
                    this.dateExternal = true;
                }
            } else {
                this.dateExternal = false;
            }

            // 今天
            let curDate = new Date();
            let curDate3 = new Date();
            if (this.dateExternal) {
                curDate.setHours(sDate[0]);
                curDate.setMinutes(sDate[1]);
            }
            curDate = curDate.getTime();

            curDate += config.reserveReceivingOrdersTime * 1000 * 60;
            curDate += config.instantDelivery * 1000 * 60;

            let curDate2 = new Date();
            curDate2.setHours(eDate[0]);
            curDate2.setMinutes(eDate[1]);
            let endDate = curDate2.getTime();
            let curD = new Date(curDate);
            if (curD.getMinutes() % 30 !== 0) {
                curD.setMinutes(curD.getMinutes() - (curD.getMinutes() % 30));
            }
            curDate = curD.getTime();
            let arr = this.initTimeArr(curDate, endDate, gapMs);
            this.timePickerData.toDay = arr;

            //第二天
            curDate3.setHours(sDate[0]);
            curDate3.setMinutes(sDate[1]);
            curDate3.setDate(curDate3.getDate() + 1);
            let startDate = curDate3.getTime();
            let endDate2 = curDate2.setDate(curDate2.getDate() + 1);

            let arr2 = this.initTimeArr(startDate, endDate2, gapMs);
            this.timePickerData.twoDay = arr2;

            if (this.timePickerData.toDay.length === 0) {
                this.curDay = "twoDay";
                this.curTime = arr2[0];
            } else {
                if (this.dateExternal) {
                    this.curTime = arr[0];
                } else {
                    this.curTime = "0";
                }
            }
        },

        getLastAddress() {
            let self = this;
            this.api
                .get("/order/GetLastAddress", { deliveryMethod: this.curTab })
                .then((res) => {
                    if (res.data) {
                        let data = res.data;
                        if (this.curTab === 1) {
                            this.address2.userName = res.data.name;
                            this.address2.telNumber = res.data.mobile;
                        } else {
                            self.address = {
                                ...data.address,
                                provinceName: data.province,
                                cityName: data.city,
                                countyName: data.county,
                                detailInfo: data.address,
                                userName: data.name,
                                telNumber: data.mobile,
                                postalCode: data.zipCode,
                                latitude: data.latitude,
                                longitude: data.longitude,
                                regionInfo: data.regionInfo,
                                lastAddress: true, // 上次地址，用于提交订单判断
                            };
                            self.calDistance();
                        }
                    }
                });
        },

        // 获取地址是否超出距离
        calDistance() {
            if (!this.address || this.productSource == "1") {
                return;
            }
            if (!this.address.longitude || !this.address.latitude) {
                return;
            }
            // let originsLocation = this.deliverierPickUpAddress.location;
            let originsLocation =
                this.deliverierPickUpAddress.longitude +
                "," +
                this.deliverierPickUpAddress.latitude;
            let desctinationLocation =
                this.address.longitude + "," + this.address.latitude;

            this.api
                .get(
                    "/order/CalPointDistanceByLocation",
                    {
                        originsLocation,
                        desctinationLocation,
                    },
                    {
                        pass: true,
                    }
                )
                .then((res) => {
                    if (res.success) {
                        var jl = Number(res.data);

                        var maxJl = Number(
                            this.deliveryConfig.deliveryDistance
                        );
                        console.log(`当前距离：${jl},最大配送距离 ${maxJl}`);
                        if (jl > maxJl) {
                            this.distance = true;
                            this.distanceTxt =
                                "当前地址不在配送范围内，请重新选择地址";
                        } else {
                            this.distance = false;
                        }
                    } else {
                        this.distance = true;
                        this.distanceTxt =
                            "判断配送地址距离错误：" + res.message;
                    }
                });
        },

        // 根据开始时间结束时间，时间间隔转化时间数组 单位ms
        initTimeArr(sDate, eDate, gap) {
            let arr = [];
            let end = sDate + gap;
            while (end <= eDate) {
                let str = `${this.fn.getDateFormat(
                    new Date(sDate),
                    "hh:mm"
                )} ~ ${this.fn.getDateFormat(new Date(end), "hh:mm")}`;

                let date = [
                    this.fn.getDateFormat(new Date(sDate), "yyyy/MM/dd hh:mm"),
                    this.fn.getDateFormat(new Date(end), "yyyy/MM/dd hh:mm"),
                ];
                arr.push({
                    name: str,
                    date: date,
                });
                sDate = end;
                end += gap;
            }
            return arr;
        },

        // 显示时间选择
        showTime() {
            this.timePickerVisible = true;
        },

        // 时间选择
        timeClick(time) {
            this.curTime = time;
            this.timePickerVisible = false;
        },

        // 配送切换
        tabChange(val) {
            if (val === 2) {
                this.$store.commit("common/update", {
                    deliveryType: 0,
                });
            } else {
                this.$store.commit("common/update", {
                    deliveryType: 1,
                });
            }
            this.curTab = val;
            this.getLastAddress();
        },

        // 设置收货地址
        setAddress() {
            const self = this;
            this.router.push({
                path: "/pages/address/index",
                query: {
                    isOrder: "1",
                },
            });
        },

        // 获取信息
        getInfo() {
            const self = this;

            self.api
                .post("/Order/Confirm", {
                    orderItemIds: self.ids.split(","),
                    storeId: this.activeShop.id,
                    shopId: this.activeShop.store.id,
                    productSource: this.productSource, // 0-商家商品1-优选商品
                })
                .then((res) => {
                    let data = JSON.parse(res.data);

                    data.itemList.forEach((item, index) => {
                        item.amount = Number(item.amount);
                        item.price = Number(item.price);

                        data.itemList.splice(index, item);
                    });
                    if (self.defaultOrderAddress === 2) {
                        // if (true) {
                        // 当前位置
                        self.getAddress(data.address);
                    } else {
                        // 上次下单地址
                        // if (data.address.latitude && data.address.longitude) {
                        // }
                    }

                    self.goodsList = data.itemList;
                    // self.express = data.logisticsList[0];
                    self.integral = data.pointInfo.points || 0;
                    self.orderData = data;
                    // if (self.address.id) {
                    // }
                });
        },

        getAddress(address) {
            let self = this;
            uni.getLocation({
                type: "gcj02",
                success: function (res) {
                    let latitude = Number(res.latitude.toFixed(6));
                    let longitude = Number(res.longitude.toFixed(6));
                    let query = {
                        location: longitude + "," + latitude,
                    };
                    //获取定位地址;
                    self.api
                        .get("/order/GetAddressByLocation", query)
                        .then((addRes) => {
                            console.log(addRes, "地址");
                            const data = addRes.data;
                            self.address = {
                                ...data,
                                provinceName: data.province,
                                cityName: data.city,
                                countyName: data.county,
                                detailInfo: data.address,
                                userName: data.name,
                                telNumber: data.mobile,
                                postalCode: data.zipCode,
                                reAddress: true,
                                longitude: res.longitude,
                                latitude: res.latitude,
                                regionInfo:
                                    data.province + data.city + data.county,
                                id: true,
                            };
                            self.calDistance();
                        });
                },
                fail(err) {
                    self.address = {
                        ...address,
                        provinceName: address.province,
                        cityName: address.city,
                        countyName: address.county,
                        detailInfo: address.address,
                        userName: address.name,
                        telNumber: address.mobile,
                        postalCode: address.zipCode,
                    };
                    self.calDistance();
                },
            });
        },

        // 修改购物车数量
        setCaetNum(val) {
            const self = this;

            self.api
                .post("/Order/UpdateItemCount", {
                    id: val.id,
                    count: val.count,
                })
                .then(() => {
                    self.$refs.coupon.getList();
                });
        },

        // 积分抵扣开关
        switchChange(e) {
            const self = this;
            self.deduction = e.detail.value;
        },

        // 打开优惠券
        openCoupon() {
            const self = this;
            self.$refs.coupon.open();
        },

        // 优惠券改变处理
        couponChange(val) {
            const self = this;

            self.coupon = val;
        },

        // 提交订单
        submit() {
            const self = this;

            if (self.isSubmit) {
                //送货上门定位地址
                if (
                    this.curTab === 2 &&
                    this.address &&
                    this.address.reAddress
                ) {
                    if (!this.address.userName) {
                        return self.fn.showToast("请填写姓名");
                    }
                    if (!this.address.telNumber) {
                        return self.fn.showToast("请填写手机号");
                    }
                    let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
                    if (!reg.test(this.address.telNumber)) {
                        return self.fn.showToast("请填写正确的手机号");
                    }
                    if (!this.myAddress) {
                        return self.fn.showToast("请填写门牌号、详细地址");
                    }
                }
                //送货上门
                if (
                    this.curTab === 2 &&
                    !self.address.id &&
                    !self.address.errMsg &&
                    !self.address.lastAddress
                ) {
                    self.openAddress();
                    return self.fn.showToast("请填写收货地址");
                }

                // 配送到家
                // if (this.address.lastAddress) {
                //     // 上次下单地址
                //     let desctinationLocation =
                //         this.address.longitude + "," + this.address.latitude;
                //     uni.getLocation({
                //         type: "wgs84",
                //         success: function (res) {
                //             let originsLocation =
                //                 res.longitude + "," + res.latitude;
                //             self.api
                //                 .get(
                //                     "/order/CalPointDistanceByLocation",
                //                     {
                //                         originsLocation,
                //                         desctinationLocation,
                //                     },
                //                     {
                //                         pass: true,
                //                     }
                //                 )
                //                 .then((res2) => {
                //                     var jl = Number(res.data);
                //                     if (jl > 500) {
                //                         self.fn
                //                             .showModal({
                //                                 conttent:
                //                                     "当前地址与你所在位置相差过远，是否确认下单",
                //                             })
                //                             .then((res) => {
                //                                 if (res.confirm) {
                //                                     self.submitOrder();
                //                                 } else {
                //                                 }
                //                             });
                //                     } else {
                //                         self.submitOrder();
                //                     }
                //                 });
                //         },
                //         fail: function () {
                //             console.log("授权位置失败");
                //             self.submitOrder();
                //         },
                //     });
                // }
                if (this.curTab === 1 && !this.address2.userName) {
                    return self.fn.showToast("请填写提货人姓名");
                }
                if (this.curTab === 1 && !this.address2.telNumber) {
                    return self.fn.showToast("请填写提货人手机号");
                }
                let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
                if (this.curTab === 1 && !reg.test(this.address2.telNumber)) {
                    return self.fn.showToast("请填写正确的手机号");
                }

                this.submitOrder();
            }
        },

        submitOrder() {
            const self = this;
            let goodsList = self.fn.deepClone(self.goodsList);

            goodsList.forEach((item, index) => {
                item.price = Number(item.price);
                item.count = Number(item.count);
                item.amount = Number(item.amount);
                goodsList.splice(index, item);
            });
            const sendData = {
                orderItemList: goodsList,
                payAmount: Number(self.payAmount),
                point: Number(self.integralDeduction * 100),
                pointPrice: Number(self.integralDeduction),
                postage:
                    this.curTab === 2
                        ? this.deliveryConfig.deliveryFee || 0
                        : 0,
                couponReceiveId: self.coupon.receiveId || "",
                remark: self.remark,

                packageFee: this.deliveryConfig.packageFee,
                storeId: this.activeShop.store.id,
                // deliveryMethod: this.curTab,
                deliveryStartTime: this.deliveryTime()[0],
                deliveryEndTime: this.deliveryTime()[1],
                productSource: Number(this.productSource), // 0-商家商品1-优选商品
            };
            if (this.productSource === "1") {
                sendData.deliveryMethod = 0;
            } else {
                sendData.deliveryMethod = this.curTab;
            }
            // 配送
            if (this.curTab === 2) {
                sendData.address = {
                    id: self.address.id,
                    userId: self.userId,
                    province: self.address.provinceName,
                    city: self.address.cityName,
                    area: self.address.countyName,
                    address: self.address.detailInfo,
                    realName: self.address.userName,
                    mobile: self.address.telNumber,
                    zip: self.address.postalCode,
                    latitude: self.address.latitude,
                    longitude: self.address.longitude,
                    regionInfo: self.address.regionInfo,
                };
                if (this.address.reAddress) {
                    sendData.address.address += this.myAddress;
                }
            }
            // 自提
            if (this.curTab === 1) {
                sendData.address = {
                    userId: self.userId,
                };
                sendData.address.mobile = this.address2.telNumber;
                sendData.address.realName = this.address2.userName;
            }
            self.isSubmit = false;
            self.api
                .post("/Order/Submit", sendData, {
                    pass: true,
                })
                .then((res) => {
                    if (res.success) {
                        if (Number(self.payAmount)) {
                            self.fn
                                .pay(res.data, self.payAmount, true)
                                .then(() => {
                                    setTimeout(() => {
                                        self.isSubmit = true;
                                    }, 2000);
                                });
                        } else {
                            setTimeout(() => {
                                self.isSubmit = true;
                            }, 2000);
                            self.router.replace({
                                path: "/pages/pay/result",
                                query: {
                                    orderId: res.data,
                                    price: self.payAmount,
                                    type: "success",
                                },
                            });
                        }
                    } else {
                        this.fn.showToast(res.message);
                    }
                });
        },

        // 时间转换
        deliveryTime() {
            const config = this.deliveryConfig;
            if (this.curTime === "0") {
                let curDate = Date.now();
                let endData = Date.now();
                endData += config.reserveReceivingOrdersTime * 1000 * 60;
                endData += config.instantDelivery * 1000 * 60;
                curDate += config.reserveReceivingOrdersTime * 1000 * 60;
                let arr = [
                    this.fn.getDateFormat(
                        new Date(curDate),
                        "yyyy-MM-dd hh:mm"
                    ),
                    this.fn.getDateFormat(
                        new Date(endData),
                        "yyyy-MM-dd hh:mm"
                    ),
                ];
                return arr;
            } else {
                return this.curTime.date;
            }
        },

        // 打开地址
        openAddress() {
            const self = this;
            console.log(self.$refs.addressSelect);
            self.$refs.addressSelect.open((val) => {
                if (val === "add") {
                    const self = this;
                    this.router.push({
                        path: "/pages/address/form",
                        query: {
                            isOrder: "1",
                        },
                    });
                } else {
                    uni.chooseAddress({
                        success(addressRes) {
                            if (addressRes.errMsg === "chooseAddress:ok") {
                                let address = {
                                    regionInfo:
                                        addressRes.provinceName +
                                        addressRes.cityName +
                                        addressRes.countyName,
                                    province: addressRes.provinceName,
                                    city: addressRes.cityName,
                                    county: addressRes.countyName,
                                    address: addressRes.detailInfo,
                                    name: addressRes.userName,
                                    // mobile: "17343041879",
                                    mobile: addressRes.telNumber,
                                };
                                self.api
                                    .post("/Address/Add", address)
                                    .then((res) => {
                                        if (res.success) {
                                            // self.fn.showToast("保存成功");
                                            address.id = res.data;
                                            self.address = {
                                                ...address,
                                                provinceName: address.province,
                                                cityName: address.city,
                                                countyName: address.county,
                                                detailInfo: address.address,
                                                userName: address.name,
                                                telNumber: address.mobile,
                                                regionInfo: address.regionInfo,
                                            };
                                            self.$refs.addressSelect.close();
                                        } else {
                                            self.fn.showModal({
                                                title: "保存失败",
                                                content: res.message,
                                                showCancel: false,
                                            });
                                        }
                                    });
                            } else {
                                this.fn.showToast("选择地址失败");
                            }
                        },
                    });
                }
            });
        },
    },

    // 数据计算
    computed: {
        // 门店位置
        deliverierPickUpAddress() {
            console.log(this.$store.state.common.activeShop.store, 55);
            return this.$store.state.common.activeShop.store;
        },
        // 门店位置
        selfPickUpAddress() {
            console.log(
                this.$store.state.common.storeConfig.selfPickUpAddress,
                2435
            );
            return this.$store.state.common.storeConfig.selfPickUpAddress;
        },

        // 提交禁用
        btnDisable() {
            if (this.curTab === 2 && this.distance) {
                return true;
            }
            if (!this.curDay || !this.curTime) {
                return true;
            }

            if (this.minChaPrice > 0) {
                return true;
            }
            if (this.curTab === 0) {
                return true;
            }

            // if (this.curTab ===2 && !this.address.id && !this.address.errMsg) {
            //     return true;
            // }

            return false;
        },

        // 最低金额
        minPrice() {
            if (this.curTab === 2) {
                if (this.deliveryConfig.deliveryMinAmount) {
                    return parseFloat(
                        this.deliveryConfig.deliveryMinAmount
                    ).toFixed(2);
                } else {
                    return "";
                }
            } else {
                if (this.deliveryConfig.pickupMinAmount) {
                    return parseFloat(
                        this.deliveryConfig.pickupMinAmount
                    ).toFixed(2);
                } else {
                    return "";
                }
            }
        },

        // 选择时间显示
        selectTime() {
            let str = "";
            if (this.curDay === "toDay") {
                str += "今天 ";
            } else {
                str += "明天 ";
            }
            if (this.curTime === "0") {
                if (this.curTab === 2) {
                    str = `尽快送达 | ${this.deliveryConfig.instantDelivery}分钟`;
                } else {
                    str = "立即提货";
                }
            } else if (this.curTime) {
                str += this.curTime.name;
            } else {
                str = "请选择";
            }
            return str;
        },

        // 交货设置
        deliveryConfig() {
            if (!this.$store.state.common.storeConfig.deliveryConfig) {
                return this.fn.showToast("获取店铺配置错误");
            }
            console.log(this.$store.state.common.storeConfig.deliveryConfig);
            return this.$store.state.common.storeConfig.deliveryConfig;
        },

        // 是否开启积分抵扣
        enablePoints() {
            return this.$store.state.common.enablePoints;
        },

        // 地址选择方式
        defaultOrderAddress() {
            return this.$store.state.common.defaultOrderAddress;
        },
        // 积分抵扣比例
        pointsRate() {
            return this.$store.state.common.pointsRate;
        },
        // 用户id
        userId() {
            return this.$store.state.user.userId;
        },
        // 商品项ids
        couponIds() {
            const self = this;
            let ids = [];

            if (self.goodsList.length) {
                self.goodsList.forEach((item) => {
                    ids.push(item.id);
                });
            }

            return ids;
        },
        // 抵扣积分对应的金额
        integralDeduction() {
            const self = this;

            // let integral = Math.floor(self.integral / self.pointsRate) / 100;

            // if (integral > self.totalAmount) {
            //     integral = self.totalAmount;
            // }

            if (this.orderData.pointInfo) {
                let maxDeductionProportion =
                    this.orderData.pointInfo.maxDeductionProportion / 100;
                let points = this.orderData.pointInfo.points / 100;
                if (points > self.totalAmount * maxDeductionProportion) {
                    points = self.totalAmount * maxDeductionProportion;
                }

                if (!self.deduction) {
                    points = 0;
                }
                return points;
            } else {
                return 0;
            }
        },
        integralDeductionStr() {
            const self = this;
            let str = "";
            if (this.orderData.pointInfo) {
                let maxDeductionProportion =
                    this.orderData.pointInfo.maxDeductionProportion / 100;
                let points = this.orderData.pointInfo.points / 100;

                if (points > self.totalAmount * maxDeductionProportion) {
                    points = self.totalAmount * maxDeductionProportion;
                    points = points.toFixed(2);
                    points = Number(points);
                }
                str = `可使用${parseInt(points * 100)}积分,抵扣${points}元`;
            }
            return str;
        },

        shopAmount() {
            const self = this;
            let sum = 0;

            self.goodsList.forEach((item) => {
                sum += (item.price / 100) * Number(item.count);
            });
            return parseFloat(sum).toFixed(2);
        },

        // 店铺总计价格
        totalAmount() {
            const self = this;
            let sum = 0;

            self.goodsList.forEach((item) => {
                sum += (item.price / 100) * Number(item.count);
            });

            if (
                self.coupon &&
                parseFloat(self.coupon.value / 100).toFixed(2) <= sum
            ) {
                sum = sum - parseFloat(self.coupon.value / 100).toFixed(2);
            }

            if (
                self.enablePoints &&
                self.integral / self.pointsRate >= 1 &&
                sum > 0
            ) {
                self.deduction = true;
            } else {
                self.deduction = false;
            }

            return parseFloat(sum).toFixed(2);
        },

        // 总支付价格
        totalAmount2() {
            const self = this;
            let sum = self.totalAmount;
            // 打包费

            if (self.deliveryConfig.packageFee) {
                sum += Number(self.deliveryConfig.packageFee);
            }
            // 配送费：
            if (self.deliveryConfig.deliveryFee) {
                sum += Number(self.deliveryConfig.deliveryFee);
            }

            return parseFloat(sum).toFixed(2);
        },

        // 总支付价格
        payAmount() {
            const self = this;
            let sum = self.totalAmount;
            sum = sum - self.integralDeduction;
            // 打包费
            if (self.deliveryConfig.packageFee) {
                sum += Number(self.deliveryConfig.packageFee);
            }
            // 配送费：
            if (self.deliveryConfig.deliveryFee && this.curTab === 2) {
                sum += Number(self.deliveryConfig.deliveryFee);
            }

            return parseFloat(sum).toFixed(2);
        },

        // 距离最低价格还差
        minChaPrice() {
            const self = this;
            let sum = self.shopAmount;

            let num = 0;
            if (this.curTab === 2) {
                num = this.deliveryConfig.deliveryMinAmount - sum;
            } else {
                num = this.deliveryConfig.pickupMinAmount - sum;
            }
            return parseFloat(num).toFixed(2);
        },

        // 商品数量
        goodsNum() {
            const self = this;
            let sum = 0;

            self.goodsList.forEach((item) => {
                sum += Number(item.count);
            });

            return sum;
        },
    },

    // 数据监听
    watch: {},
};
</script>

<style lang="scss" scoped>
.page {
    padding-bottom: px(170);
    &.bTip {
        padding-bottom: px(250);
    }
    &--iphoneeX {
        padding-bottom: px(200);
    }

    &__parting-line {
        width: 100%;
        height: px(14);
    }

    &__title {
        display: flex;
        align-items: center;
        height: px(140);
        padding: 0 px(45);
        margin-top: px(30);
        font-size: px(38);
        color: #424242;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .val {
            font-size: px(40);
            color: #ffbd2e;
            display: flex;
            align-items: center;
        }
        .arrows {
            margin-left: px(20);
            font-size: px(44);
            color: #999;
        }
    }
}
.tab {
    width: 100%;
    background-color: #fff;
    color: #999;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: px(120);
    border-bottom: solid px(3) #ececec;

    &__item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #e5e5e5;
        font-size: px(38);
        height: 100%;
        &.on {
            color: #ffbd2e;
            background-color: #fff;
        }
    }
}

.shop {
    padding: px(30) px(45);
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    .dizhi {
        margin-top: px(30);
        font-size: px(68);
        color: #999;
        flex-shrink: 0;
    }
    .con {
        width: 100%;
        margin-left: px(30);
    }
    &__name {
        font-size: px(42);
        color: #424242;
    }
    &__des {
        @include omits(2);
        margin-top: px(40);
        font-size: px(38);
        color: #999;
    }
}

.address {
    display: flex;
    justify-content: space-between;
    height: px(245);
    padding: 0 px(45);
    background-color: #fff;
    &.readdress {
        height: px(180);
        .address__arrows {
            margin-top: px(60);
        }
    }

    &__dizhi {
        margin-top: px(30);
        font-size: px(68);
        color: #999;
    }

    &__content {
        display: flex;
        justify-content: space-between;
        flex: 1;
        margin-left: px(30);
        align-items: center;
    }

    &__left {
        flex: 1;
        margin-top: px(30);
    }

    &__name {
        font-size: px(42);
        color: #424242;
        margin-bottom: px(40);
    }

    &__text {
        @include omits(2);
        font-size: px(38);
        color: #999;
        .black {
            color: #333;
        }
    }

    &__arrows {
        margin-left: px(80);
        font-size: px(44);
        color: #999;
    }
    &__warn {
        line-height: px(80);
        color: #e6a23c;
        padding: 0 px(45);
        font-size: px(38);
        background-color: #fff;
    }
}

.address-null {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: px(130);
    padding: 0 px(45);
    background-color: #fff;

    &__title {
        font-size: px(40);
        color: #333;
    }

    &__arrows {
        font-size: px(44);
        color: #c3c3c3;
    }
}

.goods {
    background-color: #fff;

    &__item {
        display: flex;
        justify-content: space-between;
        height: px(250);
        padding: 0 px(45);
        border-top: solid px(3) #ececec;
    }

    &__img {
        width: px(170);
        height: px(170);
        margin-top: px(40);
        border: solid px(3) #e5e5e5;

        /deep/ img {
            width: px(170);
            height: px(170);
        }
    }

    &__title {
        @include omits(2);
        flex: 1;
        height: px(100);
        margin: px(50) px(40) 0 px(30);
        font-size: px(36);
        color: #333;
    }

    &__right {
        margin-top: px(50);
    }

    &__price {
        margin-bottom: px(70);
        font-size: px(30);
        color: #333;
        text-align: right;
    }
}

.list {
    background-color: #fff;

    &__item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: px(130);
        padding: 0 px(45);
        border-top: solid px(3) #ececec;
    }

    &__left {
        display: flex;
        align-items: center;
    }

    &__title {
        font-size: px(40);
        color: #333;
    }

    &__text {
        font-size: px(36);
        color: #999;
    }

    &__price {
        font-size: px(36);
        color: #333;
    }
}

.remark {
    display: flex;
    justify-content: center;
    align-items: center;
    height: px(160);
    padding: 0 px(45);
    background-color: #fff;
    border-top: solid px(3) #ececec;

    &__input {
        width: 100%;
        height: px(100);
        padding: 0 px(30);
        font-size: px(36);
        color: #333;
        border-radius: px(10);
        background-color: #f5f5f5;
    }
}

.bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 995;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: px(140);
    background-color: #fff;

    &.bTip {
        height: px(200);
        padding-top: px(80);
    }
    &__tip {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        z-index: 1;
        line-height: px(80);
        padding: 0 px(35);
        border-bottom: solid px(2) #e5e5e5;
        color: #999;
        display: flex;
        align-items: center;
        font-size: px(34);
        a {
            color: #ffbd2e;
        }
    }

    &--iphoneX {
        height: px(170);
        padding-bottom: px(30);
    }

    &__left {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex: 1;
        padding-left: px(45);
    }

    &__price {
        font-size: px(42);
        color: #333;
    }

    &__big {
        font-size: px(44);
        color: #262626;
    }

    &__num {
        font-size: px(32);
        color: #999;
    }

    &__btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: px(285);
        height: 100%;
        margin-left: px(20);
        font-size: px(42);
        color: #fff;
        background-color: #27a34f;
        &.disable {
            color: #bcbec2;
            background-color: #f4f4f5;
            border-color: #e9e9eb;
            pointer-events: none;
        }
    }
}

.time-picker {
    height: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 996;
    .bg {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.3);
    }
    .body {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        z-index: 10;
        background-color: #fff;
    }
    .head {
        height: px(120);
        line-height: px(120);
        text-align: center;
        font-size: px(38);
        position: relative;
        border-bottom: px(3) solid #f2f2f2;
        .close {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
            line-height: px(120);
            font-size: px(60);
            width: px(100);
            padding: 0 px(30);
        }
    }
    .mian {
        height: px(680);
        display: flex;
        justify-content: space-between;
        .left,
        .right {
            height: 100%;
        }
        .day-list,
        .time-list {
            height: 100%;
        }
        .left {
            background-color: #f2f2f2;
            width: px(380);
            flex-shrink: 0;
            .item {
                text-align: center;
                color: #888;
                font-size: px(38);
                line-height: px(160);
                &.on {
                    background-color: #fff;
                    color: #333;
                }
            }
        }
        .right {
            width: 100%;
            padding: 0 px(60);
            .item {
                display: flex;
                line-height: px(160);
                color: #333;
                font-size: px(38);
                border-bottom: px(3) solid #f2f2f2;
            }
        }
    }
}
.my-address {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: px(40);
    background-color: #fff;
    padding: px(20) px(45);
    border-top: 1px solid #ececec;
    border-bottom: 1px solid #ececec;
    span {
        width: px(200);
        flex-shrink: 0;
    }
    input {
        width: 100%;
    }
    & ~ .my-address {
        border-top: none;
    }
}
.price_color {
    color: #27a34f !important;
}
.deliveryTips {
    background-color: #fef9f3;
    font-size: px(40);
    padding: 0 px(40);
    min-height: px(100);
    padding: px(20) px(35);
    line-height: 1.4;
    color: #ec883d;
    display: flex;
    align-items: center;
}
</style>