/*
 *      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.postchange.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.goodsuse.entity.GoodsUse;
import org.springblade.bank.message.entity.Message;
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.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.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.postchange.entity.PostChange;
import org.springblade.bank.postchange.vo.PostChangeVO;
import org.springblade.bank.postchange.wrapper.PostChangeWrapper;
import org.springblade.bank.postchange.service.IPostChangeService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 網點出納主管及專管員崗位表更記錄表 控制器
 *
 * @author BladeX
 * @since 2021-08-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("bank/postchange")
@Api(value = "網點出納主管及專管員崗位表更記錄表", tags = "網點出納主管及專管員崗位表更記錄表接口")
public class PostChangeController extends BladeController {

	private final IPostChangeService postChangeService;
	private final IUserService userService;
	private final IDeptService deptService;
	private final IUserLogService userLogService;
	private final INoticeService noticeService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入postChange")
	public R<PostChangeVO> detail(PostChange postChange) {
		PostChange detail = postChangeService.getOne(Condition.getQueryWrapper(postChange));
		return R.data(PostChangeWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 網點出納主管及專管員崗位表更記錄表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入postChange")
	public R<IPage<PostChangeVO>> list(PostChange postChange, Query query) {
		IPage<PostChange> pages = postChangeService.page(Condition.getPage(query), Condition.getQueryWrapper(postChange));
		return R.data(PostChangeWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 網點出納主管及專管員崗位表更記錄表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入postChange")
	public R<IPage<PostChangeVO>> page(PostChangeVO postChange, Query query) {
		postChange.setCurrentuserId(AuthUtil.getUser().getUserId());
		if (StringUtils.isNotBlank(postChange.getOrgNostr())){
			List<String> orgNos = Func.toStrList(postChange.getOrgNostr());
			postChange.setOrgNos(orgNos);
		}
		IPage<PostChangeVO> pages = postChangeService.selectPostChangePage(Condition.getPage(query), postChange);

		/*pages.getRecords().forEach(item -> {
			User user = userService.getById(item.getCreateUser());
			item.setCreateUserName(user.getName());
			item.setCreateUserName(user.getEhr());
		});*/

		List<PostChangeVO> records = pages.getRecords();
		List<PostChangeVO> list = new ArrayList<>();
		for (int i = 0; i < records.size(); i++) {
			PostChange item = records.get(i);
			User user = userService.getById(item.getCreateUser());
			PostChangeVO postChangeVO = Objects.requireNonNull(BeanUtil.copy(item, PostChangeVO.class));
			postChangeVO.setCreateUserName(user.getName());
			postChangeVO.setCreateUserNo(user.getEhr());
			list.add(postChangeVO);
		}

		pages.setRecords(list);

		return R.data(pages);
	}

		/**
	 * 修改 網點出納主管及專管員崗位表更記錄表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入postChange")
	public R update(@Valid @RequestBody PostChange postChange) {
		return R.status(postChangeService.updateById(postChange));
	}

	/**
	 * 新增或修改 網點出納主管及專管員崗位表更記錄表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入postChange")
	public R submit(@Valid @RequestBody PostChange postChange) {

		if (postChange.getPersonId() == null || postChange.getPersonNo() == null){
			PostChange setting = postChangeService.getOne(new QueryWrapper<>(new PostChange()).lambda().eq(PostChange::getBankNo, "000").eq(PostChange::getCreateUser, AuthUtil.getUserId()));
			Assert.notNull(setting, "請先設置審批人！");
			postChange.setPersonId(setting.getPersonId());
			postChange.setPersonNo(setting.getPersonNo());
			postChange.setPersonName(setting.getPersonName());
		}

		if (StringUtils.isNotBlank(postChange.getPersonNo())){
			User user = userService.getById(AuthUtil.getUser().getUserId());
			if (user.getEhr().equals(postChange.getPersonNo())){
				Assert.notNull(null, "發佈人和發起人不能為同一人！");
			}
		}

		boolean isAdd = postChange.getId() == null;
		BladeUser currentUser = AuthUtil.getUser();
		User user = userService.getById(currentUser.getUserId());
		Dept dept = deptService.getById(user.getDeptId());
		UserLog userLog = new UserLog();

		postChange.setProcess(2);
		PostChange last = postChangeService.getLastRecord(dept);
		if (isAdd && last != null){
			//上一条记录
			postChange.setPreviousId(last.getId());
		}

		PostChange old = null;
		if (isAdd){
		}else{
			old = postChangeService.getById(postChange.getId());
		}

		if (postChangeService.saveOrUpdate(postChange)){
			userLog.setTableName("postchange");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(postChange));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());

			if (isAdd){
				userLog.setOperationType("add");

				//發送通知
				noticeService.sendPostChangeNotice(postChange, false);
			}else{
				userLog.setOperationType("edit");
				userLog.setOldData(JSONUtil.toJsonStr(old));
				//發送通知
				noticeService.sendPostChangeNotice(postChange, true);
			}
			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();
			PostChange postchange = postChangeService.getById(id);
			userLog.setTableName("postchange");
			userLog.setOperationType("del");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setOldData(JSONUtil.toJsonStr(postchange));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLogList.add(userLog);
		});

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

	/**
	 * 新增 網點出納主管及專管員崗位表更記錄表
	 */
	@PostMapping("/settingSave")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入postChange")
	public R settingSave(@Valid @RequestBody PostChange postChange) {
		PostChange one = postChangeService.getOne(new QueryWrapper<>(new PostChange()).lambda().eq(PostChange::getBankNo, "000").eq(PostChange::getCreateUser, AuthUtil.getUserId()));

		if (one == null){
			postChange.setBankNo("000");
			return R.status(postChangeService.save(postChange));
		}else{
			one.setPersonId(postChange.getPersonId());
			one.setPersonName(postChange.getPersonName());
			one.setPersonNo(postChange.getPersonNo());
			return R.status(postChangeService.updateById(one));
		}
	}

	/**
	 * 获取审批人设置
	 */
	@GetMapping("/getSetting")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取审批人设置", notes = "")
	public R getSetting() {
		PostChange one = postChangeService.getOne(new QueryWrapper<>(new PostChange()).lambda().eq(PostChange::getBankNo, "000").eq(PostChange::getCreateUser, AuthUtil.getUserId()));
		return R.data(one);
	}

	/**
	 * 一鍵移交 網點各項憑證/實物使用及出入庫登記表
	 */
	@PostMapping("/transfer")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "一鍵移交", notes = "传入ids")
	public R transfer(@ApiParam(value = "主键集合", required = true) @RequestParam String ids, @ApiParam(value = "主键集合", required = true) @RequestParam String personNo) {

		User user = userService.getOne(new QueryWrapper<>(new User()).lambda().eq(User::getEhr, personNo));
		Assert.notNull(user, "找不到工號為：" + personNo + "的移交人！");
		List<Long> idList = Func.toLongList(ids);
		AtomicBoolean flag = new AtomicBoolean(true);
		idList.forEach(id -> {
			PostChange postChange = postChangeService.getById(id);
			postChange.setPersonId(user.getId());
			postChange.setPersonNo(user.getEhr());
			postChange.setPersonName(user.getName());
			boolean b = postChangeService.updateById(postChange);
			flag.set(flag.get() && b);
		});

		if (flag.get()){
			//記錄日誌
			User currentUser = userService.getById(AuthUtil.getUserId());
			Dept currentDept = deptService.getById(currentUser.getDeptId());
			UserLog userLog = new UserLog();
			userLog.setTableName("postchange");
			userLog.setBankNo(currentDept.getBankNo());
			userLog.setOrgNo(currentDept.getOrgNo());
			userLog.setOrgName(currentDept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(ids));
			userLog.setPersonNo(currentUser.getEhr());
			userLog.setPersonName(currentUser.getName());
			userLog.setOperationType("transfer");
			userLogService.save(userLog);
		}

		return R.status(true);
	}

	/**
	 * 审批确认
	 */
	@PostMapping("/approve")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "审批确认", notes = "传入id")
	public R approve(@ApiParam(value = "主键集合", required = true) @RequestParam Long id) {
		PostChange postchange = postChangeService.getById(id);
		postchange.setProcess(3);
		postchange.setIsCompleted(1);
		postchange.setApproveTime(DateUtil.now());

		if (postChangeService.updateById(postchange)){
			//記錄日誌
			User user = userService.getById(AuthUtil.getUserId());
			Dept currentDept = deptService.getById(user.getDeptId());
			UserLog userLog = new UserLog();
			userLog.setTableName("postchange");
			userLog.setBankNo(currentDept.getBankNo());
			userLog.setOrgNo(currentDept.getOrgNo());
			userLog.setOrgName(currentDept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(postchange));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLog.setOperationType("approve");
			userLogService.save(userLog);
		}

		return R.status(true);
	}

	/**
	 * 获取审批人设置
	 */
	@GetMapping("/getLastRecord")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取最新一条记录", notes = "")
	public R getLastRecord() {
		Dept dept = deptService.getById(AuthUtil.getDeptId());
		return R.data( postChangeService.getLastRecord(dept));
	}


}
