/*
 *      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.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.keypwd.entity.KeyPwd;
import org.springblade.bank.returns.entity.Returns;
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.log.logger.BladeLogger;
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 org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 自助設備吞沒卡處理 控制器
 *
 * @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;

	/**
	 * 详情
	 */
	@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());
		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);

		if (cardSwallowService.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();
				CardSwallow cardSwallow = cardSwallowService.getById(id);

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

	/**
	 * 審批人設置
	 * @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::getId, 1L));
		if (one == null){
			cardSwallow.setId(1L);
			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::getId, 1L));
		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);

		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::getId, 1L));
			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, "發佈人和發起人不能為同一人！");
			}
		}

		cardSwallow.setProcess(2);
		cardSwallow.setSendStatus("1");//待發送

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

		if (cardSwallowService.saveOrUpdate(cardSwallow)){
			userLog.setTableName("cardswallow");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setNewData(JSONUtil.toJsonStr(cardSwallow));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());

			if (isAdd){
				userLog.setOperationType("add");
			}else{
				userLog.setOperationType("edit");
				CardSwallow old = cardSwallowService.getById(cardSwallow.getId());
				userLog.setOldData(JSONUtil.toJsonStr(old));
			}
			userLogService.save(userLog);
		}
		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("2");
		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("3");
		BladeUser user = AuthUtil.getUser();
		User byId = userService.getById(user.getUserId());

		cardSwallow.setBankConfirmTime(DateUtil.now());
		cardSwallow.setBankConfirmNo(byId.getEhr());
		cardSwallow.setBankConfirmName(user.getUserName());
		return R.status(cardSwallowService.saveOrUpdate(cardSwallow));
	}


}
