package com.qunzhixinxi.hnqz.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.entity.SysUserExtRecord;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.mapper.SysUserExtRecordMapper;
import com.qunzhixinxi.hnqz.admin.service.SysUserExtRecordService;
import com.qunzhixinxi.hnqz.common.security.service.HnqzUser;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户认证相关的扩展信息服务
 */
@Service
@AllArgsConstructor
public class SysUserExtRecordServiceImpl extends ServiceImpl<SysUserExtRecordMapper, SysUserExtRecord>
		implements SysUserExtRecordService {

	/**
	 * 保存E证通认证结果
	 *
	 * @param userExtRecord
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUserExtRecord(SysUserExtRecord userExtRecord) {
		HnqzUser hnqzUser = SecurityUtils.getUser();

		// 作废已有数据
		this.update(Wrappers.<SysUserExtRecord>lambdaUpdate()
				.eq(SysUserExtRecord::getUserId, hnqzUser.getId())
				.eq(SysUserExtRecord::getDelFlag, DelEnum.NOT_DEL.val())
				.set(SysUserExtRecord::getDelFlag, DelEnum.DELETED.val()));
		// 新增一条数据
		SysUserExtRecord insertExtRecord = BeanUtil.copyProperties(userExtRecord, SysUserExtRecord.class);
		insertExtRecord.setUserId(hnqzUser.getId());
		insertExtRecord.setDeptId(hnqzUser.getDeptId());
		insertExtRecord.setCreateTime(LocalDateTime.now());
		insertExtRecord.setCreateUser(hnqzUser.getId());
		this.save(insertExtRecord);
	}

	/**
	 * 查询E证通是否认证过
	 *
	 * @return
	 */
	@Override
	public boolean existUserExtRecord() {
		Integer userId = SecurityUtils.getUser().getId();
		int count = this.count(Wrappers.<SysUserExtRecord>lambdaQuery()
				.eq(SysUserExtRecord::getUserId, userId)
				.eq(SysUserExtRecord::getDelFlag, DelEnum.NOT_DEL.val()));

		return count > 0;
	}

	/**
	 * 保存E证通认证结果
	 *
	 * @param data
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void eidResultHandler(JSONObject data) {
		// 认证成功，则保存
		SysUserExtRecord userExtRecord = new SysUserExtRecord();
		userExtRecord.setRealName(data.getStr("realName"));
		userExtRecord.setIdCardNumber(data.getStr("idCard"));
		userExtRecord.setBestFrameBase64(data.getStr("bestFrameBase64"));
		userExtRecord.setBestFrameUrl(data.getStr("bestFrameUrl"));
		userExtRecord.setIdCardFrontBase64(data.getStr("idCardFrontBase64"));
		userExtRecord.setIdCardBackBase64(data.getStr("idCardBackBase64"));
		userExtRecord.setIdCardFrontUrl(data.getStr("idCardFrontUrl"));
		userExtRecord.setIdCardBackUrl(data.getStr("idCardBackUrl"));
		userExtRecord.setEtoken(data.getStr("etoken"));
		this.saveUserExtRecord(userExtRecord);
	}

}
