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

import cn.hutool.json.JSONUtil;
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.keypwd.entity.KeyPwd;
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.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.bank.checklist.entity.Checklist;
import org.springblade.bank.checklist.vo.ChecklistVO;
import org.springblade.bank.checklist.wrapper.ChecklistWrapper;
import org.springblade.bank.checklist.service.IChecklistService;
import org.springblade.core.boot.ctrl.BladeController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 每日/週/月核對記錄表 控制器
 *
 * @author BladeX
 * @since 2021-08-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("bank/checklist")
@Api(value = "每日/週/月核對記錄表", tags = "每日/週/月核對記錄表接口")
public class ChecklistController extends BladeController {

	private final IChecklistService checklistService;
	private final IUserService userService;
	private final IDeptService deptService;
	private final IUserLogService userLogService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入checklist")
	public R<ChecklistVO> detail(Checklist checklist) {
		Checklist detail = checklistService.getOne(Condition.getQueryWrapper(checklist));
		return R.data(ChecklistWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 每日/週/月核對記錄表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入checklist")
	public R<IPage<ChecklistVO>> list(Checklist checklist, Query query) {
		IPage<Checklist> pages = checklistService.page(Condition.getPage(query), Condition.getQueryWrapper(checklist));
		return R.data(ChecklistWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 每日/週/月核對記錄表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入checklist")
	public R<IPage<ChecklistVO>> page(ChecklistVO checklist, Query query) {
		if (StringUtils.isNotBlank(checklist.getType())){
			List<String> units = Func.toStrList(checklist.getType());
			checklist.setTypes(units);
		}
		if (StringUtils.isNotBlank(checklist.getItem())){
			List<String> contents = Func.toStrList(checklist.getItem());
			checklist.setItems(contents);
		}
		if (StringUtils.isNotBlank(checklist.getOrgNostr())){
			List<String> orgNos = Func.toStrList(checklist.getOrgNostr());
			checklist.setOrgNos(orgNos);
		}

		if (new Integer(2).equals(checklist.getDataType())){
			String[] dateRange = getDateRange();
			checklist.setBeginDate(dateRange[0]);
			checklist.setEndDate(dateRange[1]);
		}
		IPage<ChecklistVO> pages = checklistService.selectChecklistPage(Condition.getPage(query), checklist);
		return R.data(pages);
	}

	/**
	 * 新增 每日/週/月核對記錄表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入checklist")
	public R save(@Valid @RequestBody Checklist checklist) {
		return R.status(checklistService.save(checklist));
	}

	/**
	 * 修改 每日/週/月核對記錄表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入checklist")
	public R update(@Valid @RequestBody Checklist checklist) {
		return R.status(checklistService.updateById(checklist));
	}

	/**
	 * 新增或修改 每日/週/月核對記錄表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入checklist")
	public R submit(@Valid @RequestBody Checklist checklist) {

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

		if (isAdd){
			checklist.setFillingDate(DateUtil.now());
		}

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

			if (isAdd){
				userLog.setOperationType("add");
			}else{
				userLog.setOperationType("edit");
				Checklist old = checklistService.getById(checklist.getId());
				userLog.setOldData(JSONUtil.toJsonStr(old));
			}
			userLogService.save(userLog);
		}

		if (checklist.getId() == null){
			checklist.setFillingDate(DateUtil.now());
		}
		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);

		if (checklistService.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();
				Checklist checklist = checklistService.getById(id);
				userLog.setTableName("checklist");
				userLog.setOperationType("del");
				userLog.setBankNo(dept.getBankNo());
				userLog.setOrgNo(dept.getOrgNo());
				userLog.setOldData(JSONUtil.toJsonStr(checklist));
				userLog.setPersonNo(user.getEhr());
				userLog.setPersonName(user.getName());
				userLogService.save(userLog);
			});
		}
		return R.status(true);
	}

	/**
	 * 首页 每日/週/月核對数据获取
	 */
	@GetMapping("/getHomeCount")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入checklist")
	public R getHomeCount() {
		ChecklistVO checklist = new ChecklistVO();
		checklist.setDataType(1);
		checklist.setIsChecked(1);
		List<ChecklistVO> dlist1 = checklistService.getDataList(checklist);
		checklist.setIsChecked(0);
		List<ChecklistVO> dlist0 = checklistService.getDataList(checklist);

		checklist.setDataType(3);
		checklist.setIsChecked(1);
		List<ChecklistVO> mlist1 = checklistService.getDataList(checklist);
		checklist.setIsChecked(0);
		List<ChecklistVO> mlist0 = checklistService.getDataList(checklist);

		checklist.setDataType(2);
		String[] dateRange = getDateRange();
		checklist.setBeginDate(dateRange[0]);
		checklist.setEndDate(dateRange[1]);
		checklist.setIsChecked(1);
		List<ChecklistVO> wlist1 = checklistService.getDataList(checklist);
		checklist.setIsChecked(0);
		List<ChecklistVO> wlist0 = checklistService.getDataList(checklist);

		Map map = new HashMap();
		map.put("dayCheckedCount", dlist1.size());
		map.put("dayNocheckCount", dlist0.size());
		map.put("weekCheckedCount", wlist1.size());
		map.put("weekNocheckCount", wlist0.size());
		map.put("monthCheckedCount", mlist1.size());
		map.put("monthNocheckCount", mlist0.size());

		return R.data(map);
	}

	private String[] getDateRange(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
		int[] weekDays = { 7, 1, 2, 3, 4, 5, 6 };
		int today = weekDays[w];
		int begin = today - 1;
		int end = 6 - today;

		Calendar beginDate = Calendar.getInstance();
		beginDate.setTime(new Date());
		Calendar endDate = Calendar.getInstance();
		endDate.setTime(new Date());
		beginDate.add(Calendar.DAY_OF_MONTH, begin);
		endDate.add(Calendar.DAY_OF_MONTH, end);

		String beginDateStr = format.format(beginDate.getTime());
		String endDateStr = format.format(endDate.getTime());
		return new String[]{beginDateStr, endDateStr};
	}

}
