<template>
    <view>
        <!-- <button catchtap="clear"> 清除缓存</button> -->
        <form @submit.stop.prevent="beforeFormSubmit">
            <view class="mt10" style="padding-bottom: 80px">
                <view class="quickapply" @click.stop="chooseIdCard">
                    <view class="upload">
                        <view class="t-icon t-icon-paizhao"></view>
                        <view size="mini" class="info">
                            <view class="" hover-class="none" :hover-stop-propagation="false">拍照或相册上传</view>
                            <view class="" hover-class="none" :hover-stop-propagation="false">系统智能识别并自动填写</view>
                        </view>
                    </view>
                    <view class="idCardPreview" style="display: flex; align-items: center; justify-content: flex-end" hover-class="none" :hover-stop-propagation="false">
                        <image
                            class=""
                            v-if="currentImg"
                            :src="currentImg"
                            mode="aspectFit|aspectFill|widthFix"
                            :lazy-load="false"
                            @error=""
                            @load=""
                            @click.stop="showImg"
                        ></image>
                        <view class="t-icon t-icon-gengduo111" hover-class="none" :hover-stop-propagation="false" style="width: 18px; height: 18px" v-else></view>
                    </view>
                </view>
                <view class="bgf mt10">
                    <view class="p16">
                        <view class="f16 fwb c3">
                            {{ userInfo.name || '姓名' }}/{{ userInfo.sex || '性别' }}/{{ userInfo.age || '年龄' }}/{{ userInfo.nationality || '' + '族' }}
                        </view>
                        <view class="f16 c6 mt6">{{ userInfo.address }}</view>
                        <view class="display-flex mt6">
                            <view class="flex-1">
                                <view :class="'iconView ' + (userInfo.num == '-' || userInfo.num == '' || userInfo.num == null ? '' : 'active')">
                                    <i class="iconfont icon-shenfenzheng pr" style="top: -2px"></i>
                                </view>
                                <text class="c6 f16 ml10">{{ userInfo.num == '-' || userInfo.num == '' || userInfo.num == null ? '-' : userInfo.num }}</text>
                            </view>
                            <view style="min-width: 120px; top: -2px" class="pr">
                                <view :class="'iconView ' + (userInfo.tel == '-' || userInfo.tel == '' || userInfo.tel == null ? '' : 'active') + ' pr'">
                                    <i class="iconfont icon-dianhua pr" style="font-size: 16px; top: -2px"></i>
                                </view>
                                <text class="c6 f16 ml10">{{ userInfo.tel == '-' || userInfo.tel == '' || userInfo.tel == null ? '-' : userInfo.tel }}</text>
                            </view>
                        </view>
                    </view>
                    <navigator url="./enroll/index" class="editClass" hover-class="hcb">编辑</navigator>
                </view>

                <view class="bgf mt10">
                    <view class="display-flex mt6 p016" style="line-height: 48px; border-bottom: 1rpx solid #eee">
                        <view class="f16 c6" style="width: 80px">报名岗位</view>
                        <view class="flex-1 c3 tr">
                            {{ jobName }}
                        </view>
                    </view>
                    <view class="p16">
                        <view class="display-flex">
                            <view style="width: 80px" class="c6">面试时间</view>
                            <view class="flex-1 c3 tr">
                                {{ currentTime }}
                            </view>
                        </view>
                        <view class="display-flex mt10">
                            <view style="width: 80px" class="c6">接待时间</view>
                            <view class="flex-1 c3 tr">
                                {{ currentTime2 }}
                            </view>
                        </view>
                        <view class="display-flex mt10">
                            <view style="width: 80px" class="c6">政策</view>
                            <view class="flex-1 c3 tr">
                                {{ policy }}
                            </view>
                        </view>
                    </view>
                    <navigator url="./enrollJob/index" class="editClass" hover-class="hcb">编辑</navigator>
                </view>

                <view class="weui-cells__group weui-cells__group_form mt10" style="background-color: #fff">
                    <view class="weui-cell">
                        <view class="weui-cell__hd">
                            <label class="weui-label c6">
                                <!-- <text class="cfred">*</text> -->
                                代理
                            </label>
                        </view>
                        <view class="weui-cell__bd">
                            <view
                                class=""
                                hover-class="none"
                                :hover-stop-propagation="false"
                                style="text-align: right; color: #333"
                                @tap="toJobAndAgencySelect"
                                data-type="agency"
                                v-if="managerRoleClassify"
                            >
                                <view class="" hover-class="none" :hover-stop-propagation="false" v-if="agentName">
                                    {{ agentName }}
                                    <i class="iconfont icon-gengduo11 f16 ml4 dib pr c9" style="line-height: 1; top: 1px"></i>
                                </view>
                            </view>
                            <view class="" v-else hover-class="none" :hover-stop-propagation="false" style="text-align: right; color: #999" data-type="agency">
                                <view class="" hover-class="none" :hover-stop-propagation="false" v-if="agentName">
                                    {{ agentName }}
                                    <i class="iconfont icon-gengduo11 f16 ml4 dib pr c9" style="line-height: 1; top: 1px"></i>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="f12 tc c9 ml14 display-flex" style="align-items: center; margin-top: 16px; margin-bottom: 80px">
                    <!-- <switch checked="{{switch1Checked}}" class="dib" color="#0dcc91" style="transform:scale(.5)" bindchange="switch1Change" /> -->
                    <radio-group class="dib">
                        <radio :checked="switch1Checked" @click.stop="switch1Change" value="0" class="dib" color="#f40" style="transform: scale(0.7)" />
                    </radio-group>
                    我已阅读并同意
                    <navigator url="../serviceTerm/index" class="aLink">《用户服务协议》</navigator>
                    及
                    <navigator url="../secret/index" class="aLink">《隐私政策》</navigator>
                </view>
            </view>

            <!-- <view class="mt24 mb16">
      <button class="weui-btn mbtn newBtn" style="margin-top:20px;" hover-class="thover" form-type='submit'>
        <i class="weui-loading"></i>
        确定
      </button>
    </view> -->
            <view class="btmFix display-flex" style="justify-content: center">
                <button class="dtBtnD mr12" @click.stop="shrink" data-edit="2">取消</button>
                <button type="primary" class="dtBtn ml12" hover-class="button-hover" :loading="loading" formType="submit">确定</button>
            </view>
        </form>
    </view>
</template>

<script>
// pages/newEnroll/index.js
const app = getApp();
var dateTimePicker = require('../../utils/dateTimePicker.js');
var dateUtil = require('../../utils/dateUtil.js');
import { nationArray } from '../../utils/commonUtil';
const mydate = new Date();
export default {
    data() {
        return {
            storeJobInfo: {},

            userInfo: {
                name: '姓名',
                address: '报名老乡地址',
                age: '年龄',
                nationality: '民族',
                sex: '性别',
                num: '-',
                tel: '-',
                idCardImageUrl: ''
            },

            user: app.globalData.user,
            showUpload: true,
            name: '',

            sex: [
                {
                    id: 1,
                    value: '男'
                },
                {
                    id: 2,
                    value: '女'
                }
            ],

            imgSrc: '',
            loading: false,
            idInfo: {},
            index: -1,
            agentArray: [],

            // jobIndex: -1,
            jobArray: [
                // {
                // 	id: 1,
                // 	name: "GG",
                // },
            ],

            storeIndex: -1,

            storeArray: [
                // {
                // 	id: 1,
                // 	name: "GG",
                // },
            ],

            dateTimeArray1: null,
            dateTime1: null,
            startYear: 2022,
            endYear: 2024,
            currentTime: '-',
            currentTime2: '-',
            searchListShow: false,
            searchKeys: '',
            searchKeysA: '',
            inputShowed: false,
            inputVal: '',
            inputShowedA: false,
            inputValA: '',
            storeId: '',
            agentId: '',
            agentName: '',
            storeJobId: '',
            policy: '-',
            currentImg: '',
            nationIndex: -1,

            // 民族的索引
            managerRoleClassify: app.globalData.loginUserInfo.managerRoleClassify,

            // 管理员权限
            nationArray,

            currentUser: {},
            jobName: '-',
            switch1Checked: true,
            type: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        let that = this;
        console.log(app.globalData.user);
        console.log(options);

        // 先统一给代理名字赋予登陆者的名称
        that.setData({
            agentName: app.globalData.user.userName,
            agentId: app.globalData.user.agencyId
        });
        if (app.globalData.isNotEmptyCheck(options.info)) {
            // 如果随路由传过来的信息有更新,赋值新的数据
            console.log(JSON.parse(options.info));
            this.setData({
                storeJobInfo: JSON.parse(options.info),
                storeJobId: JSON.parse(options.info).id,
                jobName: JSON.parse(options.info).jobName,
                inputVal: JSON.parse(options.info).storeName || JSON.parse(options.info).aliasName,
                storeId: JSON.parse(options.info).storeId
            });
            this.getPolicyByStoreJobId(this.storeJobId);
            uni.setStorageSync('storeJobInfo', that.storeJobInfo);
        }
        if (app.globalData.isNotEmptyCheck(options.agencyInfo)) {
            that.setData({
                agentName: JSON.parse(options.agencyInfo).agencyName,
                agentId: JSON.parse(options.agencyInfo).id
            });
        }
        if (app.globalData.isNotEmptyCheck(options.imgUrl)) {
            let imgUrl = JSON.parse(options.imgUrl);
            that.uploadIdcardImg(imgUrl);
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // let src = wx.getStorageSync("src");
        // console.log(src);
    },
    // getAgencyList: function (searchKeys) {
    // 	var that = this;
    // 	that.data.searchKeysA = searchKeys;
    // 	// 60秒后重新获取验证码
    // 	wx.request({
    // 		url: app.globalData.ip + "/agency/getByPmdUserId",
    // 		data: {
    // 			agencyName: searchKeys,
    // 			// pmdUserId: 101125
    // 		},
    // 		header: app.globalData.headers,
    // 		method: "GET",
    // 		success: function (res) {
    // 			console.log(res);
    // 			if (res.data.status == 200) {
    // 				that.setData({
    // 					agentArray: res.data.data,
    // 				});
    // 			}
    // 		},
    // 		fail: function (res) {},
    // 	});
    // },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this;
        console.log(that.managerRoleClassify);
        console.log(app.globalData.loginUserInfo);
        // 获取缓存的报名人信息
        let info = uni.getStorageSync('townsManInfo');
        console.log(info);
        if (app.globalData.isNotEmptyCheck(info)) {
            // 统一给代理岗位相关的字段赋值
            that.setData({
                userInfo: info
            });
            // this.setData({
            // 	userInfo: info,
            // 	currentImg: info.currentImg,
            // 	currentTime: info.currentTime,
            // });
            console.log(info);
            if (info.sex == '1') {
                info.sex = '男';
            } else if (info.sex == '2') {
                info.sex = '女';
            }

            // info.sex = info.sex == '1' ? '男' : '女';
            if (info.nationality.substr(info.nationality.length - 1, 1) != '族' && info.nationality.substr(info.nationality.length - 1, 1) != '') {
                info.nationality = info.nationality + '族';
            }
            that.nationArray.forEach((item, index) => {
                if (item.name.indexOf(info.nationality) > -1 && info.nationality != '') {
                    console.log('isin');
                    that.setData({
                        nationIndex: index
                    });
                }
            });
            console.log(that.nationIndex);
            this.setData({
                userInfo: info,
                sex: this.sex
            });
        }
        let infoJob = uni.getStorageSync('townsManInfoJob');
        console.log(infoJob);
        if (app.globalData.isNotEmptyCheck(infoJob)) {
            // 统一给代理岗位相关的字段赋值
            that.setData({
                storeJobId: infoJob.storeJobId,
                jobName: infoJob.jobName,
                currentImg: infoJob.currentImg,
                currentTime: infoJob.currentTime,
                currentTime2: infoJob.currentTime2
            });
            this.getPolicyByStoreJobId(that.storeJobId);
        }

        //
        // let info = wx.getStorageSync("townsManInfo");
        // if (app.isNotEmptyCheck(info)) {
        // 	this.setData({
        // 		userInfo: info,
        // 		currentImg: info.currentImg,
        // 		currentTime: info.currentTime,
        // 	});
        // 	console.log(info);
        // 	if (info.sex == "男") {
        // 		this.data.sex[0].checked = true;
        // 	} else if (info.sex == "女") {
        // 		this.data.sex[1].checked = true;
        // 	}
        // 	that.data.nationArray.forEach((item, index) => {
        // 		if (item.name.indexOf(info.nationality) > -1 && info.nationality != "") {
        // 			console.log("isin");
        // 			that.setData({
        // 				nationIndex: index,
        // 			});
        // 		}
        // 	});
        // 	console.log(that.data.nationIndex);
        // 	this.setData({
        // 		sex: this.data.sex,
        // 	});
        // }
        // this.pickerTap();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function (e) {
        console.log('isHide');
        console.log(e);
        // this.setData({
        // 	userInfo: {
        // 		name: "",
        // 		address: "",
        // 		age: "",
        // 		nationality: "",
        // 		sex: "",
        // 		num: "",
        // 		idCardImageUrl: "",
        // 	},
        // });
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // wx.removeStorageSync("townsManInfo");
        // wx.switchTab({
        // 	url: "../firstBill/index",
        // });
        // console.log(wx.getStorageSync("townsManInfo"));
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    methods: {
        shrink: function () {
            uni.navigateBack({
                delta: -1
            });
        },

        radioChange: function (e) {
            const sex = this.sex;
            let currentSex = '';
            for (let i = 0, len = sex.length; i < len; ++i) {
                sex[i].checked = sex[i].id == e.detail.value;
                if (sex[i].checked) {
                    currentSex = sex[i].value;
                }
            }
            this.setData({
                ['userInfo.sex']: currentSex,
                sex
            });
            console.log(e.detail.value);
        },

        chooseIdCard() {
            var that = this;
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    console.log(res);
                    that.uploadIdcardImg(res);
                }
            });
        },

        uploadIdcardImg(imgPath) {
            let that = this;
            // tempFilePath可以作为img标签的src属性显示图片
            console.log(imgPath.tempFilePaths[0]);
            const tempFilePaths = imgPath.tempFilePaths;
            uni.showLoading({
                title: '识别中...'
            });
            uni.uploadFile({
                // url: app.globalData.ip + '/commons/idCardOcrRecognize',
                url: app.globalData.ip + '/commons/idCardOcrRecognizeAndUploadToAliyunOss',
                filePath: imgPath.tempFilePaths[0],
                name: 'uploadFile',
                header: app.globalData.headers,
                success: function (res) {
                    console.log(JSON.parse(res.data));
                    var idcard = JSON.parse(res.data);
                    idcard.data.tel = '';
                    idcard.data.nationality = idcard.data.nationality;
                    if (idcard.status == 200) {
                        that.setData({
                            userInfo: idcard.data,
                            showUpload: false,
                            currentImg: imgPath.tempFilePaths[0]
                        });
                        that.setStorage();
                        console.log(that.userInfo);
                        that.nationArray.forEach((item, index) => {
                            if (item.name.includes(that.userInfo.nationality)) {
                                that.setData({
                                    nationIndex: index
                                });
                            }
                        });
                        if (
                            that.userInfo.nationality.substr(that.userInfo.nationality.length - 1, 1) != '族' &&
                            that.userInfo.nationality.substr(that.userInfo.nationality.length - 1, 1) != ''
                        ) {
                            that.userInfo.nationality = that.userInfo.nationality + '族';
                        }
                        if (that.userInfo.sex == '男') {
                            that.sex[0].checked = true;
                        } else {
                            that.sex[1].checked = true;
                        }
                        that.setData({
                            userInfo: that.userInfo,
                            sex: that.sex,
                            imgSrc: tempFilePaths[0]
                        });
                    } else {
                        uni.showToast({
                            duration: 2000,
                            title: '身份证未识别',
                            icon: 'none',
                            mask: true
                        });
                        // console.log(1);
                        //app.showTips(that, res.data.msg);
                    }
                    uni.hideLoading();
                },
                fail: function (res) {
                    console.log(res);
                }
            });
        },

        toJobAndAgencySelect(e) {
            console.log(e);
            console.log(this.userInfo);
            this.setStorage().then(() => {
                console.log('--------', 'isIntonavigation');
                uni.navigateTo({
                    url: `../recordChoice/index?type=${e.currentTarget.dataset.type}`
                });
            });
        },

        showImg() {
            uni.previewImage({
                current: this.currentImg,
                // 当前显示图片的 http 链接
                urls: [this.currentImg] // 需要预览的图片 http 链接列表
            });
        },

        deleteImg() {
            var that = this;
            uni.showModal({
                title: '提示',
                content: '确定要删除图片吗？',
                confirmColor: '#ff4400',
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            imgSrc: '',
                            showUpload: true
                        });
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        },

        bothwayBind(e) {
            console.log(e);
            let type = `userInfo.${e.currentTarget.dataset.type}`;
            this.setData({
                [type]: e.detail.value
            });
        },

        beforeFormSubmit: function (e) {
            var that = this;
            console.log(e);
            that.setData({
                loading: true
            });
            if (!that.switch1Checked) {
                uni.showToast({
                    title: '请先阅读并同意《服务协议》及《隐私政策》',
                    icon: 'none',
                    duration: 2000
                });
            } else if (app.globalData.isEmptyCheck(uni.getStorageSync('townsManInfo'))) {
                uni.showToast({
                    duration: 2000,
                    title: '请补全个人信息',
                    icon: 'none',
                    mask: true
                });
                that.setData({
                    loading: false
                });
            } else if (app.globalData.isEmptyCheck(uni.getStorageSync('townsManInfoJob'))) {
                uni.showToast({
                    duration: 2000,
                    title: '请补全岗位信息',
                    icon: 'none',
                    mask: true
                });
                that.setData({
                    loading: false
                });
            } else {
                setTimeout(() => {
                    that.formSubmit(e);
                }, 1);
                e.detail.value['idCardImageUrl'] = that.userInfo.idCardImageUrl;
            }
        },

        clear() {
            uni.removeStorageSync('townsManInfo');
        },

        setStorage() {
            let that = this;
            uni.removeStorageSync('townsManInfo');
            return new Promise((resolve, reject) => {
                console.log(that.storeJobId);
                let data = {
                    ...that.userInfo,
                    currentImg: that.currentImg
                };
                console.log(data);
                uni.setStorage({
                    key: 'townsManInfo',
                    data
                });
                console.log(uni.getStorageSync('townsManInfo'));
                resolve();
            });
        },

        formSubmit: function (e) {
            var that = this;
            console.log(e);
            console.log(uni.getStorageSync('townsManInfo'));
            console.log(uni.getStorageSync('townsManInfoJob'));
            console.log(that.agentName + '+===+' + that.agentId);
            that.setData({
                loading: true
            });
            // return
            uni.showLoading({
                title: '提交中...',
                mask: true
            });
            let userInfo = uni.getStorageSync('townsManInfo');
            let jobInfo = uni.getStorageSync('townsManInfoJob');
            console.log(that.idInfo);
            new Promise(function (resolve, reject) {
                var paramData = {};
                paramData['userName'] = userInfo.name;
                if (userInfo.sex == '1' || userInfo.sex == '男') {
                    paramData['sex'] = 1;
                } else {
                    paramData['sex'] = 2;
                }
                paramData['age'] = userInfo.age;
                paramData['nation'] = userInfo.nationality;
                paramData['idCard'] = userInfo.num;
                if (app.globalData.isNotEmptyCheck(userInfo.imgs)) {
                    paramData['imgs'] = userInfo.imgs.toString();
                }
                paramData['tel'] = userInfo.tel;
                paramData['idCardImageUrl'] = userInfo.idCardImageUrl;
                paramData['address'] = userInfo.address;
                paramData['agencyId'] = that.agentId;
                paramData['storeJobId'] = jobInfo.storeJobId;
                paramData['policy'] = jobInfo.policy;
                paramData['interviewTime'] = jobInfo.currentTime;
                paramData['receptionTime'] = jobInfo.currentTime2;
                resolve(paramData);
            }).then(function (paramData) {
                console.log(paramData);
                uni.request({
                    url: app.globalData.ip + '/user/apply/order/addByAgency',
                    header: app.globalData.headers,
                    data: paramData,
                    method: 'POST',
                    success: function (res) {
                        uni.removeStorageSync('townsManInfo');
                        uni.removeStorageSync('townsManInfoJob');
                        console.log(res);
                        if (res.data.status == 200) {
                            uni.hideLoading();
                            uni.switchTab({
                                url: '/pages/workBench/index'
                            });
                            uni.showToast({
                                duration: 2000,
                                title: '报名成功',
                                icon: 'success',
                                mask: true
                            });
                        }
                    }
                });
            });
            // }
        },

        inputTyping: function (e) {
            this.setData({
                inputVal: e.detail.value
            });
            if (e.detail.value.length > 0) {
                this.setData({
                    searchListShow: true
                });
                this.getStoreList(e.detail.value);
            } else {
                this.setData({
                    searchListShow: false
                });
            }
        },

        getPolicyByStoreJobId: function (storeJobId) {
            var that = this;
            // 60秒后重新获取验证码
            uni.request({
                url: app.globalData.ip + '/store/job/getPolicyByStoreJobId',
                data: {
                    storeJobId: storeJobId
                },
                header: app.globalData.headers,
                method: 'GET',
                success: function (res) {
                    console.log(res);
                    if (res.data.status == 200) {
                        that.setData({
                            policy: res.data.data
                        });
                    }
                },
                fail: function (res) {
                    console.log(res);
                }
            });
        },

        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: function () {}
    }
};
</script>
<style>
@import './index.css';
</style>
