/*
 *      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.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springblade.bank.checklist.entity.Checklist;
import org.springblade.bank.checklist.vo.ChecklistVO;
import org.springblade.bank.checklist.mapper.ChecklistMapper;
import org.springblade.bank.checklist.service.IChecklistService;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IDictService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 每日/週/月核對記錄表 服务实现类
 *
 * @author BladeX
 * @since 2021-08-13
 */
@Service
@AllArgsConstructor
public class ChecklistServiceImpl extends BaseServiceImpl<ChecklistMapper, Checklist> implements IChecklistService {

	private final String pattern = "yyyy-MM-dd";
	private final IDictService dictService;
	private final IDeptService deptService;

	@Override
	public IPage<ChecklistVO> selectChecklistPage(IPage<ChecklistVO> page, ChecklistVO checklist) {
		return page.setRecords(baseMapper.selectChecklistPage(page, checklist));
	}

	@Override
	public List<Checklist> getMyInitialted() {
		List<Checklist> list = list(new QueryWrapper<>(new Checklist()).lambda().eq(Checklist::getCreateUser, AuthUtil.getUser().getUserId()));
		return list;
	}

	@Override
	public List<ChecklistVO> getDataList(ChecklistVO checks) {
		return baseMapper.getDataList(checks);
	}

	@Override
	public List<ChecklistVO> getOverList(ChecklistVO checks) {
		return baseMapper.getOverList(checks);
	}

	@Override
	public List<Checklist> getList(ChecklistVO checklist) {
		return baseMapper.selectChecklistPage(checklist);
	}

	@Override
	public List<Map> getReport(ChecklistVO checklist) {
		List<Map> list = new ArrayList<>();
		List<Dict> check_category = dictService.getList("check_category");
		List<Dict> check_item = dictService.getList("check_item");
		List<Long> deptChildIds = new ArrayList<>();
		if (checklist.getOrgNo() == null){
			Dept dept = deptService.getById(AuthUtil.getDeptId());
			deptChildIds = deptService.getDeptChildIds(dept.getId());
		}else {
			Dept dept = deptService.getByOrgNo(checklist.getOrgNo());
			deptChildIds.add(dept.getId());
		}

		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(), 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 = getDay(dateBegin, i + 1);
				checklist.setDate_begin(theDay);
				checklist.setDate_end(theDay);

				deptChildIds.forEach(deptId -> {
					List<Map> reportData = getReportData(checklist, dataType, theDay, deptService.getById(deptId), 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]);


			deptChildIds.forEach(deptId -> {
				List<Map> reportData = getReportData(checklist, dataType, null, deptService.getById(deptId), 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]);

			deptChildIds.forEach(deptId -> {
				List<Map> reportData = getReportData(checklist, dataType, null, deptService.getById(deptId), check_category, check_item);
				list.addAll(reportData);
			});

		}
		return list;
	}

	@Override
	public List<Map> getReportData(ChecklistVO checklist, String dataType, String theDay, Dept dept, List<Dict> check_category, List<Dict> check_item){
		List<Map> list = new ArrayList<>();
		check_category.forEach(category -> {
			check_item.forEach(item -> {
				if (category.getIsSealed().equals(0) && item.getIsSealed().equals(0)){
					if (category.getDictKey().contains(dataType) && item.getDictKey().contains(dataType) && item.getDictKey().contains(category.getDictKey())){
						if (!dept.getOrgNo().startsWith("999") && !dept.getDeptCategory().equals(1)){
							Map row = new HashMap();
							row.put("orgNo", dept.getOrgNo());
							row.put("deptName", dept.getDeptName());
							row.put("type", category.getDictKey());
							row.put("item", item.getDictKey());

							checklist.setType(category.getDictKey());
							checklist.setItem(item.getDictKey());
							checklist.setOrgNo(dept.getOrgNo());
							//						checklist.setIsChecked(1);
							List<ChecklistVO> dataList = this.getDataList(checklist);
							int checkedCount = dataList.size();
							List<ChecklistVO> dlistOver = this.getOverList(checklist);
							int overCount = dlistOver.size();
							int nocheckCount = (checkedCount > 0 || overCount > 0) ? 0 : 1;
							if (checkedCount > 0){
								Checklist one = dataList.get(0);
								row.put("checkDate", DateUtil.format(one.getCheckDate(), pattern));
							}
							if (overCount > 0){
								Checklist one = dlistOver.get(0);
								row.put("checkDate", DateUtil.format(one.getCheckDate(), pattern));
							}

							if ("day".equals(dataType)){
								row.put("needCheckDate", theDay);
							}

							row.put("checked", checkedCount);
							row.put("nocheck", nocheckCount);
							row.put("over", dlistOver.size());
							list.add(row);
						}
					}
				}
			});
		});

		return list;
	}

}
