package com.artfess.uc.controller;

import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.controller.BaseController;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.AuthenticationUtil;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.EncryptUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.uc.manager.ElectronicSealManager;
import com.artfess.uc.model.ElectronicSeal;
import com.artfess.uc.model.User;
import com.artfess.uc.params.seal.ImportSignatureObject;
import com.artfess.uc.util.ContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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/v1")
@Api(tags="electronicSealController")
@ApiGroup(group= {ApiGroupConsts.GROUP_UC})
public class ElectronicSealController extends BaseController<ElectronicSealManager,ElectronicSeal>{
	@Resource
	ElectronicSealManager electronicSealManager;
	@Autowired
	PasswordEncoder passwordEncoder;

	/**
	 * uc_electronic_seal列表(分页条件查询)数据
	 * @param queryFilter
	 * @return
	 * @throws Exception
	 * PageJson
	 * @exception
	 */
	@PostMapping("/listJson")
	@ApiOperation(value="uc_electronic_seal数据列表", httpMethod = "POST", notes = "获取uc_electronic_seal列表")
	public PageList<ElectronicSeal> list(@ApiParam(name="queryFilter",value="查询对象")@RequestBody QueryFilter queryFilter) throws Exception{
		return electronicSealManager.query(queryFilter);
	}

	/**
	 * uc_electronic_seal明细页面
	 * @param id
	 * @return
	 * @throws Exception
	 * ModelAndView
	 */
	@GetMapping(value="/getJson")
	@ApiOperation(value="uc_electronic_seal数据详情",httpMethod = "GET",notes = "uc_electronic_seal数据详情")
	public ElectronicSeal get(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam String id) throws Exception{
		return electronicSealManager.get(id);
	}

	/**
	 * 新增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{
		String msg = "添加签章成功";
		String currentUserId = electronicSeal.getUserId();
		ElectronicSeal seal = electronicSealManager.getOne(new QueryWrapper<ElectronicSeal>().eq("USER_ID_", currentUserId).eq("IS_USE_", 0));
		if(BeanUtils.isEmpty(seal)){
			electronicSeal.setIsUse(0);
			electronicSeal.setPassword(encryptSealPassword(electronicSeal.getPassword())); // 对密码进行加密处理
			electronicSealManager.create(electronicSeal);
		}else{
			// 将之前签章的状态改掉
			electronicSealManager.setIsUse(seal.getId());
			ElectronicSeal electronicSealNew = new ElectronicSeal();
			electronicSealNew.setUserId(electronicSeal.getUserId());
			electronicSealNew.setIsUse(0);
			electronicSealNew.setFileId(electronicSeal.getFileId());
			if (StringUtil.isEmpty(electronicSeal.getPassword())){
				ElectronicSeal electronicSealOld = electronicSealManager.get(electronicSeal.getId());
				electronicSealNew.setPassword(electronicSealOld.getPassword());
			}else {
				electronicSealNew.setPassword(encryptSealPassword(electronicSeal.getPassword()));
			}
			electronicSealManager.create(electronicSealNew);
		}
		return new CommonResult<String>(msg);
	}

	/**
	 * 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 {
		String msg = "添加签章成功";
		User user = ContextUtil.getCurrentUser();
		if (!user.getPassword().equals(passwordEncoder.encode(electronicSeal.getOldPassWord()))){
			return new CommonResult<>(false,"您输入的登录密码不正确");
		}
		if(StringUtil.isEmpty(electronicSeal.getId())){
			electronicSeal.setIsUse(0);
			electronicSeal.setUserId(user.getId());
			electronicSeal.setPassword(encryptSealPassword(electronicSeal.getPassword())); // 对密码进行加密处理
			electronicSealManager.create(electronicSeal);
		}else{
			if (StringUtil.isEmpty(electronicSeal.getOldPassWord())){
				return new CommonResult<>(false,"请输入登录密码");
			}
			// 判断当前用户是否存在正在使用的签章
			ElectronicSeal seal = electronicSealManager.getOne(new QueryWrapper<ElectronicSeal>().eq("USER_ID_", user.getId()).eq("IS_USE_", 0));
			if (BeanUtils.isNotEmpty(seal)){
				// 拿到旧密码与当前密码进行比对，判断输入是否正确
				// 将之前的签章状态修改掉
				electronicSealManager.setIsUse(electronicSeal.getId());
				ElectronicSeal electronicSealNew = new ElectronicSeal();
				electronicSealNew.setUserId(user.getId());
				electronicSealNew.setIsUse(0);
				electronicSealNew.setFileId(electronicSeal.getFileId());
				if (StringUtil.isNotEmpty(electronicSeal.getPassword())){
					// 再用户输入了密码就修改密码。否则不修改密码，直接使用原密码
					electronicSealNew.setPassword(encryptSealPassword(electronicSeal.getPassword()));
				}else{
					electronicSealNew.setPassword(seal.getPassword());
				}
				electronicSealManager.create(electronicSealNew);
			}else{
				return new CommonResult<>(false,"未获取到正在使用的签章。");
			}
		}
		return new CommonResult<>(msg);
	}

	@PostMapping(value = "mobileUpdate")
	@ApiOperation(value = "手机端更新签章",httpMethod = "POST",notes = "手机端更新签章")
	public CommonResult<String> mobileUpdate(@RequestBody ElectronicSeal electronicSeal) throws Exception {
		if (StringUtil.isEmpty(electronicSeal.getPassword())){
			return new CommonResult<>(false,"请输入签章密码");
		}
		User user = ContextUtil.getCurrentUser();
		ElectronicSeal electronicSealOld = electronicSealManager.getOne(new QueryWrapper<ElectronicSeal>().eq("IS_USE_", 0).eq("USER_ID_", user.getId()));
		if (BeanUtils.isNotEmpty(electronicSealOld)){
			if (!user.getPassword().equals(passwordEncoder.encode(electronicSeal.getOldPassWord()))){
				return new CommonResult<>(false,"您输入的登录密码不正确，不可更新签章");
			}
			electronicSealOld.setIsUse(1);
			electronicSealManager.update(electronicSealOld);
			electronicSeal.setUserId(user.getId());
			electronicSeal.setIsUse(0);
			electronicSeal.setPassword(encryptSealPassword(electronicSeal.getPassword()));
			electronicSealManager.create(electronicSeal);
		}else{
			return new CommonResult<>(false,"您没有签章，请在应用端添加签章后，方可使用");
		}
		return new 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{
		boolean isSecretFree = secretFree.orElse(false);
		if (!isSecretFree && StringUtil.isEmpty(password.get())){
			return 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)|| StringUtil.isEmpty(electronicSeal.getFileId())){
			return new CommonResult<>(false,"您还未设置签章，请在个人信息中设置您的签章");
		}else if (!isSecretFree && !electronicSeal.getPassword().equals(encryptSealPassword(password.get()))){
			return new CommonResult<>(false,"签章使用密码错误，请重新输入");
		}else{
			return new CommonResult<>(true,"获取成功！",electronicSeal.getFileId());
		}
	}


	@GetMapping("/getSealByUserId/{userId}")
	@ApiOperation(value = "根据用户ID查询电子签章")
	public 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 null;
		}
		electronicSeal.setPassword("");
		return electronicSeal;
	}
	@GetMapping("/getSealByCurrentUserId")
	@ApiOperation(value = "获取当前登录用户的电子签章")
	public 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 null;
		}
		electronicSeal.setPassword("");
		return electronicSeal;
	}
	/**
	 * 批量删除uc_electronic_seal记录
	 * @param ids
	 * @throws Exception
	 * @return
	 * @exception
	 */
	@DeleteMapping(value="/remove")
	@ApiOperation(value = "批量删除uc_electronic_seal记录", httpMethod = "DELETE", notes = "批量删除uc_electronic_seal记录")
	public CommonResult<String> removes(@ApiParam(name="ids",value="业务主键数组,多个业务主键之间用逗号分隔", required = true)@RequestParam String...ids) throws Exception{
		electronicSealManager.removeByIds(ids);
		return new CommonResult<String>(true, "批量删除成功");
	}

	@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{
		return baseService.importSignature(signatureData);
	}

	/**
	 * 对签章密码进行加密
	 * @param blankPswd
	 * @return
	 * @throws Exception
	 */
	private String encryptSealPassword(String blankPswd) throws Exception {
		return EncryptUtil.encrypt(blankPswd);
	}
}
