package com.hotent.uc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.controller.BaseController2;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.util.*;
import com.hotent.uc.manager.ElectronicSealManager;
import com.hotent.uc.model.ElectronicSeal;
import com.hotent.uc.model.User;
import com.hotent.uc.params.seal.ImportSignatureObject;
import com.hotent.uc.util.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 
 * <pre> 
 * 描述：uc_electronic_seal 控制器类
 * 构建组：x7
 * 作者:lihq
 * 邮箱:lihq@jee-soft.cn
 * 日期:2020-10-19 18:18:31
 * 版权：广州宏天软件股份有限公司
 * </pre>
 */
@RestController
@RequestMapping(value="/uc/electronicSeal/v2")
@Api(tags="electronicSealController2")
@ApiGroup(group= {ApiGroupConsts.GROUP_UC})
public class ElectronicSealController2 extends BaseController2<ElectronicSealManager,ElectronicSeal> {
	@Resource
	ElectronicSealManager electronicSealManager;
	@Autowired
	PasswordEncoder passwordEncoder;


    /**
	 * 新增uc_electronic_seal
	 * @param electronicSeal
	 * @throws Exception
	 * @return
	 * @exception
	 */
	@PostMapping(value="save")
	@ApiOperation(value = "添加签章成功", httpMethod = "POST", notes = "添加签章成功")
	public CommonResult<String> save(@ApiParam(name="electronicSeal",value="电子签章业务对象", required = true)@RequestBody ElectronicSeal electronicSeal) throws Exception{
		return CommonResultUtil.getResult(electronicSealManager.saveElectronicSeal(electronicSeal));
	}

	/**
	 * front用户自己添加电子签章
	 * @param electronicSeal
	 * @return
	 */
	@PostMapping(value="userSave")
	@ApiOperation(value = "front用户自己添加电子签章", httpMethod = "POST", notes = "添加签章成功")
	public CommonResult<String> userSave(@ApiParam(name="electronicSeal",value="电子签章业务对象", required = true)@RequestBody ElectronicSeal electronicSeal) throws Exception {
		CommonResult<String> commonResult = electronicSealManager.userSaveElectronicSeal(electronicSeal);
		return CommonResultUtil.getResult(commonResult);
	}

	@PostMapping(value = "mobileUpdate")
	@ApiOperation(value = "手机端更新签章",httpMethod = "POST",notes = "手机端更新签章")
	public CommonResult<String> mobileUpdate(@RequestBody ElectronicSeal electronicSeal) throws Exception {
		CommonResult<String> commonResult = electronicSealManager.mobileUpdateElectronicSeal(electronicSeal);
		return CommonResultUtil.getResult(commonResult);
	}
	
	@RequestMapping(value="getElectronicSeal",method=RequestMethod.GET, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "获取当前登录用户的签章id", httpMethod = "GET", notes = "获取当前登录用户的签章id")
	public CommonResult<String> getUser(@ApiParam(name="password",value="签章使用密码") @RequestParam(required=true) Optional<String> password,@ApiParam(name="secretFree",value="是否免密") @RequestParam(required=true) Optional<Boolean> secretFree) throws Exception{
		CommonResult<String> commonResult = null;
		boolean isSecretFree = secretFree.orElse(false);
		if (!isSecretFree && StringUtil.isEmpty(password.get())){
			return CommonResultUtil.getResult(new CommonResult<>(false,"请输入签章使用密码"));
		}
		String currentUserId = AuthenticationUtil.getCurrentUserId();
		ElectronicSeal electronicSeal = electronicSealManager.getOne(new QueryWrapper<ElectronicSeal>().eq("IS_USE_", 0).eq("USER_ID_", currentUserId));
		if (BeanUtils.isEmpty(electronicSeal)){
			commonResult = new CommonResult<>(false,"您还未设置签章，请在个人信息中设置您的签章");
		}else if (!isSecretFree && !electronicSeal.getPassword().equals(encryptSealPassword(password.get()))){
			commonResult = new CommonResult<>(false,"签章使用密码错误，请重新输入");
		}else{
			commonResult = new CommonResult<>(true,"获取成功！",electronicSeal.getFileId());
		}
		return CommonResultUtil.getResult(commonResult);
	}

	@GetMapping("/getSealByUserId/{userId}")
	@ApiOperation(value = "根据用户ID查询电子签章")
	public CommonResult<ElectronicSeal> getSealByUserId(@PathVariable("userId") String userId){
		// 根据用户ID，查询出当前正在使用的电子签章
		ElectronicSeal electronicSeal = electronicSealManager.getOne(new QueryWrapper<ElectronicSeal>().eq("IS_USE_", 0).eq("USER_ID_", userId));
		if (BeanUtils.isEmpty(electronicSeal)){
			return CommonResult.<ElectronicSeal>ok().message("暂无签章！");
		}
		electronicSeal.setPassword("");
		return CommonResult.<ElectronicSeal>ok().value(electronicSeal);
	}

	@GetMapping("/getSealByCurrentUserId")
	@ApiOperation(value = "获取当前登录用户的电子签章")
	public CommonResult<ElectronicSeal> getCurrentUserSeal(){
		// 获取当前登录用户ID
		String currentUserId = AuthenticationUtil.getCurrentUserId();
		ElectronicSeal electronicSeal = electronicSealManager.getOne(new QueryWrapper<ElectronicSeal>().eq("IS_USE_", 0).eq("USER_ID_", currentUserId));
		// 把密码制空，不返回给前端
		if (BeanUtils.isEmpty(electronicSeal)){
			return CommonResult.<ElectronicSeal>ok().message("暂无签章！");
		}
		electronicSeal.setPassword("");
		return CommonResult.<ElectronicSeal>ok().value(electronicSeal);
	}

	
	@RequestMapping(value="/saveSignatureBatch",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "处理批量导入的用户签章数据", httpMethod = "POST", notes = "处理批量导入的用户签章数据")
	public CommonResult<String> saveSignatureBatch(@ApiParam(name="signatureData",value="导入的用户签章数据",required=true) @RequestBody ImportSignatureObject signatureData) throws Exception{
		CommonResult<String> commonResult = baseService.importSignature(signatureData);
		return CommonResultUtil.getResult(commonResult);
	}
	
	/**
	 * 对签章密码进行加密
	 * @param blankPswd
	 * @return
	 * @throws Exception 
	 */
	private String encryptSealPassword(String blankPswd) throws Exception {
		return EncryptUtil.encrypt(blankPswd);
	}
}
