<template>
    <BaseContainer class="activity-event">
        <NavBar title="线下课预约" />
        <view class="form-section">
            <form>
                <label :class="{ required: item.is_required }" v-for="(item, index) in event" :key="item.id">
                    <view>{{ item.event_name }}</view>
                    <input v-if="item.event_type === 1" v-model.trim="item.event_value"
                        :placeholder="'请输入' + item.event_name" type="text">
                    <input v-else-if="item.event_type === 4" v-model.trim="item.event_value"
                        :placeholder="'请输入' + item.event_name" type="tel" maxlength="11">
                    <!-- 单选 -->
                    <view class="uni-list-cell" v-else-if="item.event_type === 5 || item.event_type === 2">
                        <view class="uni-list-cell-db">
                            <picker @change="focusPicker($event, index, item.eventValue)" range-key="value"
                                :range="item.eventValue">
                                <view class="uni-input" :class="!item.event_value ? 'greycolor' : ''">
                                    <text>{{ item.event_value ? item.event_value : '请选择' + item.event_name }}</text>
                                </view>
                            </picker>
                        </view>
                    </view>
                    <!-- 多选 -->
                    <view v-else-if="item.event_type === 3" class="showcheckbox">
                        <view @click="showPopup(index)" :class="!item.event_value.length ? 'greycolor' : ''">
                            {{ item.event_value.length ? item.event_value.join() : '请选择' + item.event_name }}</view>
                    </view>
                    <i v-if="item.event_type !== 1 && item.event_type !== 4" class="iconfont iconxiangyou"></i>
                </label>
                <label v-if="selectedPeople" class="required">
                    <div>人数</div>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-db">
                            <picker @change="PeoplePicker" range-key="text" :range="peopleOptions">
                                <view class="uni-input">
                                    <text>{{ selectedPeople ? selectedPeople : '请选择' }}</text>
                                </view>
                            </picker>
                        </view>
                    </view>
                    <i class="iconfont iconxiangyou"></i>
                </label>
            </form>
        </view>
        <template v-for="(item, index) in event">
            <uni-popup :ref="`popup${index}`" :safe-area="false" type="bottom" v-if="item.event_type === 3" :key="item.id">
                <view class="checboxcontent">
                    <uni-data-checkbox multiple :wrap="false" 
                    v-model="item.event_value" :localdata="item.eventValue"
                       ></uni-data-checkbox>
                </view>
            </uni-popup>
        </template>
        <view class="foot-section">
            <view>合计：</view>
            <view><text>￥</text>{{ total }}</view>
            <button type="button" @click="register">立即报名</button>
        </view>
        <!-- 支付弹窗 -->
        <PayDialog :open.sync="payDialogOpen" :money="total" :now_money="nowMoney" :special_id="id" :pay_type_num="20"
            :is-wechat="isWechat" :is-alipay="!!isAlipay" :is-balance="isBalance" :signs="{ event: event }"
            :template-id="templateId" :wxpay-h5="wxpayH5" :price-id="priceId" :memberMoney="memberMoney"
            :isMembership="true" :isMember="!!this.level" @change="changeVal">
        </PayDialog>
    </BaseContainer>
</template>

<script>
import {
    getActivityEventData,
    getActivityEventPrice

} from "@/api/activity";
import { getAuthInfo } from "@/api/auth";
import PayDialog from "@/components/PayDialog/index.vue";
import { aliPayApp, aliPayWap } from "@/api/special";

export default {
    data() {
        return {
            id: 0,
            event: [],
            price: [],
            selectedPeople: '',
            selectedIndex: 0,
            total: 0,
            picker: null,
            payDialogOpen: false,  // 是否显示支付弹窗
            nowMoney: 0,
            isWechat: false,
            isAlipay: 0,
            isBalance: false,
            signs: 0,
            templateId: '',
            wxpayH5: false,
            priceId: 0,
            peopleOptions: [],
            multipleTitle: '',
            multipleOptions: [],
            multipleIndex: 0,
            multipleShow: false,
            level: 0,
            isOpenWeixing: false,
            memberMoney: 0,
            hobby: [{
                text: '足球',
                value: 0
            }, {
                text: '篮球',
                value: 1
            }, {
                text: '游泳',
                value: 2
            }],
        };
    },
    watch: {},
    components: {
        PayDialog,
    },
    onShow() {
        if (this.isOpenWeixing && this.orderId) {
            this.$util.wxh5PayIsSuccess(this.orderId, 2, this)
            this.isOpenWeixing = false
        }
    },
    onLoad({ id }) {
        this.id = typeof (id) == "string" ? parseInt(id) : id;
        this.getAuthInfo();
        this.getActivityEventData();
        this.getActivityEventPrice();

        if (this.isWechat) {
            this.getTemplateIds();
        }
        console.log("111"+this.level)
    },
    methods: {
        checkboxChange(e, index) {
            console.log(e, index);
        },
        showPopup(index) {
            console.log(`popup:` + index);
            this.$refs[`popup${index}`][0].open()
        },
        PeoplePicker({ detail }) {
            let index = detail.value
            if (typeof this.focusIndex === 'undefined') {
                this.selectedPeople = this.peopleOptions[index].value;
                this.selectedIndex = index;
                this.total = Number(this.price[this.selectedIndex][this.level == '1' ? 'event_mer_price' : 'event_price']);
                this.memberMoney = Number(this.price[this.selectedIndex]['event_mer_price']);
                this.priceId = this.price[this.selectedIndex].id;
            } else {
                this.event[this.focusIndex].event_value = this.peopleOptions[index].value;
            }
        },
        async getAuthInfo() {
            const res = await getAuthInfo();
            const { nowMoney, isWechat, isAlipay, isBalance, wxpayH5 } = res.data
            this.level = res.data.userInfo.level
            console.log("666"+this.level)
            Object.assign(this, {
                nowMoney,
                isWechat,
                isAlipay,
                isBalance,
                wxpayH5
            })
        },
        // 资料项
        getActivityEventData: function () {
            let vm = this;
            getActivityEventData({ id: this.id }).then(res => {

                let data = res.data;
                data.forEach(function (item) {
                    if ([2, 3].includes(item.event_type)) {
                        item.eventValue = item.event_value.split('#');
                        item.eventValue.forEach(function (value, index) {
                            item.eventValue[index] = {
                                text: value,
                                value: value
                            };
                        });
                        item.event_value = item.event_type == 3 ? [] : '';
                    }

                });
                console.log(data);
                vm.event = data;
            })
        },
        // 价格项
        getActivityEventPrice: function () {
            let vm = this;
            getActivityEventPrice({ id: this.id }).then(res => {
                vm.price = res.data;
                vm.peopleOptions = vm.price.map(function (item) {
                    return {
                        text: item.event_number + '人',
                        value: item.event_number
                    };
                });
                vm.selectedPeople = vm.peopleOptions[vm.selectedIndex].value;
                vm.total = Number(vm.price[vm.selectedIndex][vm.level === '1' ? 'event_mer_price' : 'event_price']);
                vm.priceId = vm.price[vm.selectedIndex].id;
                vm.memberMoney = Number(vm.price[vm.selectedIndex]['event_mer_price']);
            })
        },
        // 订阅模板id
        getTemplateIds: function () {
            let vm = this;
            store.baseGet($h.U({
                c: 'special',
                a: 'getTemplateIds',
                q: {
                    special_id: this.id,
                    pay_type_num: 20
                }
            }), function (res) {
                vm.templateId = res.data.msg;
            });
        },
        // 确定人数
        pickerSelect: function (selectedVal, selectedIndex) {
            if (typeof this.focusIndex === 'undefined') {
                this.selectedPeople = selectedVal[0];
                this.selectedIndex = selectedIndex[0];
                this.total = Number(this.price[this.selectedIndex][this.level == '1' ? 'event_mer_price' : 'event_price']);
                this.memberMoney = Number(this.price[this.selectedIndex]['event_mer_price']);
                this.priceId = this.price[this.selectedIndex].id;
            } else {
                this.event[this.focusIndex].event_value = selectedVal[0];
            }
        },
        // 立即报名
        register: function () {

            for (var i = 0, len = this.event.length; i < len; i++) {
                if (!this.event[i].is_required) {
                    continue;
                }
                switch (this.event[i].event_type) {
                    case 1:
                        if (!this.event[i].event_value) {
                            this.$util.showMsg('请输入' + this.event[i].event_name);
                            return;
                        }
                        break;
                    case 2:
                    case 3:
                        if (!this.event[i].event_value.length) {
                            this.$util.showMsg('请选择' + this.event[i].event_name);
                            return;
                        }
                        break;
                    case 5:
                        if (!this.event[i].event_value) {
                            this.$util.showMsg('请选择' + this.event[i].event_name);
                            return;
                        }
                        break;
                    case 4:
                        if (!this.event[i].event_value) {
                            this.$util.showMsg('请输入' + this.event[i].event_name);
                            return;
                        } else if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.event[i].event_value)) {
                            this.$util.showMsg('请输入正确的' + this.event[i].event_name);
                            return;
                        }
                        break;
                }
            }
            this.payDialogOpen = true;
        },
        changeVal: function (opt) {
            var action = '';
            var value = '';
            if (typeof opt !== 'object') {
                opt = {};
            }
            action = opt.action || '';
            value = opt.value || '';
            if (this[action]) {
                this[action](value);
            }
        },
        pay_order: function (data) {
            this.orderId = data.data.result.orderId
            switch (data.data.status) {
                case "PAY_ERROR": case 'ORDER_EXIST': case 'ORDER_ERROR':
                    this.extendOrder(data.msg);
                    break;
                case 'WECHAT_PAY':
                    this.wechatPay(data.data.result.jsConfig);
                    break;
                case 'WECHAT_H5_PAY':
                    this.payDialogOpen = false;
                    this.$util.wechatH5Pay(data.data.result.jsConfig, this);
                    break;
                case "WECHAT_ROUTINE_PAY":
                    this.$util.wechatRoutinePay(data.data.result.jsConfig, this);
                    break;
                case 'SUCCESS':
                    this.successOrder(data.msg);
                    break;
                case 'ZHIFUBAO_PAY':
                    this.aliPay(data.data.result, "signup")
                    break;
            }
        },
        aliPay(msn, type) {
            this.$util.aliPay(msn, type, this)
        },
        focusPicker: function (e, index, list) {

            this.event[index].event_value = list[e.detail.value].value
            //this.focusIndex = index;
        },
        successOrder: function (msg) {
            this.$util.showModal(msg || '支付成功', '', () => {
                uni.redirectTo({
                    url: '/pages/my/sign_list'
                });
            })

        },
        extendOrder: function (msg) {
            if (typeof msg === 'object') {
                if (msg.errMsg === 'chooseWXPay:cancel') {
                    msg = '微信支付取消';
                } else {
                    msg = '支付失败';
                }
            } else {
                msg = '支付失败';
            }
            this.payDialogOpen = false
            this.$util.showMsg(msg)
        },
        wechatPay: function (config) {
            this.$util.weixinpay(config, this)
        }
    },
};
</script>
<style lang="scss" scoped>
.activity-event .form-section uni-label uni-label {
    border-top: 1px solid;
}

.uni-list-cell {
    flex: 1
}

.uni-input {
    text-align: right;
}

.greycolor {
    color: grey;
}

body {
    background-color: #F5F5F5;
}

.picker .picker-panel .picker-choose .picker-title {
    font-weight: 500 !important;
    font-size: 32rpx !important;
    line-height: 112rpx !important;
    color: #282828 !important;
}

.select-multiple .panel {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 600;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 486rpx;
    border-radius: 16rpx 16rpx 0 0;
    background: #FFFFFF;
    transform: translateY(486rpx);
    transition: all .5s;
}

.select-multiple .panel.on {
    transform: translateY(0);
}

.select-multiple .panel-head {
    display: flex;
    height: 100rpx;
    font-size: 32rpx;
    line-height: 100rpx;
    text-align: center;
    color: #282828;
}

.select-multiple .panel-head div:first-child {
    width: 104rpx;
    color: #999999;
    cursor: pointer;
}

.select-multiple .panel-head div:nth-child(2) {
    flex: 1;
    min-width: 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.select-multiple .panel-head div:nth-child(3) {
    width: 104rpx;
    color: #2C8EFF;
    cursor: pointer;
}

.select-multiple .panel-body {
    flex: 1;
    min-height: 0;
    padding: 200rpx 0 0 200rpx;
    overflow-x: hidden;
    overflow-y: auto;
}

.select-multiple .panel-body label {
    display: inline-block;
    margin: 0 200rpx 200rpx 0;
    font-size: 32rpx;
    line-height: .5;
    color: #282828;
}

.select-multiple .panel-body input[type="checkbox"] {
    width: 32rpx;
    height: 32rpx;
    margin-right: 16rpx;
    vertical-align: text-bottom;
    appearance: checkbox;
}

.showcheckbox {
    flex: 1;
    text-align: right;
}

.checklist-box {
    border-top: 1px solid #ffffff;
}

.checboxcontent {
    background-color: #ffffff;
    height: 500rpx;
    border-radius: 15px 15px 0 0;
    padding: 36rpx;
}

.checklist-box {
    border-top: 0px;
}
</style>