import { clearToken } from '@/utils/request.js'
import { getUserInfo } from '@/api/user.js'
import { clearEnterpriseCertForm } from '@/utils/enterprise-cert-cache.js'

const defaultWorker = () => ({
	name: '',
	phone: '',
	registered: false
})

const store = {
	state: {
		loggedIn: false,
		role: 'enterprise',
		user: {
			userId: null,
			name: '张经理',
			avatarText: '张',
			mobile: '138****8888'
		},
		enterprise: {
			name: '某某科技有限公司',
			code: '91310000...',
			registered: false
		},
		worker: defaultWorker()
	},

	login(role = 'enterprise', options = {}) {
		this.state.loggedIn = true
		this.state.role = role

		const { userId, mobileMask, nickname, mobile, newUser } = options
		if (userId) this.state.user.userId = userId
		if (mobileMask || mobile) {
			this.state.user.mobile = mobileMask || mobile
		}
		if (nickname) {
			this.state.user.name = nickname
			this.state.user.avatarText = nickname.charAt(0)
		}

		// 每次登录先清登记态，避免沿用上一账号本地缓存；最终以 /getInfo 为准
		if (role === 'worker') {
			this.state.worker = defaultWorker()
			if (mobile) {
				this.state.worker.phone = mobile
			}
			if (typeof newUser === 'boolean') {
				this.state.worker.registered = !newUser
			}
		} else {
			this.state.enterprise = {
				...this.state.enterprise,
				registered: false
			}
			if (typeof newUser === 'boolean') {
				this.state.enterprise.registered = !newUser
			}
		}

		this.persist()
	},

	logout() {
		clearToken()
		this.state.loggedIn = false
		this.state.worker = defaultWorker()
		this.state.enterprise.registered = false
		clearEnterpriseCertForm()
		this.persist()
	},

	registerWorker(profile = {}) {
		this.state.worker = {
			...this.state.worker,
			...profile,
			registered: true
		}
		this.persist()
	},

	registerEnterprise(profile = {}) {
		this.state.enterprise = {
			...this.state.enterprise,
			...profile,
			registered: true
		}
		if (profile.contactName) {
			this.state.user.name = profile.contactName
			this.state.user.avatarText = profile.contactName.charAt(0)
		}
		if (profile.contactMobileMask) {
			this.state.user.mobile = profile.contactMobileMask
		}
		this.persist()
	},

	/** 将 /getInfo 响应写入本地状态 */
	applyUserInfo(info = {}) {
		if (!info || typeof info !== 'object') return

		const role = info.userType === 'worker' ? 'worker' : 'enterprise'
		this.state.loggedIn = true
		this.state.role = role

		if (info.mobileMask) {
			this.state.user.mobile = info.mobileMask
		}

		if (role === 'worker') {
			if (!this.state.worker) {
				this.state.worker = defaultWorker()
			}
			this.state.worker.registered = !!info.registered

			if (info.worker) {
				const worker = info.worker
				this.state.worker = {
					...this.state.worker,
					name: worker.realName || this.state.worker.name,
					phone: worker.mobileMask || info.mobileMask || this.state.worker.phone,
					workerId: worker.workerId,
					workerNo: worker.workerNo,
					idCardNoMask: worker.idCardNoMask,
					bankAccountMask: worker.bankAccountMask,
					bankName: worker.bankName,
					bankBranch: worker.bankBranch,
					verifyStatus: worker.verifyStatus
				}
				if (worker.realName) {
					this.state.user.name = worker.realName
					this.state.user.avatarText = worker.realName.charAt(0)
				}
			}
		}

		if (role === 'enterprise') {
			this.state.enterprise.registered = !!info.registered

			if (info.enterprise) {
				const enterprise = info.enterprise
				this.state.enterprise = {
					...this.state.enterprise,
					enterpriseId: enterprise.enterpriseId,
					enterpriseCode: enterprise.enterpriseCode,
					name: enterprise.name || this.state.enterprise.name,
					code: enterprise.creditCode || enterprise.enterpriseCode || this.state.enterprise.code,
					creditCode: enterprise.creditCode,
					legalPerson: enterprise.legalPerson,
					legalPersonIdCard: enterprise.legalPersonIdCard || enterprise.legal_person_id_card || '',
					legalPersonIdCardMask: enterprise.legalPersonIdCardMask || enterprise.legal_person_id_card_mask || '',
					registeredAddress: enterprise.registeredAddress,
					contactName: enterprise.contactName,
					contactMobile: enterprise.contactMobile || enterprise.contact_mobile || '',
					contactMobileMask: enterprise.contactMobileMask,
					authStatus: enterprise.authStatus
				}
				if (enterprise.contactName) {
					this.state.user.name = enterprise.contactName
					this.state.user.avatarText = enterprise.contactName.charAt(0)
				}
			}
		}

		this.persist()
	},

	/** 登录成功后拉取并同步用户信息 */
	syncProfile(options = {}) {
		return getUserInfo(options).then((info) => {
			this.applyUserInfo(info)
			return info
		})
	},

	isWorkerRegistered() {
		return !!(this.state.worker && this.state.worker.registered)
	},

	isEnterpriseRegistered() {
		return !!(this.state.enterprise && this.state.enterprise.registered)
	},

	getLoginEntryUrl(role, needRegister) {
		const r = role === 'worker' ? 'worker' : 'enterprise'
		// 企业：登录即可进首页，未认证不拦，在「我的」展示游客态
		if (r === 'enterprise') {
			return this.getHomeUrl()
		}
		if (needRegister === true) {
			return this.getRegisterUrl(r)
		}
		if (typeof needRegister !== 'boolean') {
			if (!this.isWorkerRegistered()) return this.getRegisterUrl(r)
		}
		return this.getHomeUrl()
	},

	getRegisterUrl(role = 'enterprise') {
		return role === 'worker' ? '/packageA/worker/register' : '/packageA/enterprise/register'
	},

	getHomeUrl() {
		return '/packageA/home/index'
	},

	getWorkerEntryUrl() {
		return this.getLoginEntryUrl('worker')
	},

	persist() {
		try {
			uni.setStorageSync('fe_demo', this.state)
		} catch (e) {}
	},

	restore() {
		try {
			const data = uni.getStorageSync('fe_demo')
			if (data) {
				this.state = { ...this.state, ...data }
				if (!this.state.worker) {
					this.state.worker = defaultWorker()
				} else if (this.state.worker.registered === undefined) {
					this.state.worker.registered = false
				}
				if (this.state.enterprise.registered === undefined) {
					this.state.enterprise.registered = false
				}
			}
		} catch (e) {}
	},

	getState() {
		return this.state
	}
}

store.restore()
export default store
