// components/three_yards/three_yards.js
const upload_image = require("../../utils/upload/upload_image");
import international from '../../international/appointment_scence/index'

import {
    getXcInfo,
    sendMessage,
    getJkmAndHs,
} from '../../utils/api/three_yards'
const app = getApp()
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        // 语言
        language: {
            type: String,
            value: 'ch'
        },
        // 手机号
        xcPhone: {
            type: Number
        },
        //时间秒
        moMsgWait: {
            type: Number,
            value: 60
        },
        //验证码长度
        codeLength: {
            type: Number,
            value: 6
        },
        //预约开始时间
        startTime: {
            type: String
        },
        //核酸时长（单位小时）
        hsHour: {
            type: Number,
        },
        //三码 1-健康码 2-核酸 3-行程码
        threeCodeList: {
            type: Array
        },
        //楼宇id
        buildingId: {
            type: Number,
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        international: international, //国际化语言包
        form: {
            // xc: null, //行程信息1 代表没有去过高风险地区 2 代表去过高风险地区 3 代表用户没有行程记录
            // hs: null, //核酸
            // jkm: null, //健康码,1绿2黄3红
            // xcPhone: null,
        },
        moDisabled: false, //验证码是否可点击
        moCodeMsg: '获取验证码', //验证码文字
        focus: false, // 隐藏的输入框是否获取焦点
        codeVal: [], //验证码
        inputCodeFocus: [], //验证码样式
    },

    /**
     * 组件的方法列表
     */
    methods: {
        getValue(e) {
            let that = this
            let {
                form
            } = this.data
            if (e.currentTarget.dataset.type == 'xcPhone') {
                form[e.currentTarget.dataset.type] = e.detail.value
            } else {
                wx.chooseMedia({
                    count: 1,
                    mediaType: ['image'],
                    sizeType: ['original'],
                    sourceType: ['album', 'camera'],
                    success(res) {
                        var image = {
                            url: res.tempFiles[0].tempFilePath
                        }
                        wx.showLoading({
                            title: '上传中~',
                        })
                        upload_image(image).then((img) => {
                            wx.hideLoading()
                            form[e.currentTarget.dataset.type] = img.url
                            that.setData({
                                form
                            })
                            that.verifyForm()
                        }).catch(() => {
                            wx.hideLoading()
                        })
                    }
                })
            }
        },
        // 校验是否填写完整
        verifyForm() {
            let {
                form,
            } = this.data
            let isthreeYards = form
            for (let key in form) {
                if (form[key] == '') {
                    isthreeYards = false
                }
            }
            this.triggerEvent('isthreeYards', isthreeYards)
        }, //
        //删除照片
        DelImg(e) {
            let that = this
            let form = this.data.form
            wx.showModal({
                title: '提示',
                content: '确定删除？',
                cancelText: '取消',
                confirmText: '确定',
                success: res => {
                    if (res.confirm) {
                        form[e.currentTarget.dataset.type] = ''
                        that.setData({
                            form
                        })
                        that.verifyForm()
                    }
                }
            })
        },
        // 预览图片
        previewImg(event) {
            // 拿到图片的地址url
            let currentUrl = event.currentTarget.dataset.src;
            // 微信预览图片的方法
            wx.previewImage({
                current: currentUrl, // 图片的地址url
                urls: [currentUrl] // 预览的地址url
            })
        },

        // 获取验证码
        getCode() {
            if (this.data.form.xcPhone) {
                this.setData({
                    moDisabled: true
                });
                wx.showLoading({
                    title: '发送中...',
                })
                sendMessage({
                    phone: this.data.form.xcPhone
                }).then(res => {
                    wx.hideLoading();
                    if (res.code == 0) {
                        wx.showToast({
                            title: '验证码发送成功，请注意查收',
                            icon: 'none'
                        })
                        this.setData({
                            focus: true
                        })
                        var inter = setInterval(function () {
                            if (this.data.moMsgWait < 1) {
                                clearInterval(inter)
                                this.setData({
                                    moCodeMsg: "获取验证码",
                                    moMsgWait: 60,
                                    moDisabled: false,
                                });
                                return;
                            }
                            this.setData({
                                moCodeMsg: "重新发送(" + this.data.moMsgWait + ")",
                                moMsgWait: this.data.moMsgWait - 1,
                                moDisabled: true
                            });
                        }.bind(this), 1000);
                    } else {
                        wx.showToast({
                            title: res.msg,
                            icon: 'none'
                        })
                        this.setData({
                            moDisabled: true
                        });
                    }
                })
            } else {
                wx.showToast({
                    title: '手机号不能为空!',
                    icon: 'none'
                })
            }

        },
        // 长按
        longPressInput() {},
        // 失去焦点
        blurInput() {
            this.inputCodeFocusInit();
            this.setData({
                focus: false
            })
        },
        // 获取焦点
        tapInput() {
            let {
                codeLength,
                codeVal,
                inputCodeFocus
            } = this.data;
            if (codeVal.join('').length == codeLength) {
                inputCodeFocus[codeLength - 1] = true
            } else {
                inputCodeFocus[codeVal.join('').length] = true
            };
            this.setData({
                focus: true,
                inputCodeFocus
            })
        },
        // 输入验证码
        inputVal(e) {
            let value = e.detail.value;
            let {
                codeLength,
                codeVal,
                inputCodeFocus,
                focus
            } = this.data;
            inputCodeFocus = new Array(codeLength).fill(false);
            if (value.length > codeVal.join('').length) {
                inputCodeFocus[value.length - 1 >= 0 ? value.length - 1 : 0] = false;
                if (value.length == codeLength) {
                    focus = false
                } else {
                    inputCodeFocus[value.length] = true;
                }
            } else {
                if (value.length == 0) {
                    inputCodeFocus[0] = true
                } else {
                    inputCodeFocus[value.length - 1] = true
                }
            }
            codeVal = codeVal.map((item, index) => {
                return value.split('')[index] || ''
            })
            this.setData({
                codeVal,
                inputCodeFocus,
                focus
            })
            // 判断参数是否填写完全，若完全，查询接口,接口返回成功,隐藏手机号和验证码两行
            if (codeVal.join('').length == codeLength) {
                this.getXcInfo()
            }
        },
        // 获取行程信息
        getXcInfo() {
            wx.showLoading({
                title: '查询中..',
            })
            let {
                form,
                codeVal,
            } = this.data;
            form.verification = codeVal.join('')
            getXcInfo({
                verification: form.verification,
                phone: form.xcPhone,
                adminId: this.data.buildingId,
            }).then(res => {
                if (res.code == 200) {
                    form.xc = res.data
                    if (res.data == 3) {
                        form.xcPhoto = ''
                    }
                    this.setData({
                        form
                    })
                    this.verifyForm()
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
                wx.hideLoading()
            })
        },
        // 获取健康码和核酸信息
        getJkmAndHs() {
            let {
                form
            } = this.data
            let {
                userInfo
            } = app.data
            wx.showLoading({
                title: '查询账号配置~',
            })
            getJkmAndHs({
                idNumber: userInfo.idNumber,
                name: userInfo.username,
                phone: userInfo.phone,
                adminId: this.data.buildingId,
            }).then(res => {
                if (res.data.jkmStatus == 1) {
                    form.jkm = res.data.jkm
                    if (res.data.jkm != '绿码') {
                        wx.showToast({
                            title: '健康码状态异常哦~',
                            icon: 'none'
                        })
                        this.setData({
                            'form.unqualifiedJKM': ''
                        })
                    }
                } else if (res.data.jkmStatus == 2) {
                    form.jkmPhoto = ''
                }
                // res.data.hsStatus = 1;
                // form.hsStatus = 1
                if (res.data.hsStatus == 1) {
                    // form.hsResultTime = res.data.hsResultTime || '2022-11-24 12:15:00'
                    // form.hs = res.data.hs || '阴性'
                    // res.data.hs = '阴性'
                    let startTime_number = this.data.startTime ? Date.parse(new Date(this.data.startTime)) : Date.now();
                    let resultTime_number = Date.parse(new Date(form.hsResultTime));
                    if (((startTime_number - resultTime_number) >= this.data.hsHour * 60 * 60 * 1000) || res.data.hs !== "阴性") {
                        wx.showToast({
                            title: '您不满足进入时拥有' + this.data.hsHour + '小时内阴性核酸报告',
                            icon: 'none'
                        })
                        form.unqualifiedHS = ''
                    } else {
                        form.unqualifiedHS = true
                    }
                } else if (res.data.hsStatus == 2) {
                    setTimeout(() => {
                        wx.showToast({
                            title: '您不满足进入时拥有' + this.data.hsHour + '小时内阴性核酸报告',
                            icon: 'none'
                        })
                        setTimeout(() => {
                            wx.hideToast();
                        }, 2000)
                    }, 0);
                    form.hsPhoto = ''
                }
                this.setData({
                    form
                })
                wx.hideLoading()
                this.verifyForm()
            })
        },
        //输入数据初始化
        codeValInit() {
            this.data.codeVal = new Array(this.data.codeLength).fill('');
            this.setData({
                codeVal: this.data.codeVal
            })
        },
        //焦点数据初始化
        inputCodeFocusInit() {
            this.data.inputCodeFocus = new Array(this.data.codeLength).fill(false);
            this.setData({
                inputCodeFocus: this.data.inputCodeFocus
            })
        }

    },
    observers: {
        'xcPhone': function (n) {
            if (n) {
                let {
                    form,
                } = this.data
                form.xcPhone = n
                this.setData({
                    form
                })
            }
        },
        'startTime': function (n) {
            this.getJkmAndHs();
        },
        threeCodeList(n) {
            this.setData({
                form: {
                    xcPhone: this.data.xcPhone,
                },
            })
            if (n.indexOf('1') > -1 || n.indexOf('2') > -1) {
                this.getJkmAndHs()
            }
            if (n.indexOf('3') > -1) {
                this.setData({
                    'form.xc': ''
                })
            }
        },
    },
    lifetimes: {
        attached() {
            this.codeValInit()
            this.inputCodeFocusInit()
        }
    }
})