<template>
	<view>
		<!-- 顶部操作条 -->
		<cu-custom :bgColor="'bg-main-color'" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">师傅入驻信息填写</block>
		</cu-custom>
		<!-- 步骤条 -->
		<view class="bg-white padding">
			<view class="cu-steps">
				<view class="cu-item" :class="index>curStep?'':'text-main-color'" v-for="(stepName, index) in stepList">
					<text class='cuIcon-radioboxfill'></text> {{stepName}}
				</view>
			</view>
		</view>
		<!-- 服务区域 -->
		<view v-if="curStep === 0">
			<view class="margin-bottom-with-bar">
				<view class="bg-white margin-top-sm" v-for="(item, index) in servArea">
					<view class="cu-bar padding-lr solid-bottom">
						<view class="text-lg">
							<text class="cuIcon-titles"></text>
							<text>服务区域{{index + 1}}(将按服务范围派单)</text>
						</view>
						<view @click="delServArea(index)">
							<text class="text-main-color">删除</text>
						</view>
					</view>
					<view class="padding">
						<view class="flex">
							<my-uni-combox class="flex-sub margin-right-xs" :candidates="provinceList"
								:showField="'areaName'" placeholder="选择省份" v-model="servArea[index].provinceObj"
								@input="chooseRegion($event, 0, index)"></my-uni-combox>
							<my-uni-combox class="flex-sub margin-right-xs" :candidates="servArea[index].cityList"
								:showField="'areaName'" placeholder="选择城市" v-model="servArea[index].cityObj"
								@input="chooseRegion($event, 1, index)" @tap="reloadTargetArea(1, index)"></my-uni-combox>
							<my-uni-combox class="flex-sub" :candidates="servArea[index].districtList"
								:showField="'areaName'" placeholder="选择地区" v-model="servArea[index].districtObj"
								@input="chooseRegion($event, 2, index)" @tap="reloadTargetArea(2, index)"></my-uni-combox>
						</view>
						<checkbox-group @change="checkStreet($event, index)" class="grid col-2 margin-top-xs">
							<view v-for="(item0, index0) in servArea[index].streetList" class="margin-tb-xs">
								<checkbox style="transform:scale(1)" class="main-color margin-right-xs"
									:value="item0.areaCode"
									:checked="servArea[index].streetIds.indexOf(String(item0.areaCode)) !== -1 ? true : false">
								</checkbox>
								<text>{{item0.areaName}}</text>
							</view>
						</checkbox-group>
					</view>
				</view>
				<view class="text-center margin-top">
					<button class="cu-btn bg-main-color light" @click="addServArea">
						<text class="margin-right-xs"><text class="cuIcon-add"></text></text>
						<text>继续添加服务区域</text>
					</button>
				</view>
			</view>
			<view class="bottom-site-bar"></view>
			<!-- 下一步 -->
			<view class="cu-bar tabbar border shop fixed-bottom-bar bg-back">
				<button class="margin-lr cu-btn bg-main-color shadow-blur long-btn" @click="nextStep">下一步</button>
			</view>
		</view>
		<!-- 服务技能 -->
		<view v-if="curStep === 1">
			<view class="margin-bottom-with-bar">
				<view class="bg-white margin-top-sm" v-for="(item, index) in servSkill">
					<view class="cu-bar padding-lr solid-bottom">
						<view class="text-lg">
							<text class="cuIcon-titles"></text>
							<text>服务技能{{index + 1}}(将按服务技能派单)</text>
						</view>
						<view @click="delServSkill(index)">
							<text class="text-main-color">删除</text>
						</view>
					</view>
					<view class="padding">
						<view class="flex">
							<my-uni-combox class="flex-sub margin-right-xs" :candidates="typeList"
								:showField="'goodsCategoryName'" placeholder="请选择" v-model="servSkill[index].typeObj"
								@input="chooseType($event, 0, index)"></my-uni-combox>
							<my-uni-combox class="flex-sub" :candidates="servSkill[index].subTypeList"
								:showField="'goodsCategoryName'" placeholder="请选择" v-model="servSkill[index].subTypeObj"
								@input="chooseType($event, 1, index)" @tap="reloadTargetCategory(1, index)"></my-uni-combox>
						</view>
						<checkbox-group @change="checkGoodType($event, index)" class="grid col-3 margin-top-xs">
							<view v-for="(item0, index0) in servSkill[index].subSubTypeList" class="margin-tb-xs">
								<checkbox style="transform:scale(1)" class="main-color margin-right-xs"
									:value="item0.goodsCategoryId"
									:checked="servSkill[index].subSubTypeIds.indexOf(String(item0.goodsCategoryId)) !== -1 ? true : false">
								</checkbox>
								<text>{{item0.goodsCategoryName}}</text>
							</view>
						</checkbox-group>
						<!-- <view>
							<input type="text" class="radius-input" placeholder="输入其他服务，用“，”隔开。"
								v-model="servSkill[index].otherServSkill">
						</view> -->
					</view>
				</view>
				<view class="text-center margin-top">
					<button class="cu-btn bg-main-color light" @click="addServSkill">
						<text class="margin-right-xs"><text class="cuIcon-add"></text></text>
						<text>继续添加服务技能</text>
					</button>
				</view>
			</view>
			<view class="bottom-site-bar"></view>
			<!-- 下一步 -->
			<view class="cu-bar tabbar border shop fixed-bottom-bar bg-back">
				<button class="margin-lr-sm cu-btn bg-white shadow-blur long-btn" @click="preStep">上一步</button>
				<!-- <button class="bg-main-color long-btn margin-lr" @click="nextStep">下一步</button> -->
				<button class="margin-lr-sm cu-btn bg-main-color shadow-blur long-btn" @click="submit">提交</button>
			</view>
		</view>
		<view v-if="false" class="margin-top-sm">
			<view class="margin-bottom-with-bar">
				<view class="bg-white margin-top-sm" v-for="(item, index) in specialSkill">
					<view class="cu-bar padding-lr solid-bottom">
						<view class="text-lg">
							<text class="cuIcon-titles"></text>
							<text>特殊技能{{index + 1}}(特殊工种如空调安装等请上传)</text>
						</view>
						<view @click="delSpecialSkill(index)">
							<text class="text-main-color">删除</text>
						</view>
					</view>
					<view class="padding">
						<view>
							<text>特殊技能：</text>
							<view>
								<view class="flex align-center margin-bottom-xs">
									<my-uni-combox class="flex-sub margin-right-xs" :candidates="specialTypeList"
										:showField="'goodsCategoryName'" placeholder="请选择"
										v-model="specialSkill[index].specialTypeObj" @input="chooseSpecialSkill($event, 0, index)">
									</my-uni-combox>
									<my-uni-combox class="flex-sub margin-right-xs"
										:candidates="specialSkill[index].specialSubTypeList" :showField="'goodsCategoryName'"
										placeholder="请选择" v-model="specialSkill[index].specialSubTypeObj"
										@input="chooseSpecialSkill($event, 1, index)"></my-uni-combox>
									<my-uni-combox class="flex-sub" :candidates="specialSkill[index].specialSubSubTypeList"
										:showField="'goodsCategoryName'" placeholder="请选择"
										v-model="specialSkill[index].specialSubSubTypeObj"
										@input="chooseSpecialSkill($event, 2, index)"></my-uni-combox>
								</view>
								<my-uni-combox :candidates="specialSkill[index].specialSkillList"
									:showField="'specialSkillName'" placeholder="请选择"
									v-model="specialSkill[index].specialSkillObj"
									@input="chooseSpecialSkill($event, 3, index)"></my-uni-combox>
							</view>
						</view>
						<view class="flex justify-start align-center margin-top-sm">
							<view>技能证书：</view>
							<view class="grid col-1 upload-pic-grid grid-square flex-sub">
								<view class="bg-img" v-for="(url, index0) in specialSkill[index].skillCert" :key="index0"
									@tap="viewImage($event, specialSkill[index].skillCert)" :data-url="url">
									<image :src="url" mode="aspectFill"></image>
									<view class="cu-tag bg-red" @tap.stop="delImg($event, specialSkill[index].skillCert)" :data-index="index0">
										<text class='cuIcon-close'></text>
									</view>
								</view>
								<view class="solids" @tap="chooseImage($event, specialSkill[index].skillCert)" v-if="specialSkill[index].skillCert.length < 1">
									<text class='cuIcon-cameraadd'></text>
								</view>
							</view>
						</view>
						<view class="flex justify-start align-center margin-top-sm">
							<view>保险证明：</view>
							<view class="grid col-1 upload-pic-grid grid-square flex-sub">
								<view class="bg-img" v-for="(url, index0) in specialSkill[index].insurCert" :key="index0"
									@tap="viewImage($event, specialSkill[index].insurCert)" :data-url="url">
									<image :src="url" mode="aspectFill"></image>
									<view class="cu-tag bg-red" @tap.stop="delImg($event, specialSkill[index].insurCert)" :data-index="index0">
										<text class='cuIcon-close'></text>
									</view>
								</view>
								<view class="solids" @tap="chooseImage($event, specialSkill[index].insurCert)" v-if="specialSkill[index].insurCert.length < 1">
									<text class='cuIcon-cameraadd'></text>
								</view>
							</view>
						</view>
						<view class="flex justify-start align-center">
							<view>保险日期：</view>
							<uni-datetime-picker style="width: 75%;"
								:value="[specialSkill[index].insurStartDate, specialSkill[index].insurEndDate]"
								type="datetimerange" rangeSeparator="~" @change="changeInsurDate($event, index)" />
						</view>
					</view>
				</view>
				<view class="text-center margin-top">
					<button class="cu-btn bg-main-color light" @click="addSpecialSkill">
						<text class="margin-right-xs"><text class="cuIcon-add"></text></text>
						<text>继续添加特殊技能</text>
					</button>
				</view>
			</view>
			<view class="bottom-site-bar"></view>
			<!-- 下一步 -->
			<view class="cu-bar tabbar border shop fixed-bottom-bar bg-back">
				<button class="bg-white long-btn margin-lr" @click="preStep">上一步</button>
				<button class="bg-main-color long-btn margin-lr" @click="submit">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import myUniCombox from '@/components/uni-combox/my-uni-combox.vue';

	export default {
		components: {
			myUniCombox
		},
		onLoad() {
			this.loadData();
		},
		data() {
			return {
				curUserInfo: {},
				curStep: 0,
				// stepList: ['服务范围', '服务技能', '特殊技能'],
				stepList: ['服务范围', '服务技能'],
				provinceList: [],
				servArea: [{
					cityList: [],
					districtList: [],
					streetList: [],
					provinceObj: {},
					cityObj: {},
					districtObj: {},
					streetIds: []
				}],
				typeList: [],
				servSkill: [{
					subTypeList: [],
					subSubTypeList: [],
					typeObj: {},
					subTypeObj: {},
					subSubTypeIds: [],
					otherServSkill: null
				}],
				specialTypeList: [],
				specialSkill: [{
					specialSubTypeList: [],
					specialSubSubTypeList: [],
					specialTypeObj: {},
					specialSubTypeObj: {},
					specialSubSubTypeObj: {},
					specialSkillList: [],
					specialSkillObj: {},
					skillCert: [],
					insurCert: [],
					insurStartDate: '',
					insurEndDate: ''
				}],
			}
		},
		methods: {
			async loadData() {
				this.curUserInfo = this.$request.getCurUserInfo();
				await this.loadProvinceList();
				await this.loadTypeList();
				await this.loadExistData();
				// this.loadSpecialSkill();
			},
			async loadExistData() {
				this.loadServAreas();
				this.loadServSkills();
			},
			async loadServAreas() {
				let res = await this.$request.getWorkerAreaEdit({
					workerId: this.curUserInfo.workerId
				});
				let servArea = [];
				for(let i = 0; i < res.data.length; i++) {
					let item = res.data[i];
					let streetListRes = await this.$request.areaListByStep({
						parentCode: item.districtArea.areaCode
					});
					servArea.push({
						cityList: [],
						districtList: [],
						streetList: streetListRes.data,
						provinceObj: item.provinceArea,
						cityObj: item.cityArea,
						districtObj: item.districtArea,
						streetIds: item.streetIds
					})
				}
				if (servArea.length > 0) {
					this.servArea = servArea;
				}
			},
			async loadServSkills() {
				let res = await this.$request.getWorkerGoodsCategoryEdit({
					workerId: this.curUserInfo.workerId
				});
				let servSkill = [];
				for(let i = 0; i < res.data.length; i++) {
					let item = res.data[i];
					let subSubTypeRes = await this.$request.listByStep({
						goodsCategoryId: item.twoGoodsCategory.goodsCategoryId,
						type: 1
					});
					servSkill.push({
						subTypeList: [],
						subSubTypeList: subSubTypeRes.data,
						typeObj: item.oneGoodsCategory,
						subTypeObj: item.twoGoodsCategory,
						subSubTypeIds: item.categoryIds
					})
				}
				if (servSkill.length > 0) {
					this.servSkill = servSkill;
				}
			},
			/* 服务区域 start */
			async loadProvinceList() {
				let res = await this.$request.areaListByStep();
				this.provinceList = res.data;
			},
			async chooseRegion(e, type, index) {
				let res = await this.$request.areaListByStep({
					parentCode: e.areaCode
				});
				if (res.code == 0) {
					switch (type) {
						case 0: {
							this.servArea[index].cityList = res.data;
							this.servArea[index].districtList = [];
							this.servArea[index].streetList = [];
							this.servArea[index].cityObj = {};
							this.servArea[index].districtObj = {};
							this.servArea[index].streetIds = [];
						}
						break;
					case 1: {
						this.servArea[index].districtList = res.data;
						this.servArea[index].streetList = [];
						this.servArea[index].districtObj = {};
						this.servArea[index].streetIds = [];
					}
					break;
					case 2: {
						this.servArea[index].streetList = res.data;
						this.servArea[index].streetIds = [];
					}
					break;
					default:
						break;
					}
				}
			},
			checkStreet(e, index) {
				let checkedIndexArr = e.detail.value;
				this.servArea[index].streetIds = checkedIndexArr;
			},
			addServArea() {
				this.servArea.push({
					cityList: [],
					districtList: [],
					streetList: [],
					provinceObj: {},
					cityObj: {},
					districtObj: {},
					streetIds: []
				});
			},
			delServArea(index) {
				this.servArea.splice(index, 1);
			},
			async reloadTargetArea(colIndex, areaIndex) {
				switch(colIndex) {
					case 1: {
						if (this.servArea[areaIndex].provinceObj 
						&& (!this.servArea[areaIndex].cityList
							|| this.servArea[areaIndex].cityList.length === 0)) {
							let res = await this.$request.areaListByStep({
								parentCode: this.servArea[areaIndex].provinceObj.areaCode,
							});
							this.servArea[areaIndex].cityList = res.data;
						}
					} break;
					case 2: {
						if (this.servArea[areaIndex].cityObj 
						&& (!this.servArea[areaIndex].districtList
							|| this.servArea[areaIndex].districtList.length === 0)) {
							let res = await this.$request.areaListByStep({
								parentCode: this.servArea[areaIndex].cityObj.areaCode,
							});
							this.servArea[areaIndex].districtList = res.data;
						}
					} break;
					default: break;
				}
			},
			/* 服务区域 end */
			/* 服务技能 start */
			async loadTypeList() {
				let res = await this.$request.listByStep({
					type: 1
				});
				res = res.data;
				let typeList = await this.$request.listByStep({
					type: 1,
					goodsCategoryId: res[0].goodsCategoryId
				});
				this.typeList = typeList.data;
			},
			async chooseType(e, type, index) {
				let res = await this.$request.listByStep({
					goodsCategoryId: e.goodsCategoryId,
					type: 1
				});
				if (res.code == 0) {
					switch (type) {
						case 0: {
							this.servSkill[index].subTypeList = res.data;
							this.servSkill[index].subSubTypeList = [];
							this.servSkill[index].subTypeObj = {};
							this.servSkill[index].subSubTypeIds = [];
						}
						break;
					case 1: {
						this.servSkill[index].subSubTypeList = res.data;
						this.servSkill[index].subSubTypeIds = [];
					}
					break;
					default:
						break;
					}
				}
			},
			checkGoodType(e, index) {
				let checkedIndexArr = e.detail.value;
				this.servSkill[index].subSubTypeIds = checkedIndexArr;
			},
			addServSkill() {
				this.servSkill.push({
					subTypeList: [],
					subSubTypeList: [],
					typeObj: {},
					subTypeObj: {},
					subSubTypeIds: [],
					otherServSkill: null
				});
			},
			delServSkill(index) {
				this.servSkill.splice(index, 1);
			},
			async reloadTargetCategory(colIndex, servSkillIndex) {
				switch(colIndex) {
					case 1: {
						if (this.servSkill[servSkillIndex].typeObj 
						&& (!this.servSkill[servSkillIndex].subTypeList
							|| this.servSkill[servSkillIndex].subTypeList.length === 0)) {
							let res = await this.$request.listByStep({
								goodsCategoryId: this.servSkill[servSkillIndex].typeObj.goodsCategoryId,
								type: 1
							});
							this.servSkill[servSkillIndex].subTypeList = res.data;
						}
					} break;
					default: break;
				}
			},
			/* 服务技能 end */
			/* 特殊技能 start */
			async loadSpecialSkill() {
				let res = await this.$request.listByStep({
					type: 1
				});
				res = res.data;
				let typeList = await this.$request.listByStep({
					type: 1,
					goodsCategoryId: res[0].goodsCategoryId
				});
				this.specialTypeList = typeList.data;
			},
			async chooseSpecialSkill(e, type, index) {
				let funName = "listByStep";
				if (type === 2) {
					funName = "qrySpecialSkillList";
				}
				let res = await this.$request[funName]({
					goodsCategoryId: e.goodsCategoryId,
					type: 1
				});
				if (res.code == 0) {
					switch (type) {
						case 0: {
							this.specialSkill[index].specialSubTypeList = res.data;
							this.specialSkill[index].specialSubSubTypeList = [];
							this.specialSkill[index].specialSubTypeObj = {};
							this.specialSkill[index].specialSubSubTypeObj = {};
						}
						break;
						case 1: {
							this.specialSkill[index].specialSubSubTypeList = res.data;
							this.specialSkill[index].specialSubSubTypeObj = {};
						}
						case 2: {
							this.specialSkill[index].specialSkillList = res.data;
							this.specialSkill[index].specialSkillObj = {};
						}
						break;
						default:
							break;
					}
				}
			},
			addSpecialSkill() {
				this.specialSkill.push({
					specialSubTypeList: [],
					specialSubSubTypeList: [],
					specialTypeObj: {},
					specialSubTypeObj: {},
					specialSubSubTypeObj: {},
					skillCert: [],
					insurCert: [],
					insurStartDate: '',
					insurEndDate: ''
				});
			},
			delSpecialSkill(index) {
				this.specialSkill.splice(index, 1);
			},
			changeInsurDate(e, index) {
				this.specialSkill[index].insurStartDate = e[0];
				this.specialSkill[index].insurEndDate = e[1];
			},
			async chooseImage(e, imgList) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						// 上传图片
						res.tempFilePaths.forEach((tmpPath) => {
							this.$request.uploadFile(tmpPath).then((url) => {
								// 存入缓存
								imgList.push(url);
							});
						})
					}
				});
			},
			viewImage(e, imgList) {
				uni.previewImage({
					urls: imgList,
					current: e.currentTarget.dataset.url
				});
			},
			delImg(e, imgList) {
				uni.showModal({
					title: '',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			/* 特殊技能 end */
			nextStep() {
				let workerAreas = [];
				// 区域参数
				this.servArea.forEach((item) => {
					item.streetIds.forEach((streetId) => {
						workerAreas.push({
							provinceId: item.provinceObj.areaId,
							cityId: item.cityObj.areaId,
							districtId: item.districtObj.areaId,
							streetId: streetId
						})
					});
				});
				let params = {
					workerAreas: workerAreas
				}
				if (this.curStep === 0 && !this.validData(params)) {
					return;
				}
				this.curStep = this.curStep === this.stepList.length - 1 ? this.curStep : ++this.curStep;
			},
			preStep() {
				this.curStep = this.curStep === 0 ? 0 : --this.curStep;
			},
			validData(data) {
				let errMsg = null;
				if (!data.workerAreas || !data.workerAreas.length) {
					errMsg = '请至少添加一个服务区域（需要勾选到服务街道）';
				}
				if (this.curStep > 0) {
					if (!data.goodsCategories || !data.goodsCategories.length) {
						errMsg = '请至少添加一个服务技能（需要勾选到三级类目）';
					}
				}
				if (errMsg) {
					uni.showToast({
						icon: 'none',
						title: errMsg,
						duration: 3000
					})
					return false;
				}
				return true;
			},
			async submit() {
				let workerId = this.curUserInfo.workerId;
				let workerAreas = [];
				let goodsCategories = [];
				// let specialSkills = [];
				// 区域参数
				this.servArea.forEach((item) => {
					item.streetIds.forEach((streetId) => {
						workerAreas.push({
							workerId: workerId,
							provinceId: item.provinceObj.areaId,
							cityId: item.cityObj.areaId,
							districtId: item.districtObj.areaId,
							streetId: streetId
						})
					});
				});
				// 服务品类参数
				this.servSkill.forEach((item) => {
					item.subSubTypeIds.forEach((goodsCategoryId) => {
						goodsCategories.push({
							workerId: workerId,
							goodsCategoryId: goodsCategoryId
						});
					});
				});
				// 特殊技能参数
				// this.specialSkill.forEach((item) => {
				// 	specialSkills.push({
				// 		workerId: workerId,
				// 		specialSkillId: item.specialSkillObj.specialSkillId,
				// 		credential: item.skillCert[0],
				// 		insurance: item.insurCert[0],
				// 		insuranceStart: item.insurStartDate,
				// 		insuranceEnd: item.insurEndDate
				// 	});
				// });
				
				let params = {
					workerId: workerId,
					workerAreas: workerAreas,
					goodsCategories: goodsCategories,
					// specialSkills: specialSkills
				}
				
				if (!this.validData(params)) {
					return;
				}
				
				let res = await this.$request.workerSettled(params);
				if (res && res.code === 0) {
					uni.showToast({
						icon: 'success',
						title: '提交成功',
						duration: 2000
					})
					// 更新当前缓存的用户信息
					let newUserInfo = await this.$request.getCurUserNoCache();
					this.$request.updateCache('userProfile', newUserInfo);
					uni.navigateBack({
						delta: -1
					})
				}
			}
		},
	}
</script>

<style scoped>
	/deep/ .uni-combox__selector {
		z-index: 99 !important;
	}

	.grid.col-1.grid-square.upload-pic-grid>view {
		padding-bottom: 35%;
		height: 0;
		margin-right: 20rpx;
	}

	.grid.col-1.upload-pic-grid>view {
		width: 35%;
	}

	/deep/ .uni-date__x-input {
		height: 36px;
	}
</style>
