/*
 *      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.common.cache.DictCache;
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.core.tool.utils.StringUtil;
import org.springblade.modules.desk.service.INoticeService;
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.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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 網點鎖匙/密碼登記表 控制器
 *
 * @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;
	private final IDictService dictService;
	private final INoticeService noticeService;


//	@Autowired
//	private ApplicationContext applicationContext;

	/**
	 * 详情
	 */
	@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) {
		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());
		}
		keyPwd.setDeptIdList(deptChildIds);
		keyPwd.setCurrentuserId(AuthUtil.getUserId());

		/*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<List<KeyPwd>> getKeepList(KeyPwdVO keyPwd) {
		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());
		}
		keyPwd.setDeptIdList(deptChildIds);
		keyPwd.setCurrentuserId(AuthUtil.getUserId());

		/*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);
		}

		List<KeyPwd> list = keyPwdService.getKeepList(keyPwd);
		/*HashSet<Map> set = new HashSet<>();
		for (int i = 0; i < list.size(); i++) {
			KeyPwd item = list.get(i);
			String[] split = item.getCategory().split(",");
			//去掉多选的，因为在确认的时候，多选的已经分解了
			if (split.length > 1){
				list.remove(i);
				i--;
				continue;
			}
			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){
				list.remove(i);
				i--;
			}
		}*/

		return R.data(list);
	}

	/**
	 * 确认 網點鎖匙/密碼登記表
	 */
	@PostMapping("/sure")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "确认", notes = "传入keyPwd")
	public R sure(@Valid @RequestBody KeyPwd keyPwd) {
		keyPwd.setProcess(3);
		keyPwd.setSureTime(DateUtil.now());
		if (keyPwdService.updateById(keyPwd)){

			String[] split = keyPwd.getCategory().split(",");
			//如有多选则分解保存，status=2做持有人标识，pid为记录的原id
			if (split.length > 0){
				for (int i = 0; i < split.length; i++) {
					String category = split[i];

					KeyPwd keep = keyPwdService.getKeepOneByOrgNoCategory(keyPwd.getBankNo(), keyPwd.getOrgNo(), category);
					if (keep == null){
						keep = keyPwd;
						keep.setId(null);
						keep.setStatus(2);
						keep.setCategory(category);
					}

					keep.setPid(keyPwd.getId());
					keep.setReceiverId(keyPwd.getReceiverId());
					keep.setReceiverNo(keyPwd.getReceiverNo());
					keep.setReceiverName(keyPwd.getReceiverName());
					keep.setHandoverDate(keyPwd.getHandoverDate());
					keep.setHandoverPersonName(keyPwd.getHandoverPersonName());
					keep.setHandoverPersonId(keyPwd.getHandoverPersonId());
					keep.setHandoverPersonNo(keyPwd.getHandoverPersonNo());
					keep.setFillingPerson(keyPwd.getHandoverPersonName());
					keep.setFillingDate(keyPwd.getFillingDate());
					keep.setCreateUser(keyPwd.getCreateUser());
					keep.setCreateTime(keyPwd.getCreateTime());
					keep.setSureTime(keyPwd.getSureTime());

					keyPwdService.saveOrUpdate(keep);
				}
			}

			User user = userService.getById(AuthUtil.getUserId());
			Dept dept = deptService.getById(user.getDeptId());

			UserLog userLog = new UserLog();
			userLog.setTableName("keypwd");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(keyPwd));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLog.setOperationType("sure");
			userLogService.save(userLog);

			//發送通知
			noticeService.sendKeyPwdNotice(keyPwd, false, true);

		}
		return R.status(true);
	}

	/**
	 * 修改 網點鎖匙/密碼登記表
	 */
	@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) {

		if (keyPwd.getIsTurnIn() == 1){
//			keyPwd.setProcess(3); //已确认，直接完结流程
			return R.status(keyPwdService.turnIn(keyPwd));
		}else {
			keyPwd.setProcess(2); //待确认
		}

		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.getHandoverPersonNo().equals(keyPwd.getReceiverNo()), "交出人不可為接收人！請重新選擇！");

		KeyPwd old = null;
		if (isAdd){
			keyPwd.setFillingPerson(user.getName());
			keyPwd.setFillingDate(DateUtil.now());
		}else{
			old = keyPwdService.getById(keyPwd.getId());
		}

		if (keyPwdService.saveOrUpdate(keyPwd)){
			User receiver = userService.getById(keyPwd.getReceiverId());
			if (receiver != null && !keyPwd.getCreateDept().equals(Long.valueOf(receiver.getDeptId()))){
				keyPwd.setCreateDept(Long.valueOf(receiver.getDeptId()));
				keyPwdService.updateById(keyPwd);
			}

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

			if (isAdd){
				userLog.setOperationType("add");
				//發送通知
				noticeService.sendKeyPwdNotice(keyPwd, false, keyPwd.getIsTurnIn().equals(1));
			}else {
				userLog.setOperationType("edit");
				userLog.setOldData(JSONUtil.toJsonStr(old));
				//發送通知 - 編輯
				noticeService.sendKeyPwdNotice(keyPwd, true, false);
				/*Notice notice = new Notice();
				notice.setTitle("test");
				HangxinNoticeEvent hangxinNoticeEvent = new HangxinNoticeEvent(notice);
				eventPublisher.publishEvent(hangxinNoticeEvent);*/
			}
			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();
			KeyPwd keyPwd = keyPwdService.getById(id);

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

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

	/**
	 * 根據交接日期來排序，判斷最新一條記錄
	 * @param category
	 * @param orgNo
	 * @return
	 */
	@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::getHandoverDate);
		List<KeyPwd> list = keyPwdService.list(eq);
		if (list != null && list.size() > 0){
			return R.data(list.get(0));
		}
		return R.data(null);
	}

	/**
	 * 获取当前用户所持有的分类，逗号拼接返回
	 * @return
	 */
	@GetMapping("/getCurrentUserKeepCategory")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取当前用户所持有的分类", notes = "")
	public R getCurrentUserKeepCategory(){
		KeyPwdVO keyPwd = new KeyPwdVO();
		keyPwd.setReceiverId(AuthUtil.getUserId());
		List<KeyPwd> keepList = keyPwdService.getKeepList(keyPwd);
		String categorys = keepList.stream().map(item -> item.getCategory()).collect(Collectors.joining(","));
		return R.data(categorys);
	}

	@GetMapping("/getList")
	public R getList(KeyPwdVO keyPwd){
		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());
		}
		keyPwd.setDeptIdList(deptChildIds);
		keyPwd.setCurrentuserId(AuthUtil.getUserId());

		/*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);
		}
		keyPwd.setStatus(1);
		List<KeyPwd> list = keyPwdService.getList(keyPwd);

		list.forEach(item -> {
			List<String> categoryStrList = new ArrayList<>();
			String[] categorys = item.getCategory().split(",");
			for (int i = 0; i < categorys.length; i++) {
				String category = categorys[i];
				String value = dictService.getValue("key_type", category);
				String[] split = category.split("_");
				String key_type = dictService.getValue("key_type", split[0] + "_" + split[1] + "_" + split[2]);
				categoryStrList.add(key_type + "-" + value);
			}
			item.setCategory(StringUtil.join(categoryStrList, " | "));
		});

		return R.data(list);
	}
}
