/*
 *      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.returns.controller;

import cn.hutool.json.JSONUtil;
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.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springblade.bank.returns.entity.Returns;
import org.springblade.bank.returns.entity.ReturnsExcel;
import org.springblade.bank.returns.service.IReturnsService;
import org.springblade.bank.returns.vo.ReturnsVO;
import org.springblade.bank.returns.wrapper.ReturnsWrapper;
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.excel.util.ExcelUtil;
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.entity.Notice;
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 org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 新開戶退件登記表 控制器
 *
 * @author BladeX
 * @since 2021-08-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("bank/returns")
@Api(value = "新開戶退件登記表", tags = "新開戶退件登記表接口")
public class ReturnsController extends BladeController {

	private final IReturnsService returnsService;
	private final IDeptService deptService;
	private final IUserService userService;
	private final IUserLogService userLogService;
	private final IDictService dictService;
	private final INoticeService noticeService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入returns")
	public R<ReturnsVO> detail(Returns returns) {
		Returns detail = returnsService.getOne(Condition.getQueryWrapper(returns));
		return R.data(ReturnsWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 新開戶退件登記表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入returns")
	public R<IPage<ReturnsVO>> list(Returns returns, Query query) {
		IPage<Returns> pages = returnsService.page(Condition.getPage(query), Condition.getQueryWrapper(returns));
		return R.data(ReturnsWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 新開戶退件登記表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入returns")
	public R<IPage<ReturnsVO>> page(ReturnsVO returns, 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());
		}
		returns.setDeptIdList(deptChildIds);
		returns.setCurrentuserId(AuthUtil.getUser().getUserId());

		if (StringUtils.isNotBlank(returns.getOrgNostr())){
			List<String> orgNos = Func.toStrList(returns.getOrgNostr());
			returns.setOrgNos(orgNos);
		}

		IPage<ReturnsVO> pages = returnsService.selectReturnsPage(Condition.getPage(query), returns);
		return R.data(pages);
	}

	/**
	 * 新增 新開戶退件登記表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入returns")
	public R save(@Valid @RequestBody Returns returns) {
		return R.status(returnsService.save(returns));
	}

	/**
	 * 修改 新開戶退件登記表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入returns")
	public R update(@Valid @RequestBody Returns returns) {
		return R.status(returnsService.updateById(returns));
	}

	/**
	 * 新增或修改 新開戶退件登記表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入returns")
	public R submit(@Valid @RequestBody Returns returns) {

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

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

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

		Returns old = null;
		if (isAdd){
		}else{
			old = returnsService.getById(returns.getId());
		}

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

			if (isAdd){
				userLog.setOperationType("upload");
			}else{
				userLog.setOperationType("edit");

				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);
		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();
			Returns returns = returnsService.getById(id);
			userLog.setTableName("returns");
			userLog.setOperationType("del");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setOldData(JSONUtil.toJsonStr(returns));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLogList.add(userLog);
		});

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

	/**
	 *
	 */
	@PostMapping("/readExcel")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "", notes = "")
	public R readExcel(MultipartFile file) {
		List<ReturnsExcel> read = null;
		try {
			InputStream is = file.getInputStream();
			Workbook workbook = new XSSFWorkbook(is);
			int i = 0;
			Sheet sheet = workbook.getSheetAt(i);
			while (workbook.isSheetHidden(i)){
				sheet = workbook.getSheetAt(++i);
			}
			read = ExcelUtil.read(file, i, ReturnsExcel.class);
		}catch (IOException e){

		}
//		List<ReturnsExcel> read = MyExcelUtil.readReturnsExcel(file);

		return R.data(read);
	}

	/**
	 *
	 */
	@PostMapping("/returnsSubmit")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "", notes = "")
	public R returnsSubmit(@Valid @RequestBody Returns returns) {

		String roleId = AuthUtil.getUser().getRoleId();
		List<User> usersByDeptIdsRoleIds = userService.getUsersByDeptIdsRoleIds(null, Func.toStrList(roleId));
		List<User> userList = new ArrayList<>();
		usersByDeptIdsRoleIds.forEach(item -> {
			if (!item.getId().equals(AuthUtil.getUserId())){
				userList.add(item);
			}
		});
		List<Long> userIdList = userList.stream().map(user -> user.getId()).collect(Collectors.toList());
		List<String> userNameList = userList.stream().map(user -> user.getName()).collect(Collectors.toList());
		List<String> userEhrList = userList.stream().map(user -> user.getEhr()).collect(Collectors.toList());
		returns.setPersonId(StringUtil.join(userIdList));
		returns.setPersonName(StringUtil.join(userNameList));
		returns.setPersonNo(StringUtil.join(userEhrList));

		/*if (returns.getPersonId() == null || returns.getPersonNo() == null){
			Returns setting = returnsService.getOne(new QueryWrapper<>(new Returns()).lambda().eq(Returns::getBankNo, "000").eq(Returns::getCreateUser, AuthUtil.getUserId()));
			Assert.notNull(setting, "請先設置發佈人！");
			returns.setPersonId(setting.getPersonId());
			returns.setPersonNo(setting.getPersonNo());
			returns.setPersonName(setting.getPersonName());
		}

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

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

		Returns old = null;
		if (isAdd){
		}else{
			old = returnsService.getById(returns.getId());
		}

		Dept byOrgNo = deptService.getByOrgNo(returns.getOrgNo());
		if (byOrgNo != null){
			returns.setOrgName(byOrgNo.getDeptName());
		}

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

			if (isAdd){
				userLog.setOperationType("upload");
			}else{
				userLog.setOperationType("edit");

				userLog.setOldData(JSONUtil.toJsonStr(old));
			}
			userLogService.save(userLog);

		}

		return R.status(true);
	}

	/**
	 * 發佈
	 */
	@PostMapping("/issue")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "returns")
	public R issue(@Valid @RequestBody Returns returns) {

		returns.setProcess(3);
		Dept dept = deptService.getOne(new QueryWrapper<>(new Dept()).lambda().eq(Dept::getOrgNo, returns.getSubOrgNo()));
		Assert.notNull(dept, "找不到該機構號【" + returns.getSubOrgNo() + "】對應的機構！");
		returns.setCreateDept(dept.getId());

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

			//發送通知
//			noticeService.sendReturnsNotice(returns);

		}

		return R.status(true);
	}



	/**
	 * 審核確認
	 */
	@PostMapping("/returnsApprove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "", notes = "")
	public R returnsApprove(@Valid @RequestBody Returns returns) {
		User user = userService.getById(AuthUtil.getUserId());
		Dept dept = deptService.getOne(new QueryWrapper<>(new Dept()).lambda().eq(Dept::getOrgNo, returns.getSubOrgNo()));
		Assert.notNull(dept, "找不到該機構號【" + returns.getSubOrgNo() + "】對應的機構！");
		returns.setCreateDept(dept.getId());

		returns.setProcess(4);
		returns.setIsCompleted(1);
		returns.setBankConfirmName(user.getName());
		returns.setBankConfirmNo(user.getEhr());
		returns.setBankConfirmTime(DateUtil.now());

		if (returnsService.updateById(returns)){
			//記錄日誌
			Dept currentDept = deptService.getById(user.getDeptId());
			UserLog userLog = new UserLog();
			userLog.setTableName("returns");
			userLog.setBankNo(currentDept.getBankNo());
			userLog.setOrgNo(currentDept.getOrgNo());
			userLog.setOrgName(currentDept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(returns));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLog.setOperationType("approve");
			userLogService.save(userLog);
		}
		return R.status(true);
	}

	/**
	 * 審批人設置
	 * @param returns
	 * @return
	 */
	@PostMapping("/settingSave")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入postChange")
	public R settingSave(@Valid @RequestBody Returns returns) {
		Returns one = returnsService.getOne(new QueryWrapper<>(new Returns()).lambda().eq(Returns::getBankNo, "000").eq(Returns::getCreateUser, AuthUtil.getUserId()));
		if (one == null){
			returns.setBankNo("000");
			return R.status(returnsService.save(returns));
		}else{
			one.setPersonId(returns.getPersonId());
			one.setPersonName(returns.getPersonName());
			one.setPersonNo(returns.getPersonNo());
			return R.status(returnsService.updateById(one));
		}
	}

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

	@GetMapping("/getList")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入returns")
	public R getList(ReturnsVO returns) {
		returns.setCurrentuserId(AuthUtil.getUser().getUserId());
		if (StringUtils.isNotBlank(returns.getOrgNostr())){
			List<String> orgNos = Func.toStrList(returns.getOrgNostr());
			returns.setOrgNos(orgNos);
		}

		List<Returns> list = returnsService.getList(returns);
		List<ReturnsVO> mapList = new ArrayList<>();

		list.forEach(item -> {
			item.setIsPublic(dictService.getValue("business_type", item.getIsPublic()));
			item.setHandlingStatus(dictService.getValue("processing_status", item.getHandlingStatus()));
			Integer status = item.getStatus();
			String value = dictService.getValue("returns_status", status + "");
			item.setStatus(null);
			ReturnsVO returnsVO = new ReturnsVO();
			BeanUtil.copy(item, returnsVO);
			returnsVO.setReturnStatus(value);
			mapList.add(returnsVO);
		});

		return R.data(mapList);
	}

}
