/*
 *      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 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.springblade.bank.checklist.entity.Checklist;
import org.springblade.bank.checklist.service.IChecklistService;
import org.springblade.bank.checklist.vo.ChecklistVO;
import org.springblade.bank.checklist.wrapper.ChecklistWrapper;
import org.springblade.bank.userlog.entity.UserLog;
import org.springblade.bank.userlog.service.IUserLogService;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.boot.ctrl.BladeController;
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.Dict;
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.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 每日/週/月核對記錄表 控制器
 *
 * @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;
	private final IDictService dictService;

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

		Checklist old = null;
		if (isAdd){
			checklist.setFillingDate(DateUtil.now());
		}else{
			old = checklistService.getById(checklist.getId());
		}

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

			if (isAdd){
				userLog.setOperationType("add");
			}else{
				userLog.setOperationType("edit");
				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);
		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();
			Checklist checklist = checklistService.getById(id);
			userLog.setTableName("checklist");
			userLog.setOperationType("del");
			userLog.setBankNo(dept.getBankNo());
			userLog.setOrgNo(dept.getOrgNo());
			userLog.setOrgName(dept.getDeptName());
			userLog.setOldData(JSONUtil.toJsonStr(checklist));
			userLog.setPersonNo(user.getEhr());
			userLog.setPersonName(user.getName());
			userLogList.add(userLog);
		});

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

	/**
	 * 首页 每日/週/月核對数据获取
	 */
	@GetMapping("/getHomeCount")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入checklist")
	public R getHomeCount(ChecklistVO checklist) {
		List<Map> list = new ArrayList<>();
		List<Dict> check_category = dictService.getList("check_category");
		List<Dict> check_item = dictService.getList("check_item");
		Dept dept = deptService.getById(AuthUtil.getDeptId());

		if (checklist.getCycle() == null){
			checklist.setCycle("day");
		}

		if (StringUtils.isNotBlank(checklist.getDate_begin()) && StringUtils.isNotBlank(checklist.getDate_end())){
			// 延长一天，是为了sql可以查询出最后一天的记录
//			checklist.setDate_end(getNextDay(checklist.getDate_end()));
		}else{
			// 默认是当天
			String today = DateUtil.format(DateUtil.now(), CommonUtil.pattern);
			checklist.setDate_begin(today);
			checklist.setDate_end(today);
		}

		String dateBegin = checklist.getDate_begin();
		String dateEnd = checklist.getDate_end();
		long days = CommonUtil.getInterval(dateBegin, dateEnd);

		String dataType = checklist.getCycle();
		if (dataType.equals("day")){
			for (int i = 0; i <= days; i++) {
				String theDay = CommonUtil.getDay(dateBegin, i);
				// 延长一天，是为了sql可以查询出最后一天的记录
				String nextDay = CommonUtil.getDay(dateBegin, i + 1);
				checklist.setDate_begin(theDay);
				checklist.setDate_end(nextDay);

				List<Map> reportData = checklistService.getReportData(checklist, dataType, theDay, dept, check_category, check_item);
				list.addAll(reportData);
			}
		}else if (dataType.equals("week")){
			String[] weekRange = CommonUtil.getWeekRange(checklist.getDate_begin());
			checklist.setDate_begin(weekRange[0]);
			checklist.setDate_end(weekRange[1]);

			List<Map> reportData = checklistService.getReportData(checklist, dataType, null, dept, check_category, check_item);
			list.addAll(reportData);
		}else {
			String[] monthRange = CommonUtil.getMonthRange(checklist.getDate_begin());
			checklist.setDate_begin(monthRange[0]);
			checklist.setDate_end(monthRange[1]);
			List<Map> reportData = checklistService.getReportData(checklist, dataType, null, dept, check_category, check_item);
			list.addAll(reportData);
		}

		return R.data(list);
	}
	/**
	 * 首页 每日/週/月核對数据获取
	 */
	@GetMapping("/getReport")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入checklist")
	public R getReport(ChecklistVO checklist) {

		List<Map> reportList = checklistService.getReport(checklist);
		return R.data(reportList);
	}

	@GetMapping("/getList")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入checklist")
	public R getList(ChecklistVO checklist) {
		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);
		}
		List<Checklist> list = checklistService.getList(checklist);

		list.forEach(item -> {
			String type = item.getType();
			String item1 = item.getItem();
			String check_category = dictService.getValue("check_category", type);
			String check_item = dictService.getValue("check_item", item1);
			item.setType(check_category);
			item.setItem(check_item);
		});

		return R.data(list);
	}

}
