<template>
    <view>
        <!-- pages/realName/index.wxml -->
        <!-- <view class="navagition">
  <view class="goback iconfont icon-xiangzuo" bindtap='goBack'></view>
</view>-->
        <!-- <view class="" hover-class="none" hover-stop-propagation="false" wx:if="{{!isFinish}}">
  <view class="progress">
    <view class="{{level == 1 || level == 2|| level == 3? 'active':''}}"></view>
    <view class="{{level == 2 || level == 3 &&  level != 1 ?'active':''}}"></view>
    <view class="{{level == 3  ?'active':''}}"></view>
  </view>
  <view class="progressInfo" hover-class="none" hover-stop-propagation="false">
    <view class="{{level == 1 || level == 2|| level == 3? 'active':''}}" hover-class="none" hover-stop-propagation="false">身份证正面</view>
    <view class="{{level == 2 || level == 3 &&  level != 1 ?'active':''}}" hover-class="none" hover-stop-propagation="false">身份证背面</view>
    <view class="{{level == 3  ?'active':''}}" hover-class="none" hover-stop-propagation="false">确认信息</view>
  </view>
</view>-->
        <view class="IDcardBox" hover-class="none" :hover-stop-propagation="false">
            <view class="imgBox" @tap="uploadCard" data-type="2">
                <image :src="user.idcardImgFront ? user.idcardImgFront : 'https://matripe-cms.oss-cn-beijing.aliyuncs.com/1shoudan/face.png'" alt />
                <view class="cardText c6" v-if="!user.idcardImgFront" hover-class="none" :hover-stop-propagation="false">
                    <view class="iconfont icon-tianjia f26 c9 fw500"></view>
                    <text class :selectable="false" :space="false" :decode="false">人像面照片</text>
                </view>
            </view>
            <view class="imgBox" @tap="uploadCard" data-type="3">
                <image :src="user.idcardImgBack ? user.idcardImgBack : 'https://matripe-cms.oss-cn-beijing.aliyuncs.com/1shoudan/back.png'" alt />
                <view class="cardText c6" v-if="!user.idcardImgBack" hover-class="none" :hover-stop-propagation="false">
                    <view class="iconfont icon-tianjia f26 c9 fw500"></view>
                    <text class :selectable="false" :space="false" :decode="false">国徽面照片</text>
                </view>
            </view>
        </view>
        <view class="infoBox mt10">
            <view class="userInfo">
                <view class="bb1 dfsb">
                    <span>姓名</span>
                    <span>
                        <input class="tar" type="text" placeholder-class="c9" placeholder="输入姓名" @input="getRealName" :value="user.realName" />
                    </span>
                </view>
                <view class="bb1 dfsb">
                    <span>性别</span>
                    <picker mode="selector" :value="user.sex" @change="changeDateTime" @columnchange="changeDateTimeColumn" :range="sexArr" range-key="text" style>
                        <view :class="user.sexStr ? 'c3' : 'c9'" hover-class="none" :hover-stop-propagation="false">{{ !!user.sexStr ? user.sexStr : '选择性别' }}</view>
                    </picker>
                </view>
                <view class="dfsb" hover-class="none" :hover-stop-propagation="false">
                    <span>身份证号</span>
                    <span>
                        <input class="tar" type="text" placeholder-class="c9" placeholder="输入身份证号" @input="getId" :value="user.IDCard" maxlength="18" />
                    </span>
                </view>
            </view>
        </view>
        <view class="successIcon" v-if="isFinish">
            <view class="iconfont icon-tijiaochenggong"></view>
            <view class>上传成功</view>
        </view>

        <!-- <view class="toNext {{user.idcardImgFront ? 'ysd-basebg-color':''}}" hover-class="none" data-level='1' bindtap='toNext' wx:if='{{level == 1 && !isFinish}}'>下一步</view>
<view class="toNext {{user.idcardImgBack ? 'ysd-basebg-color':''}}" hover-class="none" data-level='2'  bindtap='toNext' wx:if='{{level == 2 && !isFinish}}'>下一步</view>
<view class="toNext {{canFinish ? 'ysd-basebg-color':''}}" hover-class="none" bindtap='toFinish' wx:if='{{level == 3 && !isFinish}}'>确定</view>-->
        <button v-if="user.idcardImgFront && user.idcardImgBack" class="finish loginOut normalBtn mt32" hover-class="none" :hover-stop-propagation="false" @tap="toFinish">
            确定
        </button>
        <button v-else class="finish loginOut normalBtn mt32" style="background-color: #ccc" hover-class="none" :hover-stop-propagation="false">确定</button>

        <view class="f12 tc c045 mt32">
            <radio-group class="dib">
                <radio
                    :checked="switch1Checked"
                    @click.stop="switch1Change"
                    value="0"
                    class="dib"
                    color="#0dcc91"
                    style="transform: scale(0.7); position: relative; top: -2px"
                />
            </radio-group>
            我已阅读并同意
            <navigator url="/pages/serviceTerm/index" class="aLink dib">《服务协议》</navigator>
            及
            <navigator url="/pages/secret/index" class="aLink dib">《隐私政策》</navigator>
        </view>
        <!-- <view class="f14 tac" style='color:#576B95' hover-class="none" hover-stop-propagation="false">
  修改认证
</view>-->
    </view>
</template>

<script>
// pages/realName/index.js
let app = getApp();
export default {
    data() {
        return {
            level: 1,
            isFinish: false,

            user: {
                sex: '',
                sexStr: '',
                IDCard: '',
                realName: '',
                idcardImgFrontm: '',
                // 正面mini照
                idcardImgFront: '',
                // 正面标准照
                idcardImgBackm: '',
                // 反面mini照
                idcardImgBack: '' // 反面标准照
            },

            canFinish: false,
            switch1Checked: false,

            sexArr: [
                {
                    text: '男',
                    id: 1
                },
                {
                    text: '女',
                    id: 2
                }
            ],

            btnLoading: false
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {
        // if (app.globalData.isLogin) {
        // 	this.setData({
        // 		isLogin: app.globalData.isLogin,
        // 		user: app.globalData.user,
        // 	});
        // 	if (this.data.user.idcardImgBack && this.data.user.idcardImgFront) {
        // 		this.setData({
        // 			btnDisabled: false,
        // 		});
        // 	}
        // 	this.data.user["IDCard"] = this.data.user["IDCard"];
        // } else {
        // 	// 由于 userLogin 是网络请求，可能会在 Page.onLoad 之后才返回
        // 	// 所以此处加入 callback 以防止这种情况
        // 	app.userLoginCallback = (res) => {
        // 		this.setData({
        // 			isLogin: app.globalData.isLogin,
        // 			user: app.globalData.user,
        // 		});
        // 		if (this.data.user.idcardImgBack && this.data.user.idcardImgFront) {
        // 			this.setData({
        // 				btnDisabled: false,
        // 			});
        // 		}
        // 		this.data.user["IDCard"] = this.data.user["idcard"];
        // 	};
        // }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    methods: {
        switch1Change: function (e) {
            console.log('radio发生change事件，携带value值为：', e.detail.value);
            console.log(e.detail.value);
            var check = this.switch1Checked;
            if (check) {
                this.switch1Checked = false;
                console.log('已取消选中');
                uni.showToast({
                    title: '请先阅读并同意《服务协议》及《隐私政策》',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                this.switch1Checked = true;
                console.log('已选中');
            }
            this.setData({
                switch1Checked: this.switch1Checked
            });

            // if(!e.detail.value){

            // }
        },

        /**
         * 用户点击右上角分享
         */
        onShareAppMessage1() {},

        getId(e) {
            console.log(e);
            let user = 'user.IDCard';
            this.setData({
                [user]: e.detail.value
            });
            console.log(this.user.IDCard);
            this.idverify();
        },

        getRealName(e) {
            console.log(e);
            let user = 'user.realName';
            this.setData({
                [user]: e.detail.value
            });
            this.idverify();
        },

        // toNext(data) {
        // 	console.log(data);
        // 	if (data.currentTarget.dataset.level == 1) {
        // 		if (this.isNotEmptyCheck(this.data.user.idcardImgFront)) {
        // 			this.setData({
        // 				level: 2,
        // 			});
        // 		}
        // 	} else {
        // 		if (this.isNotEmptyCheck(this.data.user.idcardImgBack)) {
        // 			this.setData({
        // 				level: 3,
        // 			});
        // 		}
        // 	}
        // 	this.idverify();
        // 	// this.setData({
        // 	//   level : this.data.level <= 2 ? this.data.level + 1 : this.data.level
        // 	// })
        // 	// wx.navigateTo({
        // 	//   url: '../realName2/index',
        // 	// })
        // 	// console.log(123);
        // },
        idverify() {
            var username = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/;
            if (this.user.IDCard.length == 18 && username.test(this.user.realName)) {
                this.setData({
                    canFinish: true
                });
            } else {
                this.setData({
                    canFinish: false
                });
            }
        },

        goBack() {
            // this.data.level = this.data.level - 1
            this.setData({
                level: this.level >= 1 ? this.level - 1 : this.level,
                isFinish: false
            });
            if (this.level == 0) {
                uni.navigateBack({
                    delta: 1
                });
            }
            // this.onLoad()
        },

        toFinish() {
            let that = this;
            this.idverify();
            console.log(that.canFinish);
            if (!that.switch1Checked) {
                uni.showToast({
                    title: '请先阅读并同意《服务协议》及《隐私政策》',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            if (!that.user.idcardImgFront || !that.user.idcardImgBack) {
                uni.showToast({
                    title: '请上传身份证照片',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            if (that.canFinish) {
                uni.showLoading({
                    title: '保存中...',
                    mask: true
                });
                var realName = that.user.realName;
                var IDCard = that.user.IDCard;
                uni.request({
                    url: app.globalData.ip + '/commons/validatecard',
                    data: {
                        name: realName,
                        cardno: IDCard
                    },
                    header: app.globalData.headers,
                    method: 'POST',
                    success: function (res) {
                        console.log(res);

                        // if (res.data.status == 9999) {
                        //   app.dialogNotLogin();
                        //   return;
                        // }

                        var state = res.data.data.state;
                        // wx.navigateTo({
                        // 	url: `/pages/returnMessage/index?from=real&type=success&msg=实名认证成功`,
                        // });
                        // app.globalData.loginUserInfo.user.idauth = 1;
                        // return;
                        if (state == 101) {
                            uni.hideLoading();
                            that.dialog('已被占用', '你输入的身份证号已经被其他人占用了', '知道了');
                        } else if (state == 102) {
                            uni.hideLoading();
                            that.dialog('次数超限', '你今天已经认证失败3次，明天再认证吧', '知道了');
                        } else if (state == 5 || state == 14 || state == 96) {
                            uni.hideLoading();
                            that.dialog('认证失败', '姓名或身份证号错误，认证失败', '知道了');
                        } else if (state == 0) {
                            that.saveIDCard(realName, IDCard);
                        } else {
                            uni.hideLoading();
                            that.dialog('认证失败', res.data.msg, '知道了');
                        }
                    }
                });
            } else {
                uni.showToast({
                    icon: 'none',
                    title: '请确保信息完整',
                    duration: 2000
                });
            }
        },

        saveIDCard: function (realName, IDCard) {
            let that = this;
            uni.request({
                url: app.globalData.ip + '/user/auth/authIDCard',
                data: {
                    realName: realName,
                    IDCard: IDCard
                },
                header: app.globalData.headers,
                method: 'POST',
                success: function (res) {
                    // console.log(res);
                    if (res.data.status == 200) {
                        uni.showToast({
                            title: '保存成功',
                            icon: 'success',
                            image: '',
                            duration: 1000,
                            mask: true,
                            success: function (res) {
                                uni.hideLoading();
                                that.updateSex();
                                app.globalData.loginUserInfo.user.idauth = 1; //如果身份证上传成功，登录缓存的实名认证状态更新为已实名
                                // that.makeInfoSuccess();
                                uni.navigateTo({
                                    url: `../returnMessage/index?from=real&type=success&msg=实名认证成功`
                                });
                            },
                            fail: function (res) {
                                uni.hideLoading();
                            },
                            complete: function (res) {}
                        });
                    } else {
                        uni.navigateTo({
                            url: `../returnMessage/index?from=real&type=fail&msg=实名认证失败&status=${res.data.status}`
                        });
                        // app.showTips(that, res.data.msg);
                    }
                }
            });
        },

        dialog: function (title, content, btxt) {
            uni.showModal({
                title: title,
                content: content,
                showCancel: false,
                confirmColor: '#ff4400',
                confirmText: btxt,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        },

        uploadCard(data) {
            var that = this;
            // return
            let type = data.currentTarget.dataset.type;
            console.log(type);
            uni.chooseImage({
                count: 1,
                // 默认9
                sizeType: ['original', 'compressed'],
                // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'],
                // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    uni.showLoading({
                        title: '上传中',
                        mask: true
                    });
                    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                    var tempFilePaths = res.tempFilePaths;
                    var formData = {
                        type: type,
                        userId: app.globalData.userId
                    };
                    uni.uploadFile({
                        url: app.globalData.ip + '/user/auth/uploadImage',
                        filePath: res.tempFilePaths[0],
                        name: 'uploadFile',
                        header: app.globalData.headers2,
                        // 设置请求的 header
                        formData: formData,
                        // HTTP 请求中其他额外的 form data
                        success: function (res1) {
                            var result = JSON.parse(res1.data);
                            console.log(result);
                            if (result.status == 200) {
                                if (type == 2) {
                                    that.user['idcardImgFrontm'] = result.data.miniUrl;
                                    that.user['idcardImgFront'] = result.data.url;
                                    that.user['IDCard'] = result.data.IDCard;
                                    that.user['realName'] = result.data.realName;
                                    console.log(that.user.IDCard);
                                    if (that.user.IDCard) {
                                        if (that.user.IDCard.slice(16, 17) % 2 == 0) {
                                            that.user.sex = 2;
                                            that.user.sexStr = '女';
                                        } else {
                                            that.user.sex = 1;
                                            that.user.sexStr = '男';
                                        }
                                    }
                                } else if (type == 3) {
                                    that.user['idcardImgBackm'] = result.data.miniUrl;
                                    that.user['idcardImgBack'] = result.data.url;
                                }
                                console.log(that.user);
                                that.setData({
                                    user: that.user
                                });
                            } else {
                                uni.showToast({
                                    icon: 'none',
                                    title: result.msg,
                                    duration: 2000
                                });
                            }
                            //判断是否可以进入下一步
                            // if (!that.isEmptyCheck(that.data.user.idcardImgFront) && !that.isEmptyCheck(that.data.user.idcardImgBack)) {
                            // 	that.setData({
                            // 		btnDisabled: false,
                            // 	});
                            // }
                            uni.hideLoading();
                        },
                        fail: function (res2) {
                            uni.hideLoading();
                        }
                    });
                }
            });
        },

        updateSex() {
            // that.updateSex(that.data.user["IDCard"]);

            var formData = {
                userId: app.globalData.user.id,
                sex: this.user.sex
            };
            uni.request({
                url: app.globalData.ip + '/user/updateSex',
                method: 'POST',
                header: app.globalData.headers,
                data: formData,
                success: function (res) {
                    console.log(res);
                    if (res.data.status == 200) {
                        // let data = "user.sex";
                        // app.({
                        // 	[data]: formData.sex,
                        // });
                        app.globalData.user.sex = formData.sex;
                        console.log(app.globalData.user.sex);
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: res.data.msg,
                            duration: 2000
                        });
                        that.setData({
                            btnLoading: false
                        });
                    }
                }
            });
        },

        isEmptyCheck: function (str) {
            if (str == null || str == '' || str == 'null' || str == 'undefined' || typeof str == 'undefined') {
                return true;
            }
            return false;
        },

        isNotEmptyCheck: function (str) {
            return !this.isEmptyCheck(str);
        },

        tomine() {
            uni.navigateBack({
                delta: 1
            });
        },

        changeDateTime(e) {
            console.log(e);
            console.log(this.sex);
            if (e.detail.value == 0) {
                this.user.sexStr = '男';
                this.user.sex = 1;
            } else {
                this.user.sexStr = '女';
                this.user.sex = 2;
            }
            this.setData({
                user: this.user
            });
        },

        changeDateTimeColumn(e) {
            console.log(e);
        }
    }
};
</script>
<style>
@import './index.css';
</style>
