/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.bank.sealhandover.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springblade.bank.keypwd.entity.KeyPwd;
import org.springblade.bank.keypwd.vo.KeyPwdVO;
import org.springblade.bank.sealhandover.entity.SealHandover;
import org.springblade.bank.sealhandover.service.ISealHandoverService;
import org.springblade.bank.sealhandover.vo.SealHandoverVO;
import org.springblade.bank.sealhandover.wrapper.SealHandoverWrapper;
import org.springblade.bank.userlog.entity.UserLog;
import org.springblade.bank.userlog.service.IUserLogService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.desk.service.INoticeService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IDictService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 業務印章交接登記表 控制器
 *
 * @author BladeX
 * @since 2021-08-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("bank/sealhandover")
@Api(value = "業務印章交接登記表", tags = "業務印章交接登記表接口")
public class SealHandoverController extends BladeController {

	private final ISealHandoverService sealHandoverService;
	private final IUserLogService userLogService;
	private final IUserService userService;
	private final IDeptService deptService;
	private final IDictService dictService;
	private final INoticeService noticeService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入sealHandover")
	public R<SealHandoverVO> detail(SealHandover sealHandover) {
		SealHandover detail = sealHandoverService.getOne(Condition.getQueryWrapper(sealHandover));
		return R.data(SealHandoverWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 業務印章交接登記表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入sealHandover")
	public R<IPage<SealHandoverVO>> list(SealHandover sealHandover, Query query) {
		IPage<SealHandover> pages = sealHandoverService.page(Condition.getPage(query), Condition.getQueryWrapper(sealHandover));
		return R.data(SealHandoverWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 業務印章交接登記表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入sealHandover")
	public R<IPage<SealHandoverVO>> page(SealHandoverVO sealHandover, Query query) {

		Long deptId = Long.valueOf(AuthUtil.getDeptId());
		List<Long> deptChildIds = deptService.getDeptChildIds(deptId);
//		deptChildIds.add(deptId);
		Dept dept = deptService.getById(deptId);
		Dept parentDept = deptService.getById(dept.getParentId());
		if (parentDept.getOrgNo().startsWith("999")){
			deptChildIds.add(parentDept.getId());
		}

		sealHandover.setDeptIdList(deptChildIds);
		sealHandover.setCurrentuserId(AuthUtil.getUserId());

		if (StringUtils.isNotBlank(sealHandover.getSealType())){
			List<String> sealTypes = Func.toStrList(sealHandover.getSealType());
			sealHandover.setSealTypes(sealTypes);
		}
		if (StringUtils.isNotBlank(sealHandover.getOrgNostr())){
			List<String> orgNos = Func.toStrList(sealHandover.getOrgNostr());
			sealHandover.setOrgNos(orgNos);
		}

		IPage<SealHandoverVO> pages = sealHandoverService.selectSealHandoverPage(Condition.getPage(query), sealHandover);
		return R.data(pages);
	}

	/**
	 * 自定义分页 業務印章交接登記表
	 */
	@GetMapping("/getKeepList")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入sealHandover")
	public R<List<SealHandoverVO>> getKeepList(SealHandoverVO sealHandover) {

		Long deptId = Long.valueOf(AuthUtil.getDeptId());
		List<Long> deptChildIds = deptService.getDeptChildIds(deptId);
//		deptChildIds.add(deptId);
		Dept dept = deptService.getById(deptId);
		Dept parentDept = deptService.getById(dept.getParentId());
		if (parentDept.getOrgNo().startsWith("999")){
			deptChildIds.add(parentDept.getId());
		}
		sealHandover.setDeptIdList(deptChildIds);
		sealHandover.setCurrentuserId(AuthUtil.getUserId());

		if (StringUtils.isNotBlank(sealHandover.getSealType())){
			List<String> sealTypes = Func.toStrList(sealHandover.getSealType());
			sealHandover.setSealTypes(sealTypes);
		}
		if (StringUtils.isNotBlank(sealHandover.getOrgNostr())){
			List<String> orgNos = Func.toStrList(sealHandover.getOrgNostr());
			sealHandover.setOrgNos(orgNos);
		}

		List<SealHandoverVO> list = sealHandoverService.getKeepList(sealHandover);
		/*List<SealHandover> turnInList = sealHandoverService.getTurnInList();

		HashSet<Map> set = new HashSet<>();
		for (int i = 0; i < list.size(); i++) {
			SealHandover item = list.get(i);
			boolean flag = false;
			for (int j = 0; j < turnInList.size(); j++) {
				SealHandover turnIn = turnInList.get(j);
				if (item.getSealType().equals(turnIn.getSealType()) && item.getSealNo().equals(turnIn.getSealNo())){
					list.remove(i);
					i--;
					flag = true;
					break;
				}
			}
			if (!flag){
				HashMap<String, Object> map = new HashMap<>();
				map.put("bankNo", item.getBankNo());
				map.put("orgNo", item.getOrgNo());
				map.put("sealType", item.getSealType());
				map.put("sealNo", item.getSealNo());
				int size1 = set.size();
				set.add(map);
				if (set.size() == size1){
					list.remove(i);
					i--;
				}
			}
		}*/
		return R.data(list);
	}

	/**
	 * 下载记录用
	 * @param sealHandover
	 * @return
	 */
	@GetMapping("/getList")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入sealHandover")
	public R getList(SealHandoverVO sealHandover) {
		Long deptId = Long.valueOf(AuthUtil.getDeptId());
		List<Long> deptChildIds = deptService.getDeptChildIds(deptId);
//		deptChildIds.add(deptId);
		Dept dept = deptService.getById(deptId);
		Dept parentDept = deptService.getById(dept.getParentId());
		if (parentDept.getOrgNo().startsWith("999")){
			deptChildIds.add(parentDept.getId());
		}

		sealHandover.setDeptIdList(deptChildIds);
		sealHandover.setCurrentuserId(AuthUtil.getUserId());

		if (StringUtils.isNotBlank(sealHandover.getSealType())){
			List<String> sealTypes = Func.toStrList(sealHandover.getSealType());
			sealHandover.setSealTypes(sealTypes);
		}
		if (StringUtils.isNotBlank(sealHandover.getOrgNostr())){
			List<String> orgNos = Func.toStrList(sealHandover.getOrgNostr());
			sealHandover.setOrgNos(orgNos);
		}
		List<SealHandoverVO> list = sealHandoverService.getList(sealHandover);
		for (int i = 0; i < list.size(); i++) {
			SealHandover seal = list.get(i);
			String sealType = seal.getSealType();
			String value = dictService.getValue("seal_type", sealType);
			seal.setSealType(value);
		}
		/*list.forEach(seal -> {
			String sealType = seal.getSealType();
			String value = dictService.getValue("seal_type", sealType);
			seal.setSealType(value);
		});*/
		return R.data(list);
	}

	/**
	 * 获取当前用户所持有的分类，逗号拼接返回
	 * @return
	 */
	@GetMapping("/getCurrentUserKeepList")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取当前用户所持有的分类", notes = "")
	public R getCurrentUserKeepList(){
		SealHandoverVO keyPwd = new SealHandoverVO();
		keyPwd.setReceiverId(AuthUtil.getUserId());
		List<SealHandoverVO> keepList = sealHandoverService.getKeepList(keyPwd);
		List<SealHandoverVO> list = new ArrayList<>();
		for (int i = 0; i < keepList.size(); i++) {
			SealHandover item = keepList.get(i);
			SealHandoverVO vo = new SealHandoverVO();
			BeanUtil.copy(item, vo);
			String sealTypeName = dictService.getValue("seal_type", vo.getSealType());
			vo.setDictValue(sealTypeName + "-" + vo.getSealNo());
			vo.setDictKey(vo.getSealType() + "-" + vo.getSealNo());
			list.add(vo);
		}
		return R.data(list);
	}


	/**
	 * 確認 業務印章交接登記表
	 */
	@PostMapping("/sure")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "確認", notes = "传入sealHandover")
	public R sure(@Valid @RequestBody SealHandover sealHandover) {
		sealHandover.setProcess(3);
		sealHandover.setSureTime(DateUtil.now());
		if (sealHandoverService.updateById(sealHandover)){
			SealHandover keep = sealHandoverService.getKeyOneByOrgNoSealTypeNo(sealHandover.getBankNo(), sealHandover.getOrgNo(), sealHandover.getSealType(), sealHandover.getSealNo());
			Long keepId = null;
			if (keep != null){
				keepId = keep.getId();
			}

			if (keep == null){
				keep = sealHandover;
				keep.setId(null);
				keep.setStatus(2);
			}

			keep.setPid(sealHandover.getId());
			keep.setReceiverId(sealHandover.getReceiverId());
			keep.setReceiverNo(sealHandover.getReceiverNo());
			keep.setReceiverName(sealHandover.getReceiverName());
			keep.setCreateDept(sealHandover.getCreateDept());

			keep.setHandoverDate(sealHandover.getHandoverDate());
			keep.setHandoverPersonId(sealHandover.getHandoverPersonId());
			keep.setHandoverPersonNo(sealHandover.getHandoverPersonNo());
			keep.setHandoverPersonName(sealHandover.getHandoverPersonName());
			keep.setRemark(sealHandover.getRemark());
			keep.setFillingPerson(sealHandover.getHandoverPersonName());
			keep.setFillingDate(sealHandover.getFillingDate());
			keep.setCreateUser(sealHandover.getCreateUser());
			keep.setCreateTime(sealHandover.getCreateTime());
			keep.setSureTime(sealHandover.getSureTime());

			if (sealHandover.getIsTurnIn().equals(1) && keepId != null){
				//上繳，刪除原持有人記錄
				sealHandoverService.removeById(keepId);
				sealHandoverService.saveOrUpdate(sealHandover);
			}else{
				//非上繳，更改印章持有人（接收人信息）
				sealHandoverService.saveOrUpdate(keep);
			}

			User user = userService.getById(AuthUtil.getUserId());
			Dept dept = deptService.getById(user.getDeptId());
			UserLog userLog = new UserLog();
			userLog.setTableName("sealhandover");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(sealHandover));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLog.setOperationType("sure");
			userLogService.save(userLog);

			//發送通知
			noticeService.sendSealNotice(sealHandover, false, true);
		}
		return R.status(true);
	}

	/**
	 * 修改 業務印章交接登記表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入sealHandover")
	public R update(@Valid @RequestBody SealHandover sealHandover) {
		return R.status(sealHandoverService.updateById(sealHandover));
	}

	/**
	 * 新增或修改 業務印章交接登記表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入sealHandover")
	public R submit(@Valid @RequestBody SealHandover sealHandover) {
		boolean isAdd = sealHandover.getId() == null;
		BladeUser currentUser = AuthUtil.getUser();
		User user = userService.getById(currentUser.getUserId());
		Dept dept = deptService.getById(user.getDeptId());
		UserLog userLog = new UserLog();
		if (StringUtils.isNotBlank(sealHandover.getReceiverNo())){
			Assert.isTrue(!sealHandover.getReceiverNo().equals(sealHandover.getHandoverPersonNo()), "交出人不可為接收人！請重新選擇！");
		}

		SealHandover old = null;
		if (isAdd){
			sealHandover.setProcess(2);
			sealHandover.setFillingPerson(user.getName());
			sealHandover.setFillingDate(DateUtil.now());

			//判断该机构下此印章是否有待确认记录
			boolean hasTodo = sealHandoverService.checkTodoByOrgNoSealTypeNo(sealHandover);
			Assert.isTrue(!hasTodo, "該類型印章正處於待確認狀態！");

		}else{
			old = sealHandoverService.getById(sealHandover.getId());
		}
		if (sealHandoverService.saveOrUpdate(sealHandover)){
			User receiver = userService.getById(sealHandover.getReceiverId());
			if (sealHandover.getIsTurnIn().equals(0) && !sealHandover.getCreateDept().equals(Long.valueOf(receiver.getDeptId()))){
				sealHandover.setCreateDept(Long.valueOf(receiver.getDeptId()));
				sealHandoverService.updateById(sealHandover);
			}

			userLog.setTableName("sealhandover");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(sealHandover));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());

			if (isAdd){
				if (sealHandover.getIsTurnIn().equals(1)){
					userLog.setOperationType("turnin");
				}else{
					userLog.setOperationType("add");
				}

				//發送通知
				noticeService.sendSealNotice(sealHandover, false, false);
			}else{
				userLog.setOperationType("edit");
				userLog.setOldData(JSONUtil.toJsonStr(old));
				//發送通知
				noticeService.sendSealNotice(sealHandover, true, false);
			}
			userLogService.save(userLog);

		}

		return R.status(true);
	}


	/**
	 * 删除 業務印章交接登記表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		List<UserLog> userLogList = new ArrayList<>();
		// 日誌記錄
		BladeUser currentUser = AuthUtil.getUser();
		User user = userService.getById(currentUser.getUserId());
		Dept dept = deptService.getById(user.getDeptId());
		idList.forEach(id -> {
			UserLog userLog = new UserLog();
			SealHandover sealHandover = sealHandoverService.getById(id);

			userLog.setTableName("sealhandover");
			userLog.setOperationType("del");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setOldData(JSONUtil.toJsonStr(sealHandover));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLogList.add(userLog);
		});

		return R.status(sealHandoverService.deleteLogic(idList) && userLogService.saveBatch(userLogList));
	}

	/**
	 * 根據交接日期來排序，判斷最新一條記錄
	 * @param sealNo
	 * @param sealType
	 * @param orgNo
	 * @return
	 */
	@GetMapping("/getByNoAndType")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取最新一条记录", notes = "传入category,type")
	public R getByNoAndType(@ApiParam(required = true) @RequestParam String sealNo, @ApiParam(required = true) @RequestParam String sealType, @ApiParam(required = true) @RequestParam String orgNo){
		LambdaQueryWrapper<SealHandover> eq = new QueryWrapper<>(new SealHandover()).lambda().eq(SealHandover::getSealNo, sealNo)
			.eq(SealHandover::getSealType, sealType).eq(SealHandover::getOrgNo, orgNo).orderByDesc(SealHandover::getFillingDate);
		List<SealHandover> list = sealHandoverService.list(eq);
		if (list != null && list.size() > 0){
			return R.data(list.get(0));
		}
		return R.data(null);
	}

	/**
	 * 業務印章持有量匯總表
	 * @return
	 */
	@GetMapping("/getOrgsSealhandoverCount")
	public R getOrgsSealhandoverCount(){
		Map data = new HashMap();
		Dept currDept = deptService.getById(AuthUtil.getDeptId());
		List<Long> deptChildIds = deptService.getDeptChildIds(currDept.getId());

		List<Dict> sealList = dictService.getList("seal_type");
		List sealData = new ArrayList();
		deptChildIds.forEach(deptId -> {
			Dept dept = deptService.getById(deptId);
			if (!dept.getOrgNo().startsWith("999")){
				Map map = this.getKeepCountByDept(dept);
				if (map != null){
					sealData.add(map);
				}
			}
		});
		data.put("sealTypeList", sealList);
		data.put("sealData", sealData);
		return R.data(data);
	}

	/**
	 * 業務印章持有量匯總表-支行
	 * @param dept
	 * @return
	 */
	private Map getKeepCountByDept(Dept dept){
		Map map = new HashMap();
		map.put("orgName", dept.getDeptName());
		SealHandoverVO sealHandoverVO = new SealHandoverVO();
		sealHandoverVO.setOrgNostr(dept.getOrgNo());
		R<List<SealHandoverVO>> keepListR = this.getKeepList(sealHandoverVO);
		List<SealHandoverVO> keepList = keepListR.getData();
		if (keepList.size() > 0){
			for (int i = 0; i < keepList.size(); i++) {
				SealHandover item = keepList.get(i);
				String key = "seal_type" + item.getSealType();
				if (map.containsKey(key)){
					map.put(key, Integer.valueOf(map.get(key).toString()) + 1);
				}else{
					map.put(key, 1);
				}
			}
		}
		return map;
	}

}
