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

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.cardswallow.entity.CardSwallow;
import org.springblade.bank.cardswallow.entity.CardSwallowExcel;
import org.springblade.bank.cardswallow.service.ICardSwallowService;
import org.springblade.bank.cardswallow.vo.CardSwallowVO;
import org.springblade.bank.cardswallow.wrapper.CardSwallowWrapper;
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.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.stream.Collectors;

/**
 * 自助設備吞卡資料 控制器
 *
 * @author BladeX
 * @since 2021-08-12
 */
@RestController
@AllArgsConstructor
@RequestMapping("bank/cardswallow")
@Api(value = "自助設備吞卡資料", tags = "自助設備吞卡資料接口")
public class CardSwallowController extends BladeController {

	private final ICardSwallowService cardSwallowService;
	private final IUserService userService;
	private final IDeptService deptService;
	private final IUserLogService userLogService;
	private final IDictService dictService;
	private final INoticeService noticeService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入cardSwallow")
	public R<CardSwallowVO> detail(CardSwallow cardSwallow) {
		CardSwallow detail = cardSwallowService.getOne(Condition.getQueryWrapper(cardSwallow));
		return R.data(CardSwallowWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 自助設備吞卡資料
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入cardSwallow")
	public R<IPage<CardSwallowVO>> list(CardSwallow cardSwallow, Query query) {
		IPage<CardSwallow> pages = cardSwallowService.page(Condition.getPage(query), Condition.getQueryWrapper(cardSwallow));
		return R.data(CardSwallowWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 自助設備吞卡資料
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入cardSwallow")
	public R<IPage<CardSwallowVO>> page(CardSwallowVO cardSwallow, Query query) {
		cardSwallow.setCurrentuserId(AuthUtil.getUser().getUserId());
		cardSwallow.setIsEquipmentTeam("equipmentTeam".equals(AuthUtil.getUserRole()));

		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());
		}
		cardSwallow.setDeptIdList(deptChildIds);

		if (StringUtils.isNotBlank(cardSwallow.getOrgNostr())){
			List<String> orgNos = Func.toStrList(cardSwallow.getOrgNostr());
			cardSwallow.setOrgNos(orgNos);
		}
		if (StringUtils.isNotBlank(cardSwallow.getSendStatus())){
			List<String> statuss = Func.toStrList(cardSwallow.getSendStatus());
			cardSwallow.setSendStatuss(statuss);
		}



		IPage<CardSwallowVO> pages = cardSwallowService.selectCardSwallowPage(Condition.getPage(query), cardSwallow);
		return R.data(pages);
	}

	/**
	 * 新增 自助設備吞卡資料
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入cardSwallow")
	public R save(@Valid @RequestBody CardSwallow cardSwallow) {
		return R.status(cardSwallowService.save(cardSwallow));
	}

	/**
	 * 修改 自助設備吞卡資料
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入cardSwallow")
	public R update(@Valid @RequestBody CardSwallow cardSwallow) {
		return R.status(cardSwallowService.updateById(cardSwallow));
	}

	/**
	 * 新增或修改 自助設備吞卡資料
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入cardSwallow")
	public R submit(@Valid @RequestBody CardSwallow cardSwallow) {
		return R.status(cardSwallowService.saveOrUpdate(cardSwallow));
	}


	/**
	 * 删除 自助設備吞卡資料
	 */
	@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();
			CardSwallow cardSwallow = cardSwallowService.getById(id);
			userLog.setTableName("cardswallow");
			userLog.setOperationType("del");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setOldData(JSONUtil.toJsonStr(cardSwallow));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLogList.add(userLog);
		});

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

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

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

	/**
	 * 上傳數據讀取返回
	 */
	@PostMapping("/readExcel")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "", notes = "")
	public R readExcel(MultipartFile file) {
		List<CardSwallowExcel> 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, CardSwallowExcel.class);
		}catch (IOException e){

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

		read.forEach(item -> {
			String sendBank = item.getSendBank();
			String orgNo = item.getOrgNo();
			Dept one = deptService.getOne(Wrappers.<Dept>query().lambda().eq(Dept::getDeptName, sendBank));
			Dept byOrgNo = deptService.getByOrgNo(orgNo);
			if (one != null){
				item.setSendBank(one.getOrgNo() + " " + one.getDeptName());
			}
			if (byOrgNo != null){
				item.setOrgName(byOrgNo.getDeptName());
			}
		});

		return R.data(read);
	}

	/**
	 * 新增或修改 自助設備吞卡資料
	 */
	@PostMapping("/cardswallowSubmit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入cardSwallow")
	public R cardswallowSubmit(@Valid @RequestBody CardSwallow cardSwallow) {

		// 流程更改，跳過發佈的流程
		/*if (cardSwallow.getPersonId() == null || cardSwallow.getPersonNo() == null){
			CardSwallow setting = cardSwallowService.getOne(new QueryWrapper<>(new CardSwallow()).lambda().eq(CardSwallow::getBankNo, "000").eq(CardSwallow::getCreateUser, AuthUtil.getUserId()));
			Assert.notNull(setting, "請先設置發佈人！");
			cardSwallow.setPersonId(setting.getPersonId());
			cardSwallow.setPersonNo(setting.getPersonNo());
			cardSwallow.setPersonName(setting.getPersonName());
		}
		if (StringUtils.isNotBlank(cardSwallow.getPersonNo())){
			User user = userService.getById(AuthUtil.getUser().getUserId());
			if (user.getEhr().equals(cardSwallow.getPersonNo())){
				Assert.notNull(null, "發佈人和發起人不能為同一人！");
			}
		}*/

		String roleId = AuthUtil.getUser().getRoleId();
		String deptId = AuthUtil.getDeptId();
		List<User> usersByDeptIdsRoleIds = userService.getUsersByDeptIdsRoleIds(Func.toStrList(deptId), 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());
		cardSwallow.setPersonId(StringUtil.join(userIdList));
		cardSwallow.setPersonName(StringUtil.join(userNameList));
		cardSwallow.setPersonNo(StringUtil.join(userEhrList));

		cardSwallow.setProcess(3);	// 待簽收
		cardSwallow.setSendStatus("3");// 待簽收
		Dept dept = deptService.getOne(new QueryWrapper<>(new Dept()).lambda().eq(Dept::getOrgNo, cardSwallow.getSendOrgNo()));
		Assert.notNull(dept, "找不到該機構號【" + cardSwallow.getSendOrgNo() + "】對應的機構！");

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

		CardSwallow old = null;
		if (!isAdd){
			old = cardSwallowService.getById(cardSwallow.getId());
		}

		if (cardSwallowService.saveOrUpdate(cardSwallow)){

			// 更改創建機構信息，實現數據權限控制，只有對應支行才能查看到的數據
			cardSwallow.setCreateDept(dept.getId());
			cardSwallowService.updateById(cardSwallow);

			userLog.setTableName("cardswallow");
			userLog.setBankNo(currentDept.getBankNo());
			userLog.setOrgNo(currentDept.getOrgNo());
			userLog.setOrgName(currentDept.getDeptName());
			userLog.setNewData(JSONUtil.toJsonStr(cardSwallow));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());

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

				//發送通知
//				noticeService.sendCardSwallowNotice(cardSwallow);

			}else{
				userLog.setOperationType("edit");
				userLog.setOldData(JSONUtil.toJsonStr(old));
			}
			userLogService.save(userLog);
		}
		return R.status(true);
	}

	/**
	 * 新增或修改 自助設備吞卡資料
	 */
	@PostMapping("/cardswallowSubmitBatch")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入cardSwallow")
	public R cardswallowSubmitBatch(@Valid @RequestBody List<CardSwallow> list) {
		return R.status(true);
	}


	/**
	 * 發佈
	 */
	@PostMapping("/issue")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入cardSwallow")
	public R issue(@Valid @RequestBody CardSwallow cardSwallow) {
		User createUser = userService.getById(cardSwallow.getCreateUser());
		BladeUser user = AuthUtil.getUser();
		if (user.getUserId().equals(createUser.getId())){
			Assert.notNull(null, "數據導入用戶與確認發送用戶不可為同一人！");
		}
		cardSwallow.setProcess(3);
		cardSwallow.setSendStatus("3"); // 待簽收
		Dept dept = deptService.getOne(new QueryWrapper<>(new Dept()).lambda().eq(Dept::getOrgNo, cardSwallow.getSendOrgNo()));
		Assert.notNull(dept, "找不到該機構號【" + cardSwallow.getSendOrgNo() + "】對應的機構！");
		cardSwallow.setCreateDept(dept.getId());

		return R.status(cardSwallowService.saveOrUpdate(cardSwallow));
	}

	/**
	 * 簽收
	 */
	@PostMapping("/signin")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入cardSwallow")
	public R signin(@Valid @RequestBody CardSwallow cardSwallow) {
		cardSwallow.setProcess(4);
		//没有isComplated字段，后期需要再增加吧
		cardSwallow.setSendStatus("4");
		User user = userService.getById(AuthUtil.getUserId());

		cardSwallow.setBankConfirmTime(DateUtil.now());
		cardSwallow.setBankConfirmNo(user.getEhr());
		cardSwallow.setBankConfirmName(user.getName());

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

	@GetMapping("/getList")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入cardSwallow")
	public R getList(CardSwallowVO cardSwallow) {
		cardSwallow.setCurrentuserId(AuthUtil.getUser().getUserId());
		cardSwallow.setIsEquipmentTeam("equipmentTeam".equals(AuthUtil.getUserRole()));

		if (StringUtils.isNotBlank(cardSwallow.getOrgNostr())){
			List<String> orgNos = Func.toStrList(cardSwallow.getOrgNostr());
			cardSwallow.setOrgNos(orgNos);
		}
		if (StringUtils.isNotBlank(cardSwallow.getSendStatus())){
			List<String> statuss = Func.toStrList(cardSwallow.getSendStatus());
			cardSwallow.setSendStatuss(statuss);
		}

		List<CardSwallow> list = cardSwallowService.getList(cardSwallow);

		list.forEach(item -> {
			String sendStatus = item.getSendStatus();
			String send_status = dictService.getValue("send_status", sendStatus);
			item.setSendStatus(send_status);
		});

		return R.data(list);
	}

}
