/*
 *      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.goodsuse.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.cardswallow.entity.CardSwallow;
import org.springblade.bank.keypwd.entity.KeyPwd;
import org.springblade.bank.postchange.entity.PostChange;
import org.springblade.bank.sealhandover.entity.SealHandover;
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.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.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.bank.goodsuse.entity.GoodsUse;
import org.springblade.bank.goodsuse.vo.GoodsUseVO;
import org.springblade.bank.goodsuse.wrapper.GoodsUseWrapper;
import org.springblade.bank.goodsuse.service.IGoodsUseService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;

/**
 * 網點各項憑證/實物使用及出入庫登記表 控制器
 *
 * @author BladeX
 * @since 2021-08-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("bank/goodsuse")
@Api(value = "網點各項憑證/實物使用及出入庫登記表", tags = "網點各項憑證/實物使用及出入庫登記表接口")
public class GoodsUseController extends BladeController {

	private final IGoodsUseService goodsUseService;
	private final IUserService userService;
	private final IDeptService deptService;
	private final IUserLogService userLogService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入goodsUse")
	public R<GoodsUseVO> detail(GoodsUse goodsUse) {
		GoodsUse detail = goodsUseService.getOne(Condition.getQueryWrapper(goodsUse));
		return R.data(GoodsUseWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 網點各項憑證/實物使用及出入庫登記表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入goodsUse")
	public R<IPage<GoodsUseVO>> list(GoodsUse goodsUse, Query query) {
		IPage<GoodsUse> pages = goodsUseService.page(Condition.getPage(query), Condition.getQueryWrapper(goodsUse));
		return R.data(GoodsUseWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 網點各項憑證/實物使用及出入庫登記表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入goodsUse")
	public R<IPage<GoodsUseVO>> page(GoodsUseVO goodsUse, Query query) {
		goodsUse.setCurrentuserId(AuthUtil.getUser().getUserId());
		if (StringUtils.isNotBlank(goodsUse.getType())){
			List<String> types = Func.toStrList(goodsUse.getType());
			goodsUse.setTypes(types);
		}

		if (StringUtils.isNotBlank(goodsUse.getOrgNostr())){
			List<String> orgNos = Func.toStrList(goodsUse.getOrgNostr());
			goodsUse.setOrgNos(orgNos);
		}
		if ("manager".equals(AuthUtil.getUserRole()) || "admin".equals(AuthUtil.getUserRole()) || "administrator".equals(AuthUtil.getUserRole())){
			goodsUse.setIsManager(true);
		}

		IPage<GoodsUseVO> pages = goodsUseService.selectGoodsUsePage(Condition.getPage(query), goodsUse);
		return R.data(pages);
	}

	/**
	 * 新增 網點各項憑證/實物使用及出入庫登記表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入goodsUse")
	public R save(@Valid @RequestBody GoodsUse goodsUse) {
		return R.status(goodsUseService.save(goodsUse));
	}

	/**
	 * 修改 網點各項憑證/實物使用及出入庫登記表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入goodsUse")
	public R update(@Valid @RequestBody GoodsUse goodsUse) {
		return R.status(goodsUseService.updateById(goodsUse));
	}

	/**
	 * 新增或修改 網點各項憑證/實物使用及出入庫登記表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入goodsUse")
	public R submit(@Valid @RequestBody GoodsUse goodsUse) {

		if (goodsUse.getPersonId() == null || goodsUse.getPersonNo() == null){
			GoodsUse setting = goodsUseService.getOne(new QueryWrapper<>(new GoodsUse()).lambda().eq(GoodsUse::getId, 1L));
			Assert.notNull(setting, "請先設置確認人！");
			goodsUse.setPersonId(setting.getPersonId());
			goodsUse.setPersonNo(setting.getPersonNo());
			goodsUse.setPersonName(setting.getPersonName());
		}

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


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

		if (isAdd){
			goodsUse.setFillingDate(DateUtil.now());
			goodsUse.setFillingNo(user.getEhr());
			goodsUse.setFillingName(user.getName());
		}

		if (goodsUseService.saveOrUpdate(goodsUse)){
			userLog.setTableName("goodsuse");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setNewData(JSONUtil.toJsonStr(goodsUse));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());

			if (isAdd){
				userLog.setOperationType("add");
			}else{
				userLog.setOperationType("edit");
				GoodsUse old = goodsUseService.getById(goodsUse.getId());
				userLog.setOldData(JSONUtil.toJsonStr(old));
			}
			userLogService.save(userLog);

		}

		return R.status(goodsUseService.saveOrUpdate(goodsUse));
	}


	/**
	 * 删除 網點各項憑證/實物使用及出入庫登記表
	 */
	@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 (goodsUseService.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();
				GoodsUse goodsUse = goodsUseService.getById(id);

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

	/**
	 * 一鍵移交 網點各項憑證/實物使用及出入庫登記表
	 */
	@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);
		idList.forEach(id -> {
			GoodsUse goodsUse = goodsUseService.getById(id);
			goodsUse.setPersonId(user.getId());
			goodsUse.setPersonNo(user.getEhr());
			goodsUse.setPersonName(user.getName());
			goodsUseService.updateById(goodsUse);
		});

		return R.status(true);
	}

	/**
	 * 審批人設置
	 * @param goodsUse
	 * @return
	 */
	@PostMapping("/settingSave")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入goodsUse")
	public R settingSave(@Valid @RequestBody GoodsUse goodsUse) {
		GoodsUse one = goodsUseService.getOne(new QueryWrapper<>(new GoodsUse()).lambda().eq(GoodsUse::getId, 1L));
		if (one == null){
			goodsUse.setId(1L);
			return R.status(goodsUseService.save(goodsUse));
		}else{
			one.setPersonId(goodsUse.getPersonId());
			one.setPersonName(goodsUse.getPersonName());
			one.setPersonNo(goodsUse.getPersonNo());
			return R.status(goodsUseService.updateById(one));
		}
	}

	/**
	 * 获取审批人设置
	 */
	@GetMapping("/getSetting")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取审批人设置", notes = "")
	public R getSetting() {
		GoodsUse one = goodsUseService.getOne(new QueryWrapper<>(new GoodsUse()).lambda().eq(GoodsUse::getId, 1L));
		return R.data(one);
	}

	/**
	 * 確認
	 */
	@PostMapping("/sure")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "確認", notes = "传入goodsUse")
	public R sure(@Valid @RequestBody GoodsUse goodsUse) {
		goodsUse.setProcess(3);
		BladeUser currentUser = AuthUtil.getUser();
		User user = userService.getById(currentUser.getUserId());
		goodsUse.setApproveTime(DateUtil.now());
		goodsUse.setConfirmNo(user.getEhr());
		goodsUse.setConfirmName(user.getName());
		goodsUse.setIsCompleted(1);
		return R.status(goodsUseService.updateById(goodsUse));
	}

	/**
	 * 根据类型，获取最新一条记录
	 */
	@GetMapping("/getLastByType")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取审批人设置", notes = "")
	public R getLastByType(@ApiParam(value = "主键集合", required = true) @RequestParam String type) {

		LambdaQueryWrapper<GoodsUse> wrapper = new QueryWrapper<>(new GoodsUse()).lambda().eq(GoodsUse::getType, type).orderByDesc(GoodsUse::getCreateTime);
		wrapper.last("limit " + 2);
		List<GoodsUse> list = goodsUseService.list(wrapper);
		if (list != null && list.size() > 0){
			return R.data(list.get(0));
		}
		return R.data(null);
	}

}
