/*
 *
 *      Copyright (c) 2018-2025, avenue 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 pig4cloud.com 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: avenue
 *
 */

package com.emergency.avenue.storage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emergency.avenue.admin.api.entity.SysTreeDict;
import com.emergency.avenue.admin.handler.DataPermissionsDeptIdHandle;
import com.emergency.avenue.admin.mapper.SysTreeDictMapper;
import com.emergency.avenue.common.core.common.DataPermissions;
import com.emergency.avenue.common.excel.EasyExcelUtil;
import com.emergency.avenue.storage.api.entity.Dmmatype;
import com.emergency.avenue.storage.api.request.DmmatypeRequest;
import com.emergency.avenue.storage.api.request.IrptDimWzdwRequest;
import com.emergency.avenue.storage.api.response.DmmatypeResponse;
import com.emergency.avenue.storage.api.response.IrkzqXxb1Response;
import com.emergency.avenue.storage.api.response.IrkzqXxb3Response;
import com.emergency.avenue.storage.mapper.DmmatypeMapper;
import com.emergency.avenue.storage.service.DmmatypeService;
import com.emergency.avenue.storage.util.MyFileUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author avenue
 * @since 2018-01-20
 */
@Service
public class DmmatypeServiceImpl extends ServiceImpl<DmmatypeMapper, Dmmatype> implements DmmatypeService {

	@Resource
	private DmmatypeMapper dmmatypeMapper;
	@Resource
	private SysTreeDictMapper sysTreeDictMapper;

	@Resource
	private DataPermissionsDeptIdHandle dataPermissionsDeptIdHandle;

	@Override
	public IPage<DmmatypeResponse> getList(Page p, DmmatypeRequest dmmatypeRequest) {
		handleDmmatypeRequest(dmmatypeRequest);
		IPage<DmmatypeResponse> dmmatypeResponseIPage = dmmatypeMapper.dimWzdw(p, dmmatypeRequest);
		Map<String, SysTreeDict> sysTreeDicts = sysTreeDictMapper.getOrderDictList(1)
				.stream().collect(Collectors.toMap(SysTreeDict::getCode, d -> d, (p1, p2) -> p2));
		dmmatypeResponseIPage.getRecords().stream().forEach(dmmatypeResponse -> {
			String[] codePath = dmmatypeResponse.getMatypeapth().split("/");
			dmmatypeResponse.setMatypename4(Optional.ofNullable(sysTreeDicts.get(codePath[3] + "01")).orElse(new SysTreeDict()).getName());
			dmmatypeResponse.setMatypename1(Optional.ofNullable(sysTreeDicts.get(codePath[1])).orElse(new SysTreeDict()).getName());
			dmmatypeResponse.setMatypename2(Optional.ofNullable(sysTreeDicts.get(codePath[2])).orElse(new SysTreeDict()).getName());
			dmmatypeResponse.setMatypecode1(sysTreeDicts.get(codePath[1]).getCode());
			dmmatypeResponse.setMatypecode2(sysTreeDicts.get(codePath[2]).getCode());
			dmmatypeResponse.setMatypecode4(Optional.ofNullable(sysTreeDicts.get(codePath[3] + "01")).orElse(new SysTreeDict()).getCode());
		});
		return dmmatypeResponseIPage;
	}

	@Override
	public List<DmmatypeResponse> getAllList(DmmatypeRequest dmmatypeRequest) {
		handleDmmatypeRequest(dmmatypeRequest);
		List<DmmatypeResponse> dmmatypeResponseIPage = dmmatypeMapper.getAllList(dmmatypeRequest);
		Map<String, SysTreeDict> sysTreeDicts = sysTreeDictMapper.getOrderDictList(1)
				.stream().collect(Collectors.toMap(SysTreeDict::getCode, d -> d, (p1, p2) -> p2));
		dmmatypeResponseIPage.stream().forEach(dmmatypeResponse -> {
			String[] codePath = dmmatypeResponse.getMatypeapth().split("/");
			dmmatypeResponse.setMatypename4(Optional.ofNullable(sysTreeDicts.get(codePath[3] + "01")).orElse(new SysTreeDict()).getName());
			dmmatypeResponse.setMatypename1(Optional.ofNullable(sysTreeDicts.get(codePath[1])).orElse(new SysTreeDict()).getName());
			dmmatypeResponse.setMatypename2(Optional.ofNullable(sysTreeDicts.get(codePath[2])).orElse(new SysTreeDict()).getName());
			dmmatypeResponse.setMatypecode1(sysTreeDicts.get(codePath[1]).getCode());
			dmmatypeResponse.setMatypecode2(sysTreeDicts.get(codePath[2]).getCode());
			dmmatypeResponse.setMatypecode4(Optional.ofNullable(sysTreeDicts.get(codePath[3] + "01")).orElse(new SysTreeDict()).getCode());
		});
		return dmmatypeResponseIPage;
	}

	public void handleDmmatypeRequest(DmmatypeRequest dmmatypeRequest) {
		if (CollUtil.isNotEmpty(dmmatypeRequest.getMatype1())) {
			dmmatypeRequest.setMatype1(dmmatypeRequest.getMatype1().stream().map(d -> "%/" + d + "/%").collect(Collectors.toList()));
		}
		if (CollUtil.isNotEmpty(dmmatypeRequest.getMatype2())) {
			dmmatypeRequest.setMatype2(dmmatypeRequest.getMatype2().stream().map(d -> "%/" + d + "/%").collect(Collectors.toList()));
		}
	}

	@Override
	public List<IrkzqXxb1Response> selectIrkzqXxb(IrptDimWzdwRequest irptDimWzdwRequest) {
		DataPermissions dataPermissions = dataPermissionsDeptIdHandle.handleDataScope();
		BeanUtil.copyProperties(dataPermissions, irptDimWzdwRequest);
		if (CollUtil.isNotEmpty(irptDimWzdwRequest.getDmUpcode0List())) {
			irptDimWzdwRequest.setDmUpcode0List(irptDimWzdwRequest.getDmUpcode0List().stream().map(d -> "%/" + d + "/%").collect(Collectors.toList()));
		}
		if (CollUtil.isNotEmpty(irptDimWzdwRequest.getDmUpcode1List())) {
			irptDimWzdwRequest.setDmUpcode1List(irptDimWzdwRequest.getDmUpcode1List().stream().map(d -> "%/" + d + "/%").collect(Collectors.toList()));
		}
		List<IrkzqXxb1Response> irkzqXxb1ResponseList = new ArrayList<>();
		IrkzqXxb1Response one = new IrkzqXxb1Response();
		one.setUserid("合计");
		one.setUpidName("合计");
		one.setUsername("合计");
		one.setProvince("合计");

		List<IrkzqXxb1Response> list = dmmatypeMapper.selectIrkzqXxb(irptDimWzdwRequest);

		Map<String, BigDecimal> resultAllMap = new HashMap<>();
		for (int i = 0; i < list.size(); i++) {
			IrkzqXxb1Response irkzqXxb1Response = list.get(i);
			hande(irkzqXxb1Response.getList3());
			Map<String, BigDecimal> resultMap = irkzqXxb1Response.getList3().stream()
					.collect(Collectors.toMap(IrkzqXxb3Response::getDmUpcode2, IrkzqXxb3Response::getTolNum));
			resultMap.forEach((key, value) -> resultAllMap.merge(key, value, BigDecimal::add));

			irkzqXxb1Response.setMap(resultMap);
			irkzqXxb1Response.setTolNum(irkzqXxb1Response.getList3().stream().map(IrkzqXxb3Response::getTolNumhs).reduce(BigDecimal.ZERO, BigDecimal::add));
			irkzqXxb1Response.setTolMoney(irkzqXxb1Response.getList3().stream().map(IrkzqXxb3Response::getTolMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
		}
		one.setMap(resultAllMap);
		one.setTolNum(list.stream().map(IrkzqXxb1Response::getTolNum).reduce(BigDecimal.ZERO, BigDecimal::add));
		one.setTolMoney(list.stream().map(IrkzqXxb1Response::getTolMoney).reduce(BigDecimal.ZERO, BigDecimal::add));

		irkzqXxb1ResponseList.add(one);
		irkzqXxb1ResponseList.addAll(list);
		return irkzqXxb1ResponseList;
	}

	/**
	 * @param fileName  文件名
	 * @param irptDimWzdwRequest
	 * @return
	 */
	@Override
	public void selectIrkzqXxbExport(String fileName, String templateFile , IrptDimWzdwRequest irptDimWzdwRequest, HttpServletResponse response) {
		// 查询数据
		List<IrkzqXxb1Response> list0 = selectIrkzqXxb(irptDimWzdwRequest);

		// 组装数据
		List<Map<String, BigDecimal>> listMap = new ArrayList<>(list0.size());
		// 获取6位编码对应多品类信息，默认一个值都是0的容器，用于填充值是空的单元格
		List<String> allDictCode6 = sysTreeDictMapper.getAllDictCode6();
		list0.forEach(i -> {
			Map<String, BigDecimal> defaultMap = new HashMap<>();
			allDictCode6.forEach(d -> {
				defaultMap.put(d, BigDecimal.ZERO);
			});
			getListMap(i, defaultMap, listMap);
		});

		//合计需要合并，不好处理，用另一个list插入合计数据，见模板
		List<IrkzqXxb1Response> list1 = new ArrayList<>();
		if(!list0.isEmpty()){
			list1.add(list0.get(0));
			list0.remove(0);
		}

		MyFileUtil.listToExcel(response,fileName, templateFile, 2,null, list0, listMap,list1);

	}

	private void getListMap(IrkzqXxb1Response i, Map<String, BigDecimal> defaultMap, List<Map<String, BigDecimal>> listMap) {
		Map<String, BigDecimal> map = i.getMap();
		if (map != null) {
			defaultMap.forEach((k, v) -> {
				if (map.containsKey(k)) {
					BigDecimal bigDecimal = map.get(k);
					if (bigDecimal != null) {
						defaultMap.put(k, bigDecimal);
					}
				}
			});
		}
		listMap.add(defaultMap);
	}

	@Override
	public void exportyjwzflb(String fileName, String templateFile, List<DmmatypeResponse> list0,HttpServletResponse response) {
//		根据模板生成文件
		MyFileUtil.listToExcel(response,fileName, templateFile, -1,null, list0, null);
	}

	public void hande(List<IrkzqXxb3Response> list3) {
		if (CollUtil.isNotEmpty(list3)) {
			for (int i = 0; i < list3.size(); i++) {
				list3.get(i).setTolNumhs(list3.get(i).getTolNum());
				if (list3.get(i).getDmUpcode2().equals("10305")) {
					list3.get(i).setTolNumhs(list3.get(i).getTolNum().multiply(BigDecimal.valueOf(10000L)).divide(BigDecimal.valueOf(500L), 6, BigDecimal.ROUND_HALF_UP));
				}
				if (list3.get(i).getDmUpcode2().equals("10303")) {
					list3.get(i).setTolNumhs(list3.get(i).getTolNum().multiply(BigDecimal.valueOf(10000L)).divide(BigDecimal.valueOf(600L), 6, BigDecimal.ROUND_HALF_UP));
				}
				if (list3.get(i).getDmUpcode2().equals("10306")) {
					list3.get(i).setTolNumhs(list3.get(i).getTolNum().multiply(BigDecimal.valueOf(10000L)).divide(BigDecimal.valueOf(600L), 6, BigDecimal.ROUND_HALF_UP));
				}
				if (list3.get(i).getDmUpcode2().equals("10310")) {
					list3.get(i).setTolNumhs(list3.get(i).getTolNum().multiply(BigDecimal.valueOf(10000L)).divide(BigDecimal.valueOf(300L), 6, BigDecimal.ROUND_HALF_UP));
				}
				if (list3.get(i).getDmUpcode2().equals("10307")) {
					list3.get(i).setTolNumhs(list3.get(i).getTolNum().divide(BigDecimal.valueOf(5L), 6, BigDecimal.ROUND_HALF_UP));
				}
				if (list3.get(i).getDmUpcode2().equals("20121")) {
					list3.get(i).setTolNumhs(list3.get(i).getTolNum().multiply(BigDecimal.valueOf(10000L)).divide(BigDecimal.valueOf(20L), 6, BigDecimal.ROUND_HALF_UP));
				}
				if (list3.get(i).getDmUpcode2().equals("20120")) {
					list3.get(i).setTolNumhs(list3.get(i).getTolNum().multiply(BigDecimal.valueOf(10000L)).divide(BigDecimal.valueOf(20L), 6, BigDecimal.ROUND_HALF_UP));
				}
			}
		}
	}

	public void excel() {
		int[] meargeColl = new int[]{0, 1};
		EasyExcelUtil.CellMerge cellMerge = EasyExcelUtil.setCellMerge(meargeColl, meargeColl);

		//EasyExcelUtil.createExcel(response, fileName, studentData, Student.class, cellMerge);
	}
}
