<template>
    <div class="klkl-turntable-bg">
        <img class="logo" src="https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/klkl/logo2.png">
        <input-info v-if="isShowInput" @confirm="inputConfirm"></input-info>
        <div class="dzp" v-if="!isShowInput">
            <img class="slogan" src="https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/klkl/turntable-slogan.png">
            <turnplate :prize-index="prizeIndex" :prizes="prizes" @start="start" @stop="stop"></turnplate>
            <img class="turnplate-bt" src="https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/klkl/turnplate-bt.png">
        </div>
        <result v-model="isResultVisible" :result-data="resultData" @inputInfo="isShowInput = true"></result>
        <img class="milk" src="https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/klkl/milk.png">
    </div>
</template>

<script>
    import mobileInit from '@/assets/js/mobile-init'
    import Turnplate from '@/components/marketing/temp004/components/Turntalbe'
    import InputInfo from '@/components/marketing/temp004/components/InputInfo'
    import Result from '@/components/marketing/temp004/components/Result'
    import apiHelper from '@/assets/js/apiHelper.js'
    import eventBus from '@/assets/js/eventBus.js'

    export default {
        name: 'Comp',
        components: {Result, InputInfo, Turnplate},
        props: ['comp', 'cfg', 'selectedPage'],
        data() {
            return {
                prizeIndex: null,
                prizes: [],
                isShowInput: false,
                isResultVisible: false,
                resultData: null
            }
        },
        computed: {
            isRunEnv() {
                return this.sup8._def.env.run.val === this.sup8.env.val
            },
            isPreviewEnv() {
                return this.sup8._def.env.preview.val === this.sup8.env.val
            },
        },
        methods: {
            //获取用户信息
            getUserInfo() {
                const {context, codeInfo, h5Template = {ActivityId: ''}, urlparams} = this.sup8
                const geo = !!context.geo ? context.geo.addressComponent : {}
                const userinfo = {
                    Address: `${geo.country}${geo.province}${geo.city}${geo.district}${geo.street}${geo.street_number}`,
                    IsRegister: false,
                    Location: context.channel,
                    WeChat: context.wxUser,
                    DigitCode: codeInfo.Code,
                    ActivityId: h5Template.ActivityId,
                    EnterpriseNo: codeInfo.EnterpriseNo,
                    UserId: context.userId,
                    WebBrowser: navigator.userAgent,
                    Mobile: this.mobile,
                    MsgCode: this.smscode,
                    Channel: urlparams.channel,
                    Vcode: this.sup8.__VCODE,
                    LabelNo: urlparams.labelno
                }
                return JSON.stringify(userinfo)
            },
            //抽奖
            start() {
                this.prizeIndex = null;
                apiHelper.participationActivity(this.getUserInfo(), (res) => {
                    this.resultData = res;
                    if (res.flag) {
                        const {IsNewJoin, WiningRecords} = res.data
                        const {GiftType, AwardsName, RecordUser, AwardsReamrk, Id} = WiningRecords[0]
                        const prizeIndex = this.prizes.findIndex(prize => prize.name === AwardsName)
                        if (!IsNewJoin && GiftType === '2') {
                            //现金红包二次参与提示已参与
                            this.resultData.msg = '此码已参与本次活动'
                            this.prizeIndex = -1
                        } else if (!IsNewJoin && GiftType === '3') {
                            //实物礼品二次参与
                            this.getExistsConsignee(Id, (exists) => {
                                if (exists.flag) {
                                    this.prizeIndex = exists.data ? -1 : prizeIndex;
                                    this.resultData.msg = exists.data ? '此码已参与本次活动' : '';
                                } else {
                                    this.$layerLite.toast('网络开小差了，请稍后再试');
                                }
                            });
                        } else {
                            this.prizeIndex = prizeIndex
                        }
                    } else {
                        this.prizeIndex = -1
                    }
                }, () => {
                    this.$layerLite.toast('网络开小差了，请稍后再试')
                })
            },
            stop() {
                if (this.prizeIndex !== null && this.prizeIndex > -1) {
                    this.isResultVisible = true
                } else {
                    this.$layerLite.toast(decodeURIComponent(this.resultData.msg))
                }
            },
            getExistsConsignee(Winid, callback) {
                const {codeInfo, h5Template = {ActivityId: ''}} = this.sup8
                apiHelper.getExistsConsignee({
                    Winid,
                    EnterpriseNo: codeInfo.EnterpriseNo,
                    ActivityId: h5Template.ActivityId,
                    // ActivityNo: "klkl001",
                }, (res) => {
                    callback(res)
                }, () => {
                    this.$layerLite.toast('网络开小差了，请稍后再试')
                    this.prizeIndex = -1;
                });
            },
            inputConfirm(infoData) {
                const {name, mobile, areaData, address} = infoData
                if (!name) {
                    this.$layerLite.toast('请输入姓名')
                    return
                }
                if (!mobile || mobile.length === 0) {
                    this.$layerLite.toast('请输入手机号')
                    return
                }
                if (!/^\d{11}$/.test(mobile)) {
                    this.$layerLite.toast('请输入正确的手机号')
                    return
                }
                if (!areaData) {
                    this.$layerLite.toast('请选择所在省市')
                    return
                }
                if (!address) {
                    this.$layerLite.toast('请输入详细地址')
                    return
                }
                this.$layerLite.loading.open();
                const {context, codeInfo, h5Template = {ActivityId: ''}, urlparams} = this.sup8
                apiHelper.getSaveConsignee({
                    Winid: this.resultData.data.WiningRecords[0].Id,
                    EnterpriseNo: codeInfo.EnterpriseNo,
                    ActivityId: h5Template.ActivityId,
                    // ActivityNo: "klkl001",
                    ConsigneeName: name,
                    ConsigneeMobile: mobile,
                    ConsigneeAddress: `${areaData},${address}`,
                    LanguageType: "zh-cn"
                }, (res) => {
                    if (res.flag) {
                        this.$layerLite.toast('提交成功')
                    } else {
                        this.$layerLite.toast(res.msg)
                    }
                    this.$layerLite.loading.close();
                    this.isShowInput = false;
                }, () => {
                    this.$layerLite.toast('提交失败')
                    this.$layerLite.loading.close();
                });
            },
            //数据初始化
            init() {
                //校验是否注册
                this.$layerLite.loading.open()
                apiHelper.checkIsRegister(this.getUserInfo(),
                    (res) => {
                        if (res.flag) {
                            const {UserId = null} = res.data
                            this.sup8.context.userId = UserId
                        }
                        this.$layerLite.loading.close()
                    },
                    () => {
                        this.$layerLite.loading.close()
                        this.$layerLite.toast('网络开小差了，请稍后再试')
                    }
                )
            },
        },
        created: function () {
            const that = this
            that.mergeCompProps(that.comp)

            switch (that.sup8.env) {
                case that.sup8._def.env.design:
                    that.env = '设计器模式'
                    this.envType = 'design'
                    break
                case that.sup8._def.env.preview:
                    that.env = '预览模式'
                    break
                case that.sup8._def.env.run:
                    that.env = '运行模式'
                    sessionStorage.removeItem('prizeInfo')
                    break
                default:
                    break
            }
        },
        mounted() {
            mobileInit()
            this.prizes = [
                {
                    type: 1,
                    img: 'https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/klkl/huawei-small.png',
                    name: '华为Mate30Pro'
                },
                {
                    type: 2,
                    amount: 1000,
                    name: '1000元现金红包'
                },
                {
                    type: 1,
                    img: 'https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/klkl/abk-small.png',
                    name: 'Karihealth爱毕可复合粉1罐'
                },
                {
                    type: 2,
                    amount: 50,
                    name: '50元现金红包'
                },
                {
                    type: 2,
                    amount: 30,
                    name: '30元现金红包'
                },
                {
                    type: 2,
                    amount: 10,
                    name: '10元现金红包'
                },
                {
                    type: 2,
                    amount: 5,
                    name: '5元现金红包'
                },
                {
                    type: 2,
                    amount: 3,
                    name: '3元现金红包'
                },
            ]
            if (this.isRunEnv) {
                if (this.sup8.context.geo) {
                    this.init()
                } else {
                    eventBus.subscribe('gpsDone', data => {
                        this.init()
                    })
                }
            }
        }
    }
</script>

<style scoped>
    .klkl-turntable-bg {
        width: 100%;
        min-height: 100vh;
        background: url("https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/klkl/tbg.png") no-repeat center center;
        background-size: 100% 100%;
        position: relative;
        text-align: center;
    }

    #part_phone .klkl-turntable-bg {
        width: 320px;
        height: 540px;
    }

    .logo {
        width: 2.27rem;
        margin: 0.4rem auto;
    }

    .slogan {
        width: 5.67rem;
    }

    .milk {
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        max-height: 553px;
    }

    .turnplate-bt {
        width: 5.97rem;
        height: 2.97rem;
        display: block;
        margin: -.85rem auto 0 auto;
    }
</style>
