/*
 *      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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springblade.bank.keypwd.entity.KeyPwd;
import org.springblade.bank.keypwd.vo.KeyPwdVO;
import org.springblade.bank.userlog.entity.UserLog;
import org.springblade.bank.userlog.service.IUserLogService;
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.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.bank.sealhandover.entity.SealHandover;
import org.springblade.bank.sealhandover.vo.SealHandoverVO;
import org.springblade.bank.sealhandover.wrapper.SealHandoverWrapper;
import org.springblade.bank.sealhandover.service.ISealHandoverService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * 業務印章交接登記表 控制器
 *
 * @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;

	/**
	 * 详情
	 */
	@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) {
		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<IPage<SealHandoverVO>> getKeepList(SealHandoverVO sealHandover, Query query) {
		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);
		}

		query.setSize(500);
		IPage<SealHandoverVO> pages = sealHandoverService.selectSealHandoverPage(Condition.getPage(query), sealHandover);
		List<SealHandoverVO> records = pages.getRecords();
		HashSet<Map> set = new HashSet<>();
		for (int i = 0; i < records.size(); i++) {
			SealHandover item = records.get(i);
			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){
				records.remove(i);
				i--;
			}
		}
		return R.data(pages);
	}

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

	/**
	 * 修改 業務印章交接登記表
	 */
	@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();
		Assert.isTrue(sealHandover.getReceiverNo().equals(user.getEhr()), "當前填報人不能作為接收人！請重新選擇！");

		if (isAdd){
			sealHandover.setFillingPerson(currentUser.getUserName());
			sealHandover.setFillingDate(DateUtil.now());
		}

		if (sealHandoverService.saveOrUpdate(sealHandover)){
			userLog.setTableName("sealhandover");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setNewData(JSONUtil.toJsonStr(sealHandover));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());

			if (isAdd){
				userLog.setOperationType("add");
			}else{
				userLog.setOperationType("edit");
				SealHandover old = sealHandoverService.getById(sealHandover.getId());
				userLog.setOldData(JSONUtil.toJsonStr(old));
			}
			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);

		if (sealHandoverService.deleteLogic(idList)){
			// 日誌記錄
			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.setOldData(JSONUtil.toJsonStr(sealHandover));
				userLog.setPersonNo(user.getEhr());
				userLog.setPersonName(user.getName());
				userLogService.save(userLog);
			});
		}
		return R.status(true);
	}

	@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);
	}

}
