<template>
	<view class="apply-pages" v-if="isLoad">
		<view class="apply-form">
			<view class="fill-base radius-16">
				<view @tap.stop="toChooseUser" class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text">关联用户</view>
					<view class="item-input text">
						<view class="flex-between">
							{{form.user_id ? form.nickName :'请选择'}}
							<i class="iconfont icon-right ml-sm" style="font-size: 28rpx;"></i>
						</view>
					</view>
				</view>
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>姓名</view>
					<input v-model="form.coach_name" type="text" class="item-input flex-1" maxlength="20"
						:placeholder="rule[0].errorMsg" />
				</view>
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>性别</view>
					<view class="item-input flex-1 flex-y-center">
						<view @tap.stop="form.sex = index" class="flex-y-center" :class="[{'mr-lg':index==0}]"
							:style="{color:form.sex == index ? primaryColor:''}" v-for="(item,index) in ['男','女']"
							:key="index"><i class="iconfont icon-xuanze mr-sm"
								:class="[{'icon-xuanze-fill':form.sex == index}]"></i>{{item}}
						</view>
					</view>
				</view>
				<view class="flex-between ml-lg mr-lg b-1px-b">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>生日</view>
					<view class="item-input text flex-1">
						<picker @change="pickerChange($event,'birthday')" mode="date" :end="endYear"
							:value="form.birthday">
							<view class="flex-between">
								{{form.birthday||'请选择'}}
								<i class="iconfont icon-right ml-sm" style="font-size: 28rpx;"></i>
							</view>
						</picker>
					</view>
				</view>
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>手机号</view>
					<input v-model="form.mobile" type="text" class="item-input flex-1"
						:placeholder="rule[2].errorMsg" />
				</view>
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>从业年份</view>
					<input v-model="form.work_time" type="number" class="item-input flex-1"
						:placeholder="rule[3].errorMsg" />
				</view>
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text flex-y-center" style="width:230rpx"><i
							class="iconfont icon-required c-warning"></i>意向工作城市</view>
					<view class="item-input text">
						<picker @change="pickerChange($event,'city')" :value="cityIndex" :range="cityList"
							range-key="title">
							<view class="flex-between">
								{{cityIndex!=-1?cityList[cityIndex].title:'请选择'}}
								<i class="iconfont icon-right ml-sm" style="font-size: 28rpx;"></i>
							</view>
						</picker>
					</view>
				</view>
				<view class="flex-between pl-lg pr-lg b-1px-b" v-if="configInfo.plugAuth.store && storeList.length>0">
					<view class="item-text">挂靠门店</view>
					<view class="item-input text">
						<picker @change="pickerChange($event,'store')" :value="storeIndex" :range="storeList"
							range-key="title">
							<view class="flex-between">
								<view class="max-400 ellipsis">{{storeIndex!=-1?storeList[storeIndex].title:'请选择'}}
								</view>
								<i class="iconfont icon-right ml-sm" style="font-size: 28rpx;"></i>
							</view>
						</picker>
					</view>
				</view>
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>所在地址</view>
					<view class="item-input text flex-1">
						<view @tap.stop="toChooseLocation" class="flex-between">
							<view>{{form.address || `点击右边图标设置`}}</view>
							<i class="iconfont iconjuli ml-sm" :style="{color: primaryColor}"></i>
						</view>
					</view>
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text flex-y-center" style="width:auto"><i
							class="iconfont icon-required c-warning"></i>{{$t('action.attendantName')}}简介</view>
					<input :disabled="true" type="text" class="item-input flex-1" />
				</view>
				<textarea v-model="form.text" class="item-textarea pd-lg" maxlength="300"
					:placeholder="'输入'+$t('action.attendantName')+'简介'" />
				<view class="text-right pb-lg pr-lg">
					{{form.text.length>300?300:form.text.length}}/300
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>身份证号</view>
					<input v-model="form.id_code" type="text" class="item-input flex-1"
						:placeholder="rule[7].errorMsg" />
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>身份证照片</view>
					<view class="item-input flex-1">图片大小不超过10M</view>
				</view>
				<view class="flex-between pl-lg pr-lg pb-md">
					<upload @upload="imgUpload" :imagelist="form.id_card" imgtype="id_card" imgclass="md" text="身份证人像面"
						:imgsize="1"></upload>
					<upload @upload="imgUpload" :imagelist="form.id_card_fan" imgtype="id_card_fan" imgclass="md"
						text="身份证国徽面" :imgsize="1"></upload>
				</view>
				<view class="flex-between pl-lg pr-lg pb-md">
					<upload @upload="imgUpload" :imagelist="form.id_card_people" imgtype="id_card_people" imgclass="md"
						text="手持身份证照片" :imgsize="1"></upload>
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>资格证书</view>
					<view class="item-input flex-1">图片大小不超过10M</view>
				</view>
				<view class="flex-between pl-lg pr-lg pb-md">
					<upload @upload="imgUpload" @del="imgUpload" :imagelist="form.license" imgtype="license" text="上传图片"
						:imgsize="15">
					</upload>
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>工作形象照</view>
					<view class="item-input flex-1">图片建议尺寸: 750 * 750，大小不超过10M</view>
				</view>
				<view class="flex-between pl-lg pr-lg pb-md">
					<upload @upload="imgUpload" :imagelist="form.work_img" imgtype="work_img" text="上传图片" :imgsize="1">
					</upload>
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>个人生活照</view>
					<view class="item-input flex-1">图片建议尺寸: 750 * n，大小不超过10M</view>
				</view>
				<view class="flex-between pl-lg pr-lg pb-md">
					<upload @upload="imgUpload" @del="imgUpload" :imagelist="form.self_img" filetype="picture"
						imgtype="self_img" text="上传图片" :imgsize="9">
					</upload>
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg">
					<view class="item-text">个人视频介绍</view>
					<view class="item-input flex-1">视频大小不超过50M</view>
				</view>
				<view class="flex-between pl-lg pr-lg pb-md">
					<upload @upload="imgUpload" @del="imgUpload" :imagelist="form.video" filetype="video"
						imgtype="video" text="上传视频" :imgsize="1">
					</upload>
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>虚拟订单</view>
					<input v-model="form.order_num" type="number" class="item-input flex-1"
						:placeholder="rule[14].errorMsg" />
				</view>
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text flex-y-center"><i class="iconfont icon-required c-warning"></i>是否接单</view>
					<view class="item-input flex-1 flex-y-center">
						<view @tap.stop="toSetItem(index)" class="flex-y-center" :class="[{'mr-lg':item.id==1}]"
							:style="{color:form.is_work == item.id ? primaryColor:''}" v-for="(item,index) in workList"
							:key="index"><i class="iconfont mr-sm"
								:class="[{'icon-xuanze':form.is_work != item.id},{'icon-radio-fill':form.is_work == item.id}]"></i>{{item.title}}
						</view>
					</view>
				</view>
				<view class="flex-between pd-lg" v-if="form.is_work===1">
					<view @tap.stop="toShowTime('start_time')" class="item-time flex-center flex-column">
						<view>开始时间</view>
						<view class="mt-sm" :style="{color:form.start_time ? primaryColor : '#999'}">
							{{form.start_time || '选择时间'}}
						</view>
					</view>
					<view @tap.stop="toShowTime('end_time')" class="item-time flex-center flex-column  b-1px-l">
						<view>结束时间</view>
						<view class="mt-sm" :style="{color:form.end_time ? primaryColor : '#999'}">
							{{form | handleStartEndTime(toDay)}}{{form.end_time || '选择时间'}}
						</view>
					</view>
				</view>
			</view>
			
			
			<!-- TODO 合同 -->
			<view @tap.stop="toFddSign" class="fill-base mt-md radius-16"
				v-if="fdd_agreement && fdd_agreement.hasOwnProperty('viewpdf_url')">
				<view class="flex-between pl-lg pr-lg b-1px-b">
					<view class="item-text">电子签约</view>
					<view class="item-input flex-1" :style="{color:primaryColor}">
						查看签约合同
					</view>
				</view>
			</view>
		</view>

		<view class="space-max-footer"></view>

		<fix-bottom-button @confirm="submit" :text="[{text:'确定提交',type:'confirm',isAuth:true}]" bgColor="#fff">
		</fix-bottom-button>


		<w-picker :visible.sync="showTime" mode="time" :value="toDayTime" :current="false" :second="false"
			:themeColor="primaryColor" @confirm="onConfirm" ref="time"></w-picker>
	</view>
</template>

<script>
	import $util from "@/utils/index.js"
	import wPicker from "@/components/w-picker/w-picker.vue";
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		components: {
			wPicker
		},
		data() {
			return {
				isLoad: false,
				options: {},
				cityList: [],
				cityIndex: -1,
				storeList: [],
				storeIndex: -1,
				toDay: '',
				toDayTime: '',
				showKey: '',
				showTime: false,
				workList: [{
					id: 1,
					title: '接单'
				}, {
					id: 0,
					title: '休息'
				}],
				fdd_agreement: {},
				form: {
					id: 0,
					user_id: '',
					nickName: '',
					coach_name: '', //姓名 
					mobile: '', //手机号 
					sex: 0, //性别 
					birthday: '',
					work_time: '', //从业年份 
					city_id: '', // 城市id
					store_id: '', // 门店id
					lng: '',
					lat: '',
					address: '', //详细地址 
					text: '', //备注 
					id_code: '', //身份证号
					id_card: [], //身份证
					id_card_fan: [], // 身份证反面
					id_card_people: [], //手持身份证
					license: [], //资格证书
					work_img: [], // 工作照
					self_img: [], // 生活照
					city_id: '', // 城市 id
					video: [],
					order_num: 0,
					is_work: 1,
					start_time: '00:00',
					end_time: '23:59'
				},
				rule: [{
						name: "coach_name",
						checkType: "isNotNull",
						errorMsg: "输入您的姓名",
						regType: 2
					}, {
						name: "birthday",
						checkType: "isNotNull",
						errorMsg: "请选择您的生日",
						regType: 2
					},
					{
						name: "mobile",
						checkType: "isMobile",
						errorMsg: "输入手机号"
					}, {
						name: "work_time",
						checkType: "isNotNull",
						errorMsg: "请输入从业年份，例如：5"
					}, {
						name: "city_id",
						checkType: "isNotNull",
						errorMsg: "请选择意向工作城市"
					},
					{
						name: "address",
						checkType: "isNotNull",
						errorMsg: "请选择所在地址"
					}, {
						name: "text",
						checkType: "isNotNull",
						errorMsg: "请输入" + this.$t('action.attendantName') + "简介",
						regType: 2
					}, {
						name: "id_code",
						checkType: "isIdCard",
						errorMsg: "输入您的身份证号码"
					},
					{
						name: "id_card",
						checkType: "isNotNull",
						errorMsg: "请上传身份证人像面"
					},
					{
						name: "id_card_fan",
						checkType: "isNotNull",
						errorMsg: "请上传身份证国徽面"
					},
					{
						name: "id_card_people",
						checkType: "isNotNull",
						errorMsg: "请上传手持身份证照片"
					},
					{
						name: "license",
						checkType: "isNotNull",
						errorMsg: "请上传资格证书"
					},
					{
						name: "work_img",
						checkType: "isNotNull",
						errorMsg: "请上传工作形象照"
					},
					{
						name: "self_img",
						checkType: "isNotNull",
						errorMsg: "请上传个人生活照"
					},
					{
						name: "order_num",
						checkType: "isNumber",
						errorMsg: "请输入虚拟订单量",
						regType: 2
					},
				],
				have_user_id: false,
				lockTap: false
			}
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			userInfo: state => state.user.userInfo,
			location: state => state.user.location,
		}),
		async onLoad(options) {
			let {
				id = 0
			} = options
			this.options = options
			this.$util.showLoading()
			await this.initIndex()
			let {
				coach_status
			} = this
			
			uni.setNavigationBarTitle({
				title: id ? '编辑' : '新增' + this.$t(
					'action.attendantName')
			})
			this.isLoad = true
		},
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo']),
			...mapMutations(['updateUserItem']),
			async initIndex(refresh = false) {
				// #ifdef H5
				if (!refresh && this.$jweixin.isWechat()) {
					await this.$jweixin.initJssdk();
					this.$jweixin.wxReady(() => {
						this.$jweixin.hideOptionMenu()
					})
				}
				// #endif
				if (!this.configInfo.id || !this.configInfo.hasOwnProperty(
						'plugAuth') || (this.configInfo.hasOwnProperty(
						'plugAuth') && !this.configInfo.plugAuth.hasOwnProperty(
						'store')) || refresh) {
					await this.getConfigInfo()
				}
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				let cur_time = new Date(Math.ceil(new Date().getTime()))
				this.toDay = this.$util.formatTime(cur_time, 'YY-M-D')
				this.toDayTime = this.$util.formatTime(cur_time, 'h:m')
				await Promise.all([this.getCityList(), this.getStoreList()])
				let {
					id = 0
				} = this.options
				if (!id) {
					this.$util.hideAll()
					return
				}

				let data = await this.$api.agent.coachInfo({
					id
				})
				data.id_card = data.id_card.map(item => {
					return {
						path: item
					}
				})
				data.id_card_fan = [data.id_card[1]]
				data.id_card_people = [data.id_card[2]]
				data.id_card.splice(1, 3)
				data.license = data.license.map(item => {
					return {
						path: item
					}
				})
				data.work_img = [{
					path: data.work_img
				}]
				data.self_img = data.self_img.map(item => {
					return {
						path: item
					}
				})
				data.video = data.video && data.video.length > 0 ? [{
					path: data.video
				}] : []
				this.cityIndex = this.cityList.findIndex(item => {
					return item.id == data.city_id
				})
				this.storeIndex = this.storeList.findIndex(item => {
					return item.id == data.store_id
				})
				data.birthday = data.birthday ? this.$util.formatTime(data.birthday * 1000, 'YY-M-D') : ''
				for (let key in this.form) {
					this.form[key] = data[key]
				}
				this.have_user_id = data.id && data.user_id
				this.fdd_agreement = data.fdd_agreement
				this.$util.hideAll()
			},
			initRefresh() {
				this.initIndex(true)
			},
			async getStoreList() {
				let {
					store = false
				} = this.configInfo.plugAuth
				if (store) {
					let data = await this.$api.agent.storeSelect()
					data.unshift({
						id: 0,
						title: '不挂靠门店'
					})
					this.storeList = data
				}
			},
			async getCityList() {
				let {
					location
				} = this
				if (!location.lat) {
					// #ifdef H5
					if (this.$jweixin.isWechat()) {
						this.$util.showLoading()
						// await this.$jweixin.initJssdk();
						await this.$jweixin.wxReady2();
						let {
							latitude: lat = 0,
							longitude: lng = 0
						} = await this.$jweixin.getWxLocation()
						location = {
							lng,
							lat,
							address: '定位失败',
							province: '',
							city: '',
							district: ''
						}
						if (lat && lng) {
							let key = `${lat},${lng}`
							let data = await this.$api.base.getMapInfo({
								location: key
							})
							let {
								status,
								result
							} = JSON.parse(data)
							if (status == 0) {
								let {
									address,
									address_component
								} = result
								let {
									province,
									city,
									district
								} = address_component
								location = {
									lng,
									lat,
									address,
									province,
									city,
									district
								}
							}
						}
					}
					// #endif
					// #ifndef H5
					location = await this.$util.getBmapLocation()
					// #endif

					this.updateUserItem({
						key: 'location',
						val: location
					})
				}

				let {
					lng = 0,
						lat = 0
				} = location
				if (lat && lng) {
					let city = await this.$api.base.getCity({
						lng,
						lat
					})
					this.$util.hideAll()
					this.cityList = city
					this.cityIndex = city.length > 0 ? 0 : -1
					this.form.city_id = city.length > 0 ? city[0].id : ''
				}
			},
			async toFddSign() {
				this.updateUserItem({
					key: 'fddExtsign',
					val: ''
				})
				let {
					viewpdf_url = ''
				} = this.fdd_agreement
				this.updateUserItem({
					key: 'fddExtsign',
					val: viewpdf_url
				})
				this.$util.goUrl({
					url: `/user/pages/common/web?url=fddExtsign`
				})
			},
			pickerChange(e, key) {
				let ind = e.target.value
				if (key === 'birthday') {
					let unix = this.$util.DateToUnix(ind)
					if (unix > new Date(Math.ceil(new Date().getTime())) / 1000) {
						this.$util.showToast({
							title: `不能选择未来时间哦`
						})
						return
					}
					this.form[key] = ind
					return
				}
				this[`${key}Index`] = ind
				this.form[`${key}_id`] = this[`${key}List`][ind].id
			},
			imgUpload(e) {
				let {
					imagelist,
					imgtype
				} = e;
				this.form[imgtype] = imagelist;
			},
			toSetItem(index) {
				let {
					id
				} = this.workList[index]
				this.form.is_work = id
			},
			toShowTime(key) {
				this.showKey = key
				this.showTime = true
			},
			onConfirm(val) {
				this.form[this.showKey] = val.result;
			},
			// 选择地区
			async toChooseLocation(e) {
				await this.$util.checkAuth({
					type: 'userLocation'
				})
				let {
					lat: locaLat = '',
					lng: locaLng = ''
				} = this.location
				let {
					id = 0,
						lat: addrLat,
						lng: addrLng
				} = this.form

				if (id) {
					locaLat = addrLat
					locaLng = addrLng
				}

				let param = {}
				if (!locaLat && !locaLng) {
					// #ifdef H5
					if (this.$jweixin.isWechat()) {
						this.$util.showLoading()
						await this.$jweixin.wxReady2();
						let {
							latitude,
							longitude
						} = await this.$jweixin.getWxLocation()
						locaLat = latitude
						locaLng = longitude
					}
					// #endif
					// #ifdef APP-PLUS
					let location = await this.$util.getBmapLocation()
					locaLat = location.lat
					locaLng = location.lng
					// #endif
				}

				// #ifndef MP-WEIXIN
				param = {
					latitude: locaLat,
					longitude: locaLng
				}
				// #endif
				let [, {
					address = '',
					longitude,
					latitude
				}] = await uni.chooseLocation(param);
				if (!address) return
				this.form.address = address
				this.form.lng = longitude
				this.form.lat = latitude
			},
			toChooseUser() {
				let {
					have_user_id
				} = this
				if (have_user_id) return
				this.$util.goUrl({
					url: `/agent/pages/technician/user`
				})
			},
			//表单验证
			validate(param) {
				let validate = new this.$util.Validate();
				this.rule.map(item => {
					let {
						name,
					} = item
					validate.add(param[name], item);
				})
				let message = validate.start();
				return message;
			},
			async submit() {
				let param = this.$util.deepCopy(this.form)
				let arr = ['id_card', 'id_card_fan', 'id_card_people', 'work_img', 'video']
				arr.map(item => {
					param[item] = param[item].length > 0 ? param[item][0].path : ''
				})
				param.license = param.license.map(item => {
					return item.path
				})
				param.self_img = param.self_img.map(item => {
					return item.path
				})
				let msg = this.validate(param);
				if (msg) {
					this.$util.showToast({
						title: msg
					});
					return;
				}

				let {
					is_work: work = 0,
					start_time: start,
					end_time: end
				} = param
				if (work && (!start || !end)) {
					this.$util.showToast({
						title: !start ? '请选择开始时间' : '请选择结束时间'
					})
					return
				}

				param.birthday = this.$util.DateToUnix(param.birthday)
				param.id_card = [param.id_card, param.id_card_fan, param.id_card_people]
				delete param.id_card_fan
				delete param.id_card_people
				delete param.nickName
				if (param.id) {
					delete param.admin_id
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					let {
						is_edit = 0
					} = this.options
					let methodModel = param.id ? 'coachDataUpdate' : 'coachApply'
					await this.$api.agent[methodModel](param)
					this.$util.hideAll()
					this.$util.showToast({
						title: `提交成功`
					})
					setTimeout(() => {
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 2000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}

			}
		},
		filters: {
			handleStartEndTime(val, toDay) {
				let text = ''
				let {
					start_time,
					end_time
				} = val
				let start = `${toDay} ${start_time}`
				let end = `${toDay} ${end_time}`
				if (start_time && end_time && $util.DateToUnix(start) >= $util.DateToUnix(end)) {
					text = '次日'
				}
				return text
			}
		}
	}
</script>


<style lang="scss">
	.item-time {
		width: 50%;
	}
</style>