<template>
    <div class="content">
        <div class="header">
            <u-navbar
                :background="{ backgroundColor: '#ffcb57' }"
                :border-bottom="false"
                title="客户信息"
                title-color="#472d21"
            ></u-navbar>
        </div>
        <view class="wrap">
            <view class="recognition">
                <u-input
                    type="textarea"
                    v-model="addresRec"
                    class="addresRec"
                    :border="true"
                    :height="120"
                    :auto-height="true"
                    :disabled="disableInput"
                    placeholder="上海市浦东新区纳贤路701号百度上海研发中心 张三 13000000000"
                />
                <u-button
                    :custom-style="{ margin: '16rpx 0', backgroundColor: '#ffcb57', color: '#472d21' }"
                    hover-class="defaultBtnhover"
                    @click="handleRecognition"
                    :disabled="disableInput"
                    >一键识别</u-button
                >
            </view>
            <u-card title="客户信息" margin="30rpx 30rpx 0 30rpx" :body-style="{ padding: 0 }">
                <view slot="body">
                    <u-cell-group :border="false">
                        <u-cell-item required title="姓名" :arrow="false">
                            <u-input
                                type="text"
                                v-model="name"
                                height="48"
                                input-align="right"
                                placeholder="请输入姓名"
                                :clearable="false"
                                :disabled="disableInput"
                            />
                        </u-cell-item>
                        <u-cell-item required title="手机" :arrow="false">
                            <u-input
                                type="number"
                                v-model="phone"
                                height="48"
                                input-align="right"
                                placeholder="请输入手机号"
                                :clearable="false"
                                :disabled="disableInput"
                            />
                        </u-cell-item>
                        <u-cell-item required title="区域" :value="region" @click="chooseRegion"></u-cell-item>
                        <u-cell-item required title="详细地址" :arrow="false">
                            <u-input
                                type="text"
                                v-model="addressDetail"
                                height="48"
                                input-align="right"
                                placeholder="请输入详细地址"
                                :clearable="false"
                                :disabled="disableInput"
                            />
                        </u-cell-item>
                        <u-cell-item title="位置" :arrow="false">
                            <u-icon name="map-fill" slot="right-icon" @click="openMap"></u-icon>
                            <u-input
                                type="text"
                                disabled
                                v-model="address"
                                height="48"
                                input-align="right"
                                placeholder="点击选择地点"
                                @click="openMap"
                            />
                        </u-cell-item>
                        <u-cell-item
                            required
                            title="期望上门时间"
                            :value="expectedTime"
                            @click="chooseExpectedTime"
                        ></u-cell-item>
                        <!-- <u-cell-item required title="物流公司" :arrow="false">
                            <u-input
                                type="text"
                                v-model="logistics"
                                height="48"
                                input-align="right"
                                placeholder="请填写物流公司"
                            />
                        </u-cell-item>-->
                        <u-cell-item title="备注说明" :arrow="false" :border-bottom="false">
                            <u-input
                                type="textarea"
                                v-model="mark"
                                height="48"
                                input-align="right"
                                placeholder="备注说明"
                                :clearable="false"
                                :disabled="disableInput"
                            />
                        </u-cell-item>
                    </u-cell-group>
                </view>
            </u-card>
            <!-- <u-card title="悬赏金额" margin="30rpx 30rpx 15rpx 30rpx">
                <view slot="body">
                    <view class="reward">
                        <u-input type="number" :border="false" />
                        <view class="unit">元</view>
                    </view>
                </view>
                <view slot="foot">
                    <view class="minddesc">师傅将根据服务内容、服务价格等因素综合考虑接单，请务必合理设置悬赏金额，价格过低可能导致无人接单。</view>
                </view>
            </u-card>-->
            <u-card title="支付方式" margin="30rpx 30rpx 0 30rpx" :body-style="{ padding: 0 }">
                <view slot="body">
                    <u-cell-group>
                        <u-cell-item
                            title="下单支付"
                            label="下单支付享受VIP人工专属客服跟单服务，保质保量省心省时"
                            :arrow="false"
                            v-if="userDetail.F_PAEZ_CheckBox"
                            @click="() => this.changePayType({ name: '1' })"
                        >
                            <u-checkbox
                                slot="right-icon"
                                shape="circle"
                                active-color="#ffcb57"
                                size="50"
                                :value="payType === 1"
                                name="1"
                                @change="changePayType"
                                :disabled="disableInput"
                            ></u-checkbox>
                        </u-cell-item>
                        <u-cell-item
                            title="验收完成支付"
                            label="由系统自动推荐匹配师傅自行选择师傅验收后支付，平台仅提供流程和师傅信息不承担安装风险"
                            :arrow="false"
                            v-if="userDetail.F_PAEZ_CheckBox1"
                            @click="() => this.changePayType({ name: '2' })"
                        >
                            <u-checkbox
                                slot="right-icon"
                                shape="circle"
                                active-color="#ffcb57"
                                size="50"
                                :value="payType === 2"
                                name="2"
                                @change="changePayType"
                                :disabled="disableInput"
                            ></u-checkbox>
                        </u-cell-item>
                        <u-cell-item
                            title="业主现场支付"
                            label="安装完成后现场支付给师傅，请及时通知用户现场验收满意再付款"
                            :arrow="false"
                            v-if="userDetail.F_PAEZ_CheckBox11"
                            @click="() => this.changePayType({ name: '3' })"
                        >
                            <u-checkbox
                                slot="right-icon"
                                shape="circle"
                                active-color="#ffcb57"
                                size="50"
                                :value="payType === 3"
                                name="3"
                                @change="changePayType"
                                :disabled="disableInput"
                            ></u-checkbox>
                        </u-cell-item>
                    </u-cell-group>
                </view>
            </u-card>
            <u-card :show-head="false" margin="30rpx 30rpx 0 30rpx" :body-style="{ padding: 0 }" v-if="payType === 2">
                <view slot="body">
                    <u-cell-group :border="false">
                        <u-cell-item title="期望价格" :arrow="false" :border-bottom="false">
                            <u-input
                                type="number"
                                v-model="expectAmount"
                                height="48"
                                input-align="right"
                                placeholder="完成这笔订单您期望费用范围"
                                :clearable="false"
                                :disabled="disableInput"
                            />
                        </u-cell-item>
                    </u-cell-group>
                </view>
            </u-card>
            <u-card :show-head="false" margin="30rpx 30rpx 0 30rpx" :body-style="{ padding: 0 }">
                <view slot="body">
                    <u-cell-group :border="false">
                        <u-cell-item
                            title="建议收费标准"
                            :arrow="false"
                            :value="`${totalAmount}元`"
                            v-if="[1, 2].includes(payType)"
                        ></u-cell-item>
                        <u-cell-item
                            title="商家应付费用"
                            :arrow="false"
                            :value="`${totalAmount}元`"
                            :border-bottom="false"
                            v-if="[1].includes(payType)"
                        ></u-cell-item>
                        <u-cell-item
                            title="现场收费金额"
                            :arrow="false"
                            :value="`${totalAmount}元`"
                            :border-bottom="false"
                            label="以与客户沟通为准"
                            v-if="[3].includes(payType)"
                        ></u-cell-item>
                    </u-cell-group>
                </view>
            </u-card>
            <u-card :show-head="false" margin="30rpx 30rpx 15rpx 30rpx" :body-style="{ padding: 0 }">
                <view slot="body">
                    <u-alert-tips
                        type="warning"
                        title="温馨提示"
                        description="标准收费不含加急费远程费特殊墙体打孔费材料费等，如有相关特殊需求请联系客服确认价格再下单。"
                        v-if="payType !== 3"
                    ></u-alert-tips>
                    <u-alert-tips
                        type="warning"
                        title="温馨提示"
                        description="具体收费金额以最终现成客户沟通结果为准，如您对当前页面费用有疑问，请及时联系客服进行咨询。"
                        v-else
                    ></u-alert-tips>
                </view>
            </u-card>
            <view class="mc-btn">
                <u-button
                    :custom-style="{ margin: '16rpx 30rpx', backgroundColor: '#ffcb57', color: '#472d21' }"
                    hover-class="defaultBtnhover"
                    :loading="loading"
                    @click="placeOrder"
                    >提交订单</u-button
                >
            </view>
            <u-picker mode="region" v-model="showRegion" @confirm="confirmRegion" confirm-color="#ffcb57"></u-picker>
            <u-picker
                v-model="showExpectedTime"
                mode="time"
                :params="params"
                :default-time="defaultTime"
                @confirm="confirmExpectedTime"
                confirm-color="#ffcb57"
            ></u-picker>
            <u-modal
                v-model="showModal"
                content="您的余额不足，请充值"
                confirm-text="去充值"
                confirm-color="#ffcb57"
                :show-title="false"
                @confirm="goRecharge"
            ></u-modal>
            <u-modal
                v-model="showPswModal"
                content="请先设置支付密码"
                confirm-color="#ffcb57"
                :show-title="false"
                @confirm="goChangePsw"
            ></u-modal>
            <u-modal v-model="showPswTips" content="请联系企业管理员设置支付密码" confirm-color="#ffcb57"></u-modal>
            <u-keyboard
                default
                ref="uKeyboard"
                mode="number"
                :mask="true"
                :mask-close-able="true"
                :dot-enabled="false"
                v-model="showPay"
                :safe-area-inset-bottom="true"
                :tooltip="false"
                @change="onChange"
                @backspace="onBackspace"
            >
                <view>
                    <view class="u-flex u-row-center u-m-t-48">
                        <u-message-input
                            mode="box"
                            :maxlength="6"
                            :dot-fill="true"
                            v-model="password"
                            :disabled-keyboard="true"
                            @finish="finish"
                        ></u-message-input>
                    </view>
                    <view class="u-text-center u-padding-top-10 u-padding-bottom-20 tips">支付键盘</view>
                </view>
            </u-keyboard>
            <u-modal
                :show-title="false"
                v-model="showPayPswError"
                content="密码有误！"
                :show-cancel-button="true"
                confirm-text="重新支付"
                @confirm="payAgain"
                confirm-color="#ffcb57"
            ></u-modal>
            <u-toast ref="uToast" />
        </view>
    </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import request from '../../common/service';

export default {
    data() {
        return {
            isUrgentOrder: false,
            isAutoChange: false,
            showRegion: false,
            showExpectedTime: false,
            name: '',
            phone: '',
            address: '',
            gps: '',
            expectedTime: '选择上门时间',
            logistics: '',
            mark: '',
            province: null,
            city: null,
            area: null,
            params: {
                year: true,
                month: true,
                day: true,
                hour: false,
                minute: false,
                second: false,
            },
            loading: false,
            addressDetail: '',
            payType: null,
            expectAmount: null,
            addresRec: '',
            showModal: false,
            showPswModal: false,
            password: '',
            showPay: false,
            orderId: '',
            disableInput: false,
            showPswTips: false,
            showPayPswError: false,
            defaultTime: '',
        };
    },
    onLoad() {
        console.log(this.publishDetail);
        const now = new Date();
        now.setTime(now.getTime() + 24 * 60 * 60 * 1000);
        this.defaultTime = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
        this.expectedTime = this.defaultTime;
    },
    onShow() {
        if (this.orderId) {
            this.disableInput = true;
        }
    },
    computed: {
        ...mapGetters({
            publishDetail: 'publish/publishDetail',
            curUserinfo: 'user/displayUserInfo',
            userDetail: 'user/userDetail',
        }),
        region() {
            if (!this.province) {
                return '请选择地址';
            }
            return `${this.province.label}/${this.city.label}/${this.area.label}`;
        },
        totalAmount() {
            return this.publishDetail.FGoodsMouldEntity.map((x) => x.FAmount).reduce((prev, current) => {
                return prev + current;
            });
        },
    },
    watch: {
        addressDetail(value) {
            const _t = this;
            uni.request({
                url: 'https://apis.map.qq.com/ws/geocoder/v1/',
                data: {
                    address: `${this.province.label}${this.city.label}${this.area.label}${value}`,
                    key: 'LXNBZ-L5UC3-VE33D-YNCRH-OJCKK-IABDF',
                },
                method: 'GET',
                success: function (res) {
                    const { data, statusCode } = res;
                    if (statusCode !== 200) {
                        console.log('服务异常');
                        return;
                    }
                    if (data.status === 0) {
                        const { lat, lng } = data.result.location;
                        _t.gps = `${lat},${lng}`;
                    }
                },
            });
        },
    },
    methods: {
        ...mapActions({
            updateCurrentStatus: 'order/updateCurrentStatus',
            updateCurrentOrder: 'order/updateCurrentOrder',
            updateUserDetail: 'user/updateUserDetail',
        }),
        goChangePsw() {
            this.$u.route('/pages/password/pay/index');
        },
        chooseRegion() {
            if (this.disableInput) {
                return;
            }
            this.showRegion = true;
        },
        confirmRegion(e) {
            // const areaList = await this.getqqmapLocation(e);
            // console.log(areaList, typeof areaList)
            // debugger
            this.province = e.province;
            this.city = e.city;
            this.area = e.area;
        },
        openMap() {
            if (this.disableInput) {
                return;
            }
            const _t = this;
            uni.chooseLocation({
                success: function (res) {
                    _t.address = res.name;
                    _t.gps = `${res.latitude},${res.longitude}`;
                },
            });
        },
        chooseExpectedTime() {
            if (this.disableInput) {
                return;
            }
            this.showExpectedTime = true;
        },
        confirmExpectedTime(e) {
            this.expectedTime = `${e.year}-${e.month}-${e.day}`;
        },
        getqqmapLocation(params) {
            console.table(params);
            const cityList = ['北京市', '重庆市', '天津市', '上海市'];
            //香港,澳门,台湾 查不到数据(id对应不上，写死)
            const other = {
                香港: '710000',
                澳门: '810000',
                台湾: '820000',
            };
            console.log('params.province.label', params);
            // const id = params.city.value;
            let id = cityList.includes(params.province.label)
                ? params.province.value + '0000'
                : params.city.value + '00';
            if (['香港', '澳门', '台湾'].includes(params.province.label)) {
                id = other[params.province.label];
            }
            return new Promise((resolve, reject) => {
                uni.request({
                    url: 'https://apis.map.qq.com/ws/district/v1/getchildren',
                    data: {
                        id,
                        key: 'QVXBZ-H4YEK-TOMJT-A2JU3-LMTQQ-H4BAD',
                    },
                    method: 'GET',
                    success: function (res) {
                        console.log('re', res);
                        const { data, statusCode } = res;
                        if (statusCode !== 200) {
                            reject('服务异常');
                        }
                        if (data.status === 0) {
                            resolve(data.result[0]);
                        } else {
                            reject(data.message || '查询行政区域服务异常');
                        }
                    },
                    error: function (err) {
                        reject(err);
                    },
                });
            });
        },
        changePayType(e) {
            this.payType = parseInt(e.name);
        },
        handleRecognition() {
            const _t = this;
            const { addresRec } = this;
            if (!addresRec) {
                this.$refs.uToast.show({
                    title: '请按照格式填入您的地址',
                });
                return;
            }
            uni.request({
                url: 'https://aip.baidubce.com/oauth/2.0/token',
                data: {
                    grant_type: 'client_credentials',
                    client_id: 'zK0l8vY7b2rRFsyXHVlbOjzT',
                    client_secret: '3VOg0lP3Qg7bDnYtd8ro2oUCf8cDfHRX',
                },
                method: 'GET',
                success: function (res) {
                    const { statusCode, data } = res;
                    if (statusCode === 200) {
                        const { access_token } = data;
                        uni.request({
                            url: `https://aip.baidubce.com/rpc/2.0/nlp/v1/address?access_token=${access_token}`,
                            data: {
                                text: addresRec,
                            },
                            success: function (res1) {
                                const {
                                    log_id,
                                    town,
                                    city,
                                    county_code,
                                    county,
                                    city_code,
                                    phonenum,
                                    province_code,
                                    town_code,
                                    province,
                                    person,
                                    detail,
                                    text,
                                } = res1.data;
                                _t.confirmRegion({
                                    area: {
                                        label: county,
                                        value: county_code,
                                    },
                                    city: {
                                        label: city,
                                        value: city_code,
                                    },
                                    province: {
                                        label: province,
                                        value: province_code,
                                    },
                                });
                                _t.name = person;
                                _t.phone = phonenum;
                                _t.addressDetail = detail;
                            },
                        });
                    }
                },
                error: function (err) {},
            });
        },
        placeOrder() {
            const {
                name,
                phone,
                address,
                gps,
                expectedTime,
                logistics,
                province,
                city,
                area,
                isUrgentOrder,
                isAutoChange,
                mark,
                addressDetail,
                curUserinfo,
                payType,
                expectAmount,
                totalAmount,
                orderId,
            } = this;
            if (
                !name ||
                !phone ||
                !addressDetail ||
                expectedTime === '选择上门时间' ||
                !province ||
                !city ||
                !area ||
                !payType
            ) {
                this.$refs.uToast.show({
                    title: '请完善信息后再提交！',
                });
                return;
            }
            // 未设置支付密码
            if (this.userDetail.FPayPassword === ' ') {
                if (this.curUserinfo.userType === '个人') {
                    this.showPswModal = true;
                    return;
                }
                if (this.curUserinfo.userType === '企业用户' && !this.curUserinfo.isManager) {
                    this.showPswTips = true;
                    return;
                }
                this.showPswModal = true;
                return;
            }
            // 正则校验
            const phoneReg = new RegExp('0?(13|14|15|17|18|19)[0-9]{9}');
            if (phoneReg.test(name) || phoneReg.test(addressDetail) || phoneReg.test(mark)) {
                this.$refs.uToast.show({
                    title: '请勿在姓名、详细地址、备注中填写手机号码！',
                });
                return;
            }
            if (payType === 1) {
                // 余额不足付款
                if (this.curUserinfo.balance < this.totalAmount) {
                    this.showModal = true;
                    return;
                }
                // 输入支付密码
                this.showPay = true;
                return;
            }
            this.pay();
        },
        goRecharge() {
            this.$u.route('/pages/recharge/index');
        },
        onChange(val) {
            if (this.password.length < 6) {
                this.password += val;
            }
            if (this.password.length >= 6) {
                if (this.password === this.userDetail.FPayPassword) {
                    this.pay();
                } else {
                    this.showPay = false;
                    this.password = '';
                    this.showPayPswError = true;
                }
            }
        },
        pay() {
            this.showPay = false;
            const {
                name,
                phone,
                address,
                gps,
                expectedTime,
                logistics,
                province,
                city,
                area,
                isUrgentOrder,
                isAutoChange,
                mark,
                addressDetail,
                curUserinfo,
                payType,
                expectAmount,
                totalAmount,
                orderId,
            } = this;
            if (!orderId) {
                uni.showLoading({
                    title: '提交订单中',
                });
                let commitData = {
                    Model: {
                        FCustomerName: name,
                        FCustomerPhone: phone,
                        FHopeServiceTime: expectedTime,
                        Logistics: logistics,
                        FCustomerNote: mark,
                        FPROVINCE: province.label,
                        FPROVINCE_ID: String(province.value).padEnd(6, '0'),
                        FCity: city.label,
                        FCity_ID: String(city.value).padEnd(6, '0'),
                        FCOUNTY: area.label,
                        FCOUNTY_ID: area.value,
                        FLocation: gps,
                        FAdressLocation: address,
                        FAdress: addressDetail,
                        FIsAutoChange: isAutoChange,
                        FIsUrgentOrder: isUrgentOrder,
                        // 上一步的数据
                        FID: 0,
                        ...this.publishDetail,
                        FPayWay: payType,
                        FExpectAmount: expectAmount,
                        FSHAmount: totalAmount,
                        // FSHSAmount: FPayWay === 1 ? totalAmount : '',
                        FDocumentMakerName: curUserinfo.name,
                        FStatus: 'DBJ',
                    },
                };
                request.post('/api/Order/save', commitData).then((res) => {
                    const { code, message } = res;
                    console.log('订单已生成：', res);
                    console.log('订单提交参数：', commitData);
                    uni.hideLoading();
                    if (code === 0) {
                        if (payType === 1) {
                            this.orderId = res.result.Result.Id;
                            this.payForOrder();
                            return;
                        }
                        this.updateCurrentStatus(1).then(() => {
                            this.$refs.uToast.show({
                                title: '下单成功！',
                                isTab: true,
                                url: '/pages/orders/index',
                            });
                        });
                    } else {
                        this.$refs.uToast.show({
                            title: message,
                        });
                    }
                });
            } else {
                this.payForOrder();
            }
        },
        payForOrder() {
            const _t = this;
            uni.showLoading({
                title: '支付中',
            });
            request
                .post('/api/Order/Pay', {
                    FID: this.orderId,
                    FSHSAmount: Number(this.totalAmount).toFixed(2),
                    FStatus: 'DBJ',
                })
                .then((res) => {
                    console.log('订单支付参数：', this.orderId);
                    const { code, message } = res;
                    if (code === 0) {
                        uni.showLoading({
                            title: '支付成功，正在跳转',
                        });
                        _t.updateCurrentStatus(1).then(() => {
                            _t.getAccountInfo();
                        });
                    } else {
                        _t.$refs.uToast.show({
                            title: message,
                        });
                    }
                    uni.hideLoading();
                });
        },
        onBackspace(e) {
            if (this.password.length > 0) {
                this.password = this.password.substring(0, this.password.length - 1);
            }
        },
        payAgain() {
            this.showPay = true;
        },
        getAccountInfo() {
            const _t = this;
            request.get('/api/Business/View').then((res) => {
                const { code, message, result } = res;
                if (code === 0) {
                    uni.hideLoading();
                    const detail = JSON.parse(result.result);
                    _t.updateUserDetail(detail).then(() => {
                        _t.$refs.uToast.show({
                            title: '订单支付成功',
                            isTab: true,
                            url: '/pages/orders/index',
                        });
                    });
                } else {
                    uni.hideLoading();
                    _t.$refs.uToast.show({
                        title: message,
                    });
                }
            });
        },
    },
    onShareAppMessage(res) {
        if (res.from === 'button') {
            // 来自页面内分享按钮
            console.log(res.target);
        }
        return {
            title: '京台分享更多精彩',
            path: '/pages/index/index',
            imageUrl: '/static/images/share/WechatIMG96.png'
        };
    },
};
</script>

<style lang="scss" scoped>
.content {
    .header {
        background-color: #ffcb57;
    }
    .wrap {
        display: flex;
        flex-direction: column;
        height: calc(100vh - var(--window-top));
        width: 100%;
        .recognition {
            margin: 30rpx 30rpx 0 30rpx;
            .addresRec {
                /deep/ .u-input--border {
                    background-color: #fff;
                }
            }
            /deep/.u-hairline-border {
                &::after {
                    border: none;
                }
            }
        }
        .distinguish {
            /deep/.u-input {
                padding: 0 !important;
            }
            /deep/.u-btn {
                margin: 12rpx 0;
                width: 300rpx;
            }
        }
        .coupon {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .paydetail {
            .line {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 6rpx 0;
                .title {
                    font-size: 24rpx;
                    color: #8c8c8c;
                }
                .content {
                    font-size: 26rpx;
                    color: #434343;
                    &.total {
                        font-size: 32rpx;
                        color: #f5222d;
                    }
                }
            }
        }
        .mlabel {
            font-size: 24rpx;
            color: #595959;
            .desc {
                font-size: 20rpx;
                color: #8c8c8c;
            }
        }
        .reward {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .minddesc {
            color: #f5222d;
        }
    }
}
</style>
