/*
 *      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 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.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.common.utils.MyExcelUtil;
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.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-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;

	/**
	 * 详情
	 */
	@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) {
		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) {
		return R.status(returnsService.saveOrUpdate(returns));
	}


	/**
	 * 删除 新開戶退件登記表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(returnsService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 *
	 */
	@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) {

		if (returns.getPersonId() == null || returns.getPersonNo() == null){
			Returns setting = returnsService.getOne(new QueryWrapper<>(new Returns()).lambda().eq(Returns::getId, 1L));
			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, "發佈人和發起人不能為同一人！");
			}
		}


		returns.setProcess(2);
		boolean save = returnsService.saveOrUpdate(returns);
		return R.status(save);
	}

	/**
	 * 發佈
	 */
	@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());

		return R.status(returnsService.saveOrUpdate(returns));
	}

	/**
	 * 審核確認
	 */
	@PostMapping("/returnsApprove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "", notes = "")
	public R returnsApprove(@Valid @RequestBody Returns returns) {
		BladeUser user = AuthUtil.getUser();
		User currentUser = userService.getById(user.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(currentUser.getName());
		returns.setBankConfirmNo(currentUser.getEhr());
		returns.setBankConfirmTime(DateUtil.now());

		boolean result = returnsService.updateById(returns);
		return R.status(result);
	}

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


}
