package com.cku.oa.statistics.service;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.cku.oa.finance.dao.statistics.FinanceStatisticsDao;
import com.cku.oa.show.dao.ShowApplyDao;
import com.cku.oa.show.entity.ShowApply;
import com.cku.oa.statistics.entity.RegionExport;
import com.cku.oa.statistics.entity.RegionExportXls;
import com.cku.oa.statistics.vo.RegionRevenueVo;
import com.cku.oa.statistics.vo.RegionVo;
import com.cku.oa.sys.service.FileService;
import com.cku.thirdparty.oss.OssApiClient;
import com.cku.thirdparty.oss.OssUploadResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;

@Service
@Transactional(readOnly = true)
public class RegionRevenueService {

	@Autowired
	private FinanceStatisticsDao financeStatisticsDao;

	@Autowired
	private ShowApplyDao showApplyDao;

	@Autowired
	private ShowOfficeRegionService showOfficeRegionService;

	@Autowired
	private RegionExportService regionExportService;

	@Autowired
	private FileService fileService;

	@Autowired
	private OssApiClient ossApiClient;

	@Async
	@Transactional
	public void export(String startDate, String endDate, RegionExport regionExport) throws IOException {
		List<String> plist1 = showOfficeRegionService.findProvince("1");
		List<String> plist2 = showOfficeRegionService.findProvince("2");
		List<String> plist3 = showOfficeRegionService.findProvince("3");
		List<String> plist4 = showOfficeRegionService.findProvince("4");

		List<RegionVo> regions = showOfficeRegionService.findRegionList();
		List<Map> officeName = financeStatisticsDao.regionOfficeName(); // 部门名称

		Map<String, Object> result = new HashMap<>();
		for (RegionVo region : regions) {
			Map<String, Object> map = new HashMap<>();
			List<Map> chargeItem = financeStatisticsDao.regionCharge(startDate, endDate, region.getLabel(), null); // 扣费项目
			for (Map<String, Object> office : officeName) {
				double countFee = 0.00;// 总数
				for (Map<String, Object> charge : chargeItem) {
					if (office.get("id").equals(charge.get("id"))) {
						countFee += ((java.math.BigDecimal) charge.get("countFee")).doubleValue();
					}
				}
				map.put((String) office.get("name"), new BigDecimal(countFee).setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			result.put(region.getLabel(), map);
		}

		List<RegionExportXls> list1 = new ArrayList<>();
		List<RegionExportXls> list2 = new ArrayList<>();
		List<RegionExportXls> list3 = new ArrayList<>();
		List<RegionExportXls> list4 = new ArrayList<>();

		for (String key : result.keySet()) {
			RegionExportXls xls = new RegionExportXls();
			xls.setStartDate(regionExport.getStartDate());
			xls.setEndDate(regionExport.getEndDate());
			xls.setExportDate(LocalDateTime.now().toString());
			xls.setProvince(key);
			Map<String, Object> proviceMap = (Map<String, Object>) result.get(key);
			for (String proviceKey : proviceMap.keySet()) {
				String value = proviceMap.get(proviceKey).toString();
				if ("会员部".equals(proviceKey)) {
					xls.setMemberCount(value);
				} else {
					xls.setBreedCount(value);
				}
			}
			if (plist1.contains(key)) {
				list1.add(xls);
			}
			if (plist2.contains(key)) {
				list2.add(xls);
			}
			if (plist3.contains(key)) {
				list3.add(xls);
			}
			if (plist4.contains(key)) {
				list4.add(xls);
			}
		}
		// 生成文件
		ExportExcel excel = new ExportExcel("总部", RegionExportXls.class);
		excel.setDataList(list1, 0);
		excel.addSheet("杭州办", RegionExportXls.class);
		excel.setDataList(list2, 1);
		excel.addSheet("长春办", RegionExportXls.class);
		excel.setDataList(list3, 2);
		excel.addSheet("重庆办", RegionExportXls.class);
		excel.setDataList(list4, 3);
		InputStream in = excel.writeInputStream();
		OssUploadResult uploadResult = ossApiClient.uploadTmp(in, "region", regionExport.getFileName());
		if (Objects.nonNull(in)) {
			in.close();
		}
		// 更新下载地址
		regionExport.setUrl(uploadResult.getUploadUrl());
		regionExportService.updateUlr(regionExport);
	}

	public void revenue(RegionRevenueVo vo, Model model, List<RegionVo> regioins) {
		double chargeTotal = 0; // 业务扣费总计金额
		List<Map> officeName = financeStatisticsDao.regionOfficeName(); // 部门名称
		List<Map> chargeItem = financeStatisticsDao.regionCharge(vo.getStartDate(), vo.getEndDate(), vo.getProvince(),
				regioins); // 扣费项目
		List<Map> chargeDetails = new ArrayList();

		for (Map<String, Object> office : officeName) {
			List<Map> myDetails = Lists.newArrayList();
			double corpNum = 0, corpFee = 0;// 合作机构
			double memberNum = 0, memberFee = 0;// 会员中心
			double orderNum = 0, orderFee = 0;// 业务订单
			double OANum = 0, OAFee = 0;// OA扣费
			double countNum = 0, countFee = 0;// 总数

			Map<String, Object> countAll = new HashMap<String, Object>();
			Map<String, Object> content = new HashMap<String, Object>();

			content.put("officeName", office.get("name"));
			for (Map<String, Object> charge : chargeItem) {
				if (office.get("id").equals(charge.get("id"))) {
					Map<String, Object> myCharge = Maps.newHashMap();
					myCharge.put("chargeID", charge.get("chargeID"));
					myCharge.put("chargeItem", charge.get("chargeItem"));
					myCharge.put("corpNum", charge.get("corpNum"));
					myCharge.put("corpNum", charge.get("corpNum"));
					myCharge.put("corpFee", charge.get("corpFee"));
					myCharge.put("memberNum", charge.get("memberNum"));
					myCharge.put("memberFee", charge.get("memberFee"));
					myCharge.put("orderNum", charge.get("orderNum"));
					myCharge.put("orderFee", charge.get("orderFee"));
					myCharge.put("OANum", charge.get("OANum"));
					myCharge.put("OAFee", charge.get("OAFee"));
					myCharge.put("countNum", charge.get("countNum"));
					myCharge.put("countFee", charge.get("countFee"));
					corpNum += ((java.math.BigDecimal) charge.get("corpNum")).doubleValue();
					corpFee += ((java.math.BigDecimal) charge.get("corpFee")).doubleValue();
					memberNum += ((java.math.BigDecimal) charge.get("memberNum")).doubleValue();
					memberFee += ((java.math.BigDecimal) charge.get("memberFee")).doubleValue();
					orderNum += ((java.math.BigDecimal) charge.get("orderNum")).doubleValue();
					orderFee += ((java.math.BigDecimal) charge.get("orderFee")).doubleValue();
					OANum += Double.parseDouble(charge.get("OANum").toString());
					OAFee += ((java.math.BigDecimal) charge.get("OAFee")).doubleValue();
					countNum += ((java.math.BigDecimal) charge.get("countNum")).doubleValue();
					countFee += ((java.math.BigDecimal) charge.get("countFee")).doubleValue();
					myDetails.add(myCharge);
					if (!content.get("officeName").equals("财务部") && !content.get("officeName").equals("合作单位"))
						chargeTotal += Double.parseDouble(charge.get("countFee").toString());
				}
			}

			countAll.put("countCoreNum", corpNum);
			countAll.put("countCoreFee", corpFee);
			countAll.put("countMemberNum", memberNum);
			countAll.put("countMemberFee", memberFee);
			countAll.put("countOrderNum", orderNum);
			countAll.put("countOrderFee", orderFee);
			countAll.put("countOANum", OANum);
			countAll.put("countOAFee", OAFee);
			countAll.put("totalCountNum", countNum);
			countAll.put("totalCountFee", countFee);
			content.put("totalCount", countAll);
			content.put("chargeItem", myDetails);
			chargeDetails.add(content);
		}
		List<String> showChargeItemID = financeStatisticsDao.showChargeItemID();
		List<String> showChargeCouponItemID = financeStatisticsDao.showChargeCouponItemID();

		model.addAttribute("showChargeItemID", showChargeItemID);
		model.addAttribute("showChargeCouponItemID", showChargeCouponItemID);
		model.addAttribute("chargeDetails", chargeDetails);
		model.addAttribute("chargeTotal", chargeTotal);
	}

	public String regionsCountOrder(RegionRevenueVo vo, List<RegionVo> regions, Model model, Page page) {

		Map countOrder = financeStatisticsDao.regionCountOrder(vo.getTotalPrice(), vo.getOrderCode(),
				vo.getMemberCode(), vo.getMemberName(), vo.getOrderType(), vo.getChargingItemID(), vo.getProjectID(),
				vo.getVoucherCode(), vo.getPaymentState(), vo.getStartDate(), vo.getEndDate(), vo.getProvince(),
				regions);
		List<Map> orderList = financeStatisticsDao.regionOrderList(vo.getTotalPrice(), vo.getOrderCode(),
				vo.getMemberCode(), vo.getMemberName(), vo.getOrderType(), vo.getChargingItemID(), vo.getProjectID(),
				vo.getVoucherCode(), vo.getPaymentState(), vo.getStartDate(), vo.getEndDate(),
				(page.getPageNo() - 1) * page.getPageSize(), page.getPageSize(), vo.getProvince(), regions);
		if (StringUtils.isNotBlank(vo.getIsShowCoupon())) {
			for (Map map : orderList) {
				map.put("show_code", "");
				String chargind_item_id = map.get("charging_item_id").toString();
				String ids = map.get("business_ids").toString();
				// 查询赛事
				if (StringUtils.isNotBlank(ids)) {
					String[] split = ids.split("#");
					//
					ShowApply showApply = showApplyDao.get(split[0]);
					map.put("show_code", showApply.getShowCode());
				}
			}
		}

		List<Map> chargingItemOption = financeStatisticsDao.chargeItemOption();
		List<Map> chargeCouponItemOption = financeStatisticsDao.chargeCouponItemOption();
		model.addAttribute("chargeCouponItemOption", chargeCouponItemOption);
		model.addAttribute("chargeItemOption", chargingItemOption);
		model.addAttribute("orderList", orderList);
		model.addAttribute("countOrder", countOrder);

		page.setCount(Integer.parseInt(countOrder.get("countNum").toString())); // 总条数
		page.initialize();// 初始化
		model.addAttribute("page", page);
		return "oa/finance/statistics/orderList";
	}

}
