/*
 *      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.keypwd.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.service.IKeyPwdService;
import org.springblade.bank.keypwd.vo.KeyPwdVO;
import org.springblade.bank.keypwd.wrapper.KeyPwdWrapper;
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.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 javax.validation.Valid;
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/keypwd")
@Api(value = "網點鎖匙/密碼登記表", tags = "網點鎖匙/密碼登記表接口")
public class KeyPwdController extends BladeController {

	private final IKeyPwdService keyPwdService;
	private final IUserLogService userLogService;
	private final IUserService userService;
	private final IDeptService deptService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入keyPwd")
	public R<KeyPwdVO> detail(KeyPwd keyPwd) {
		KeyPwd detail = keyPwdService.getOne(Condition.getQueryWrapper(keyPwd));
		return R.data(KeyPwdWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 網點鎖匙/密碼登記表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入keyPwd")
	public R<IPage<KeyPwdVO>> list(KeyPwd keyPwd, Query query) {
		IPage<KeyPwd> pages = keyPwdService.page(Condition.getPage(query), Condition.getQueryWrapper(keyPwd));
		return R.data(KeyPwdWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 網點鎖匙/密碼登記表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入keyPwd")
	public R<IPage<KeyPwdVO>> page(KeyPwdVO keyPwd, Query query) {

		if (StringUtils.isNotBlank(keyPwd.getCategory())){
			List<String> categorys = Func.toStrList(keyPwd.getCategory());
			keyPwd.setCategorys(categorys);
		}
		if (StringUtils.isNotBlank(keyPwd.getOrgNostr())){
			List<String> orgNos = Func.toStrList(keyPwd.getOrgNostr());
			keyPwd.setOrgNos(orgNos);
		}

		IPage<KeyPwdVO> pages = keyPwdService.selectKeyPwdPage(Condition.getPage(query), keyPwd);
		return R.data(pages);
	}

	/**
	 * 自定义分页 網點鎖匙/密碼登記表
	 */
	@GetMapping("/getKeepList")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入keyPwd")
	public R<IPage<KeyPwdVO>> getKeepList(KeyPwdVO keyPwd, Query query) {

		if (StringUtils.isNotBlank(keyPwd.getCategory())){
			List<String> categorys = Func.toStrList(keyPwd.getCategory());
			keyPwd.setCategorys(categorys);
		}
		if (StringUtils.isNotBlank(keyPwd.getOrgNostr())){
			List<String> orgNos = Func.toStrList(keyPwd.getOrgNostr());
			keyPwd.setOrgNos(orgNos);
		}

		query.setSize(500);
		IPage<KeyPwdVO> pages = keyPwdService.selectKeyPwdPage(Condition.getPage(query), keyPwd);
		List<KeyPwdVO> records = pages.getRecords();
		HashSet<Map> set = new HashSet<>();
		for (int i = 0; i < records.size(); i++) {
			KeyPwd item = records.get(i);
			HashMap<String, Object> map = new HashMap<>();
			map.put("bankNo", item.getBankNo());
			map.put("orgNo", item.getOrgNo());
			map.put("category", item.getCategory());
			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 = "传入keyPwd")
	public R save(@Valid @RequestBody KeyPwd keyPwd) {
		return R.status(keyPwdService.save(keyPwd));
	}

	/**
	 * 修改 網點鎖匙/密碼登記表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入keyPwd")
	public R update(@Valid @RequestBody KeyPwd keyPwd) {
		return R.status(keyPwdService.updateById(keyPwd));
	}

	/**
	 * 新增或修改 網點鎖匙/密碼登記表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入keyPwd")
	public R submit(@Valid @RequestBody KeyPwd keyPwd) {


		boolean isAdd = keyPwd.getId() == null;
		BladeUser currentUser = AuthUtil.getUser();
		User user = userService.getById(currentUser.getUserId());
		Dept dept = deptService.getById(user.getDeptId());
		UserLog userLog = new UserLog();
		Assert.isTrue(keyPwd.getReceiverNo().equals(user.getEhr()), "當前填報人不能作為接收人！請重新選擇！");

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

		if (keyPwdService.saveOrUpdate(keyPwd)){
			userLog.setTableName("keypwd");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setNewData(JSONUtil.toJsonStr(keyPwd));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());

			if (isAdd){
				userLog.setOperationType("add");
			}else{
				userLog.setOperationType("edit");
				KeyPwd old = keyPwdService.getById(keyPwd.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 (keyPwdService.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();
				KeyPwd keyPwd = keyPwdService.getById(id);

				userLog.setTableName("keypwd");
				userLog.setOperationType("del");
				userLog.setBankNo(dept.getBankNo());
				userLog.setOrgNo(dept.getOrgNo());
				userLog.setOldData(JSONUtil.toJsonStr(keyPwd));
				userLog.setPersonNo(user.getEhr());
				userLog.setPersonName(user.getName());
				userLogService.save(userLog);
			});
		}
		return R.status(true);
	}

	@GetMapping("/getByCategoryAndType")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取最新一条记录", notes = "传入category,type")
	public R getByCategoryAndType(@ApiParam(required = true) @RequestParam String category, @ApiParam(required = true) @RequestParam String orgNo){
		LambdaQueryWrapper<KeyPwd> eq = new QueryWrapper<>(new KeyPwd()).lambda().eq(KeyPwd::getCategory, category)
			.eq(KeyPwd::getOrgNo, orgNo).orderByDesc(KeyPwd::getFillingDate);
		List<KeyPwd> list = keyPwdService.list(eq);
		if (list != null && list.size() > 0){
			return R.data(list.get(0));
		}
		return R.data(null);
	}

}
