<template>
	<view class="page">
		<view class="steps flex-col flex-jus-center" v-if="role!=3">
			<d-steps mode="number" :list="numList" :current="current"></d-steps>
		</view>
		<view class="hiht" v-show="current==2">
			{{`根据国家监管要求，${role==1?'医生':'药师'}线上执业需要进行资格认证，请根据提示完善认证信息，开启线上个人诊室`}}
		</view>
		<scroll-view scroll-y="true"
			:style="{height: `calc(100vh - 160rpx - env(safe-area-inset-bottom) - ${role!=3?'138rpx':'1rpx'} - ${current==2?'100rpx':'1rpx'})`}"
			:scroll-top="scrollTop">
			<basic-information ref="info" :role="role" :info="info[current]" @submit_data="dispose" v-if="current == 0"
				@select="pickerShow=true" @select1="pickerShow1=true">
			</basic-information>
			<self-introduction ref="info" :role="role" :info="info[current]" @submit_data="dispose" v-if="current == 1"
				@affirm="showHs = true">
			</self-introduction>
			<practice-info ref="info" :role="role" :info="info[current]" @submit_data="dispose" v-if="current == 2">
			</practice-info>
			<open-serve ref="info" :info="info[current]" @submit_data="dispose" v-if="current == 3"></open-serve>
			<view style="height: 40rpx;width: 100vw;"></view>
		</scroll-view>
		<view class="bottom flex-col flex-jus-se flex-ali-center">
			<view class="flex-row flex-ali-center">
				<image src="../../../static/image/aq.png"></image>
				<text>请如实填写,本平台将严格保密您的个人信息</text>
			</view>
			<view class="button btn" v-show="current==0||role==3">
				<u-button :throttle-time="0" shape="circle" @click="submit">{{role==3?'立即提交':'下一步'}}
				</u-button>
			</view>
			<view class="flex-row flex-jus-sp button" v-show="current>0">
				<view style="width: 327rpx;86rpx;" class="plain">
					<u-button :throttle-time="0" shape="circle" @click="save();current--" plain>返回上一步</u-button>
				</view>
				<view style="width: 327rpx;86rpx;" class="btn">
					<u-button :throttle-time="0" shape="circle" @click="submit">
						{{current==numList.length-1?'立即提交':'下一步'}}
					</u-button>
				</view>
			</view>
		</view>
		<d-handwritten v-model="showHs" @saveCanvas="saveCanvas"></d-handwritten>
		<u-modal v-model="show" :async-close="true" @confirm="confirm" :show-cancel-button="true"
			content="请确认您填写的信息准确无误" :content-style="{fontSize: '34rpx',color:'#6C7380'}" confirm-text="确定"
			:confirm-style="{fontSize: '34rpx'}" :cancel-style="{fontSize: '34rpx'}"></u-modal>

		<u-picker cancel-color="#6ACDBB" confirm-text="确定" :safe-area-inset-bottom="true" v-model="pickerShow"
			@confirm="sel" mode="selector" :default-selector="[0]" range-key="name" :range="positions" title="职称"
			:mask-close-able="false" @cancel="cancel">
		</u-picker>




		<u-picker v-if="role==1" cancel-color="#6ACDBB" confirm-text="确定" :safe-area-inset-bottom="true"
			v-model="pickerShow1" @confirm="selxi" mode="selector" :default-selector="[0]" range-key="value"
			:range="doctorTypes" title="西医/中医" :mask-close-able="false" @cancel="cancel">
		</u-picker>

		<u-picker v-if="role==2" cancel-color="#6ACDBB" confirm-text="确定" :safe-area-inset-bottom="true"
			v-model="pickerShow1" @confirm="selxi" mode="selector" :default-selector="[0]" range-key="value"
			:range="doctorTypes" title="西药/中药" :mask-close-able="false" @cancel="cancel">
		</u-picker>

	</view>
</template>

<script>
	import {
		doctorTypeList,
		professionalList,
		doctorStepOne,
		doctorStepTwo,
		doctorStepThree,
		doctorStepFour,
		drugStepOne,
		drugStepTwo,
		drugStepThree,
		leader,
		info,
		personalData,
		leadInfo,
		servInfo,
		drugInfo,
		drugTypeList,
		syncDoctor
	} from '@/api/all.js'
	import basicInformation from './components/basic-information.vue';
	import selfIntroduction from './components/self-introduction.vue';
	import openServe from './components/open-serve.vue';
	import practiceInfo from './components/practice-info.vue';
	import { checkProfileTexts, handleSecurityError, SCENE_PROFILE } from '@/common/js/content-security.js';
	export default {
		components: {
			basicInformation,
			selfIntroduction,
			openServe,
			practiceInfo
		},
		data() {
			return {
				isSet: false,
				isSetIndex: 0,
				isFresh: false,
				positions: [],
				doctorTypes: [],
				pickerShow: false,
				pickerShow1: false,
				scrollTop: 0,
				showHs: false,
				windowHeight: this.$windowHeight,
				show: false,
				info: [{
						card: [],
						hospital: {},
						repartments: {},
						position: {},
						doctorType: {},
						mobile: (uni.getStorageSync('logInfo') || {}).mobile ? uni.getStorageSync('logInfo').mobile : (
							uni.getStorageSync('userInfo') || {}).mobile
					},
					{
						card: [],
						work: ''
					},
					{
						qualifications: {},
						practice: {},
						position: {}
					},
					{}
				],
				is_login: false, // 是否登录
				current: 0, //设置当前处于第几步
				numList: [{
						name: '基本信息'
					},
					{
						name: '身份认证'
					},
					{
						name: '执业信息'
					},
					{
						name: '开通服务'
					}
				],
				identity: uni.getStorageSync('role') || 1,
				role: uni.getStorageSync('role') || 1,
				identitys: "",
				// 内容安全 baseline：表单初始值快照
				_securityBaseline: {},
			};
		},
		created() {
			switch (parseInt(this.identity) - 1) {
				case 0:
					this.numList = this.numList
					break;
				case 1:
					this.numList = [{
							name: '基础信息'
						},
						{
							name: '身份认证'
						},
						{
							name: '执业信息'
						}
					]
					break;
			}
			this.professionalList()
			this.doctorTypeList()
		},
		onShow() {
			this.getInfo();
			this.$nextTick(() => {
				this.$set(this.$refs.info, 'form', {
					...this.$refs.info['form'],
					show: true
				})
				let userInfo = uni.getStorageSync('userInfo')
				if (userInfo.DoctorInfo) {
					if (this.role == 1) {
						userInfo = {
							...userInfo,
							...userInfo.DoctorInfo,
							titles: userInfo.title
						}
					} else {
						userInfo = {
							...userInfo
						}
					}
				}
				if (userInfo && !this.isSet) {
					this.isSet = true
					this.$set(this.$refs.info, 'form', {
						...this.$refs.info['form'],
						...userInfo,
						position: {
							name: userInfo.titles.name,
							title_id: userInfo.title_id || userInfo.titles.id
						},
						// positioned: { name: userInfo.titles.name },
						id_card: userInfo.idcard
					})
					this._securityBaseline = {
						name: userInfo.name || '',
						beGoodAt: userInfo.good_at || '',
						about: userInfo.intro || '',
					}
					uni.setStorageSync('d_name', userInfo.depart)
				}
				// 门店
				uni.getStorageSync('callBackM') && this.$set(this.$refs.info.form, 'callBackM', uni.getStorageSync(
					'callBackM'))
				// 科室
				uni.getStorageSync('d_name') && this.$set(this.$refs.info.form, 'd_name', uni
					.getStorageSync('d_name'))
				uni.removeStorageSync('callBackM');
				uni.removeStorageSync('d_name');
			})
		},
		methods: {
			dispose() {
				this.save()
				if (this.current == this.numList.length - 1) {
					this.show = true
					return
				}
				if (this.isSetIndex == this.current) {
					this.isSetIndex++
				}
				this.current++;
				this.scrollTop = -1

				this.$nextTick(() => {
					this.scrollTop = 0
					let userInfo = uni.getStorageSync('userInfo')
					if (userInfo.DoctorInfo) {
						userInfo = {
							...userInfo,
							...userInfo.DoctorInfo
						}
					}
					if (userInfo) {
						if (this.current == 1 && this.isSetIndex == 1) {
							if (this.role == 1) {
								this.$set(this.$refs.info, 'form', {
									...this.$refs.info['form'],
									// signature: userInfo.identity.sign_type,
									work: {
										url: userInfo.DoctorIdentity.work_avator,
										error: false,
										progress: 100
									},
									card: [{
										url: userInfo['DoctorIdentity']['card_down'],
										error: false,
										progress: 100
									}, {
										url: userInfo.DoctorIdentity.card_up,
										error: false,
										progress: 100
									}]
								})
							} else {
								this.$set(this.$refs.info, 'form', {
									...this.$refs.info['form'],
									// signature: userInfo.identity.sign_type,
									card: [{
										url: userInfo.identity['card_down'],
										error: false,
										progress: 100
									}, {
										url: userInfo.identity.card_up,
										error: false,
										progress: 100
									}]
								})
							}
						}
						// console.log(userInfo.doctor_service.register_status,'aaaaaaaaaaaaaasd');
						if (this.current == 3 && this.isSetIndex == 3 && this.role == 1) {
							this.$set(this.$refs.info, 'form', {
								...this.$refs.info['form'],
								openServe: userInfo.doctor_service.register_status,
								price: userInfo.doctor_service.register_price,
							})
						}
						if (this.current == 2 && this.isSetIndex == 2) {
							if (this.identity == 1) {
								this.$set(this.$refs.info, 'form', {
									...this.$refs.info['form'],
									qualifications: JSON.parse(userInfo.DoctorPracticing.qualification)
										.map(item => ({
											url: item,
											error: false,
											progress: 100
										})),
									practice: JSON.parse(userInfo.DoctorPracticing.practicing).map(item =>
										({
											url: item,
											error: false,
											progress: 100
										})),
									position: JSON.parse(userInfo.DoctorPracticing.title).map(item => ({
										url: item,
										error: false,
										progress: 100
									}))
								})
							} else {
								this.$set(this.$refs.info, 'form', {
									...this.$refs.info['form'],
									qualifications: JSON.parse(userInfo.practings.qualification).map(
										item => ({
											url: item,
											error: false,
											progress: 100
										})),
									practice: JSON.parse(userInfo.practings.practicing).map(item => ({
										url: item,
										error: false,
										progress: 100
									})),
									position: JSON.parse(userInfo.practings.title).map(item => ({
										url: item,
										error: false,
										progress: 100
									}))
								})
							}
						}
					}
				})

			},


			//region
			async getInfo() {
				let role = uni.getStorageSync('identity')
				let req = {};
				const data = {
					store_id: uni.getStorageSync('store_id') || '11001',
				}
				role == 1 && (req = await info(data))
				role == 2 && (req = await personalData(data))
				// role == 2 && (req = await drugInfo(data))

				if (req.errcode == 0) {
					let userInfo = {
						...req.data
					}
					uni.removeStorageSync('logInfo')
					uni.setStorageSync('userInfo', userInfo)

					// console.log(req.data,'ssssssssssssssssss');
					if (this.role == 1 && userInfo.ServiceUser.status == 1) {
						this.$go('../workbench_succeed?type=1')
					}
					if (this.role == 2 && userInfo.user['status'] == 1) {
						this.$go('../workbench_succeed?type=1')
					}
					if (this.role == 1 && userInfo.DoctorInfo.user['role']) {
						uni.setStorageSync('identity', userInfo.DoctorInfo.user['role'])
					} else {
						uni.setStorageSync('identity', userInfo.user['role'])
					}
				} else {
					this.$toast(req.msg)
				}
			},
			sel(e) {
				this.$set(this.$refs.info, 'form', {
					...this.$refs.info['form'],
					show: true
				})
				this.$set(this.$refs.info.form, 'position', this.positions[e[0]])

			},
			cancel() {
				this.$set(this.$refs.info, 'form', {
					...this.$refs.info['form'],
					show: true
				})
			},

			selxi(e) {
				this.$set(this.$refs.info, 'form', {
					...this.$refs.info['form'],
					show: true
				})
				this.$set(this.$refs.info.form, 'doctorType', this.doctorTypes[e[0]])
				this.identitys = this.doctorTypes[e[0]].key
				// console.log(this.doctorTypes[e[0]].key);
				// console.log(this.identitys);
			},

			//职称列表 type 1医生2药师
			professionalList() {
				const dat = {
					store_id: uni.getStorageSync('store_id') || '11001',
					type: this.role,
				}
				professionalList(dat).then(res => {
					// console.log(res);
					if (res.errcode != -1) {
						this.positions = res.data
						// console.log(res.data);
					} else {
						this.$toast(res.msg)
					}
				})
			},
			//中西医
			doctorTypeList() {
				const dat = {
					store_id: uni.getStorageSync('store_id') || '11001',
					type: this.role,
					page: 1,
				}
				this.role == 1 && doctorTypeList(dat).then(res => {
					// console.log(res);
					if (res.errcode != -1) {
						this.doctorTypes = res.data
						// console.log(res.data);
					} else {
						this.$toast(res.msg)
					}
				})

				this.role == 2 && drugTypeList(dat).then(res => {
					// console.log(res);
					if (res.errcode != -1) {
						this.doctorTypes = res.data
						// console.log(res.data);
					} else {
						this.$toast(res.msg)
					}
				})
			},

			saveCanvas(e) {
				this.showHs = false
				const base64 = typeof e === 'string' ? e : (e && e.base64)
				if (base64) this.$set(this.$refs.info.form, 'write', base64)
			},
			async confirm() {
				switch (parseInt(this.identity - 1)) {
					case 0:
						await this.stepOne();
						await this.stepTwo();
						await this.stepThree();
						// await this.stepFour();
						break;
					case 1:
						await this.stepOne();
						await this.stepTwo();
						await this.stepThree();
						break;
				}
			},

			//#region
			succeed() {
				this.show = false
				this.getInfo();
			},
			submit() {
				this.$refs.info.submit();
			},
			save() {
				this.info[this.current] = this.$refs.info.form
				// console.log(this.info, 'save-fu');
			},

			// 完善基本信息
			async stepOne() {
				console.log(this.info, 'this.infossssssssssssssss');
				try {
					if (this.role == 1) {
						await checkProfileTexts({
							beGoodAt: this.info[0]['beGoodAt'],
							about: this.info[0]['about'],
							name: this.info[0]['name'],
						}, this._securityBaseline, SCENE_PROFILE);
					} else if (this.role == 2) {
						await checkProfileTexts({
							name: this.info[0]['name'],
						}, this._securityBaseline, SCENE_PROFILE);
					}
				} catch (e) {
					handleSecurityError(e);
					return;
				}
				const data = {
					name: this.info[0]['name'],
					avatar: this.info[0]['avatar'],
					mobile: this.info[0]['mobile'],
					depart_id: uni.getStorageSync('depart_id'),
					idcard: this.info[0]['id_card'],
					store_id: JSON.stringify(uni.getStorageSync('storeidList') || '11001'),
					// yard_id: this.info[0]['hospital']['1']['id'],
					title_id: this.info[0]['position'] ? this.info[0]['position']['id'] : '',
					good_at: this.info[0]['beGoodAt'],
					intro: this.info[0]['about'],
					identity: this.info[0]['doctorType'] ? this.info[0]['doctorType']['key']  : '1'
				}

				let res = {};
				this.role == 1 && (res = await doctorStepOne(data))

				const datas = {
					name: this.info[0]['name'],
					avatar: this.info[0]['avatar'],
					mobile: this.info[0]['mobile'],
					// depart_id: uni.getStorageSync('depart_id'),
					idcard: this.info[0]['id_card'],
					store_id: uni.getStorageSync('storeidList') || '11001',
					type: this.info[0]['doctorType'] ? this.info[0]['doctorType']['key'] + 1 : 1,
					// yard_id: this.info[0]['hospital']['1']['id'],
					title_id: this.info[0]['position'] ? this.info[0]['position']['id'] : '',
				}
				this.role == 2 && (res = await drugStepOne(datas))

				// this.identity == 3 && (res = await leader(data))
				// this.identity == 4 && (res = await service(data))
				if (res.errcode == 0) {
					// uni.removeStorageSync('info_submit')
					parseInt(this.role) > 2 && this.succeed()
				} else {
					this.$toast(res.msg)
					this.show = false
				}
			},
			// 完善认证信息
			async stepTwo() {
				const data = {
					card_up: this.info[1]['card'][0]['url'],
					card_down: this.info[1]['card'][1]['url'],
					sign_image: this.info[1]['write'],
					sign_type: this.info[1]['signature'],
					work_avator: this.info[1]['work']['url'],
					store_id: uni.getStorageSync('store_id') || '11001',
				}
				this.role == 2 && delete data['work_avator'];
				let res = {};
				this.role == 1 && (res = await doctorStepTwo(data));
				this.role == 2 && (res = await drugStepTwo(data));
				if (res.errcode == 0) {} else {

					this.$toast(res.msg)
					this.show = false
				}
			},
			// 完善执业信息
			async stepThree() {
				let qualifications = this.info[2]['qualifications']
				let qualification = [qualifications[0]['url'], qualifications[1]['url']]
				qualifications['list'] && qualification.push(...qualifications['list'].reduce((total, item) => {
					total.push(item.url)
					return total
				}, []))
				
				const data = {
					qualification: JSON.stringify(qualification),
					// practicing: JSON.stringify(practicing),
					// title: JSON.stringify(title),
					store_id: uni.getStorageSync('store_id') || '11001',
				}
				
				let res = {};
				this.role == 2 && (res = await drugStepThree(data))
				if (res.errcode == 0) {
					parseInt(this.role) == 2 && this.$go('../workbench_succeed?type=1')
					uni.removeStorageSync('info_submit')
				} else {
					this.$toast(res.msg)
					this.show = false
				}

				let practice = this.info[2]['practice']
				let practicing = [practice[0]['url'], practice[1]['url']]
				practice['list'] && practicing.push(...practice['list'].reduce((total, item) => {
					total.push(item.url)
					return total
				}, []))

				let position = this.info[2]['position']
				let title = []
				position[0] && title.push(position[0]['url'])
				position[1] && title.push(position[0]['url'])
				position['list'] && title.push(...position['list'].reduce((total, item) => {
					total.push(item.url)
					return total
				}, []))
				
				const dataed = {
					qualification: JSON.stringify(qualification),
					practicing: JSON.stringify(practicing),
					title: JSON.stringify(title),
					store_id: uni.getStorageSync('store_id') || '11001',
				}

				this.role == 1 && (res = await doctorStepThree(dataed))

				this.role == 1 && this.stepFour()

				if (res.errcode == 0) {
					parseInt(this.role) == 2 && this.$go('../workbench_succeed?type=1')
				} else {
					this.$toast(res.msg)
					this.show = false
				}
			},
			stepFour() {
				const data = {
					register_status: Number(this.info[3]['price'] >= 0 ? 1 : 0),
					register_price: Number(this.info[3]['price'] || 0),
					store_id: JSON.stringify([uni.getStorageSync('store_id') || '11001']),
				}
				doctorStepFour(data).then(res => {
					if (res.errcode == 0) {
						uni.showModal({
							title: '提示',
							content: '是否要同步到互联网医院？',
							success: async (res) => {
								if (res.confirm) {
									syncDoctor({
										store_id: JSON.stringify([uni.getStorageSync('store_id') || '11001']),
									}).then(res => {
										this.succeed()
										this.$go('../workbench_succeed?type=1')
										uni.removeStorageSync('info_submit')
									}).catch(() => {
										this.succeed()
										this.$go('../workbench_succeed?type=1')
										uni.removeStorageSync('info_submit')
									})
								} else {
									this.succeed()
									this.$go('../workbench_succeed?type=1')
									uni.removeStorageSync('info_submit')
								}
							}
						});
						
					} else {
						this.$toast(res.msg)
						this.show = false
					}
				})
			},
		},
		mounted() {
			this.professionalList()
			this.doctorTypeList()
		}
	};
</script>
<style>
	page {
		background-color: #F7F8FA;
	}
</style>
<style lang="scss" scoped>
	.steps {
		background-color: #fff;
		height: 138rpx;
	}

	.hiht {
		width: 750rpx;
		height: 100rpx;
		background: #FFF3E0;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		color: #FFAB40;
		padding: 16rpx 32rpx;
	}

	.bottom {
		position: fixed;
		width: 100vw;
		height: calc(160rpx + env(safe-area-inset-bottom));
		padding: 0 32rpx;
		padding-bottom: env(safe-area-inset-bottom);
		bottom: 0;
		left: 0;
		background-color: #fff;
		z-index: 1;

		text {
			font-size: 24rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #6C7380;
		}

		image {
			width: 21rpx;
			height: 24rpx;
			margin-right: 10rpx;
		}
	}

	::v-deep .plain {
		button {
			background-color: transparent;
			color: #6ACDBB;
		}
	}

	.button {
		width: 686rpx;
		height: 86rpx;
	}

	.btn {
		::v-deep button {
			border: 0;
			background: #6ACDBB;
			font-size: 32rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
		}
	}
</style>