package com.gci.boot.modules.dataview.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gci.boot.common.util.DateUtils;
import com.gci.boot.modules.basedata.entity.TbVehicle;
import com.gci.boot.modules.basedata.mapper.TbVehicleMapper;
import com.gci.boot.modules.customer.mapper.TbCustomerFollowMapper;
import com.gci.boot.modules.customer.mapper.TbInspectionTaskMapper;
import com.gci.boot.modules.customer.vo.CustomerFollowVo;
import com.gci.boot.modules.customer.vo.InspectionTaskVo;
import com.gci.boot.modules.dataview.service.ITbBusinessCenterService;
import com.gci.boot.modules.dataview.vo.ProjectContractVo;
import com.gci.boot.modules.dataview.vo.RepairPayMonthVo;
import com.gci.boot.modules.driver.entity.TbDriver;
import com.gci.boot.modules.driver.mapper.TbDriverMapper;
import com.gci.boot.modules.projects.entity.Projects;
import com.gci.boot.modules.projects.entity.TbContract;
import com.gci.boot.modules.projects.mapper.TbContractMapper;
import com.gci.boot.modules.projects.service.IProjectsService;
import com.gci.boot.modules.vehicles.mapper.TbRepairOfferMapper;

/**
 * <p>
 *  数据看板-业务中心 服务实现类
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-04
 */
@Service
public class TbBusinessCenterServiceImpl extends ServiceImpl<TbDriverMapper, TbDriver> implements ITbBusinessCenterService {
	
	@Autowired
	private TbContractMapper tbContractMapper;
	@Autowired
	private TbRepairOfferMapper tbRepairOfferMapper;

    @Autowired
    private IProjectsService projectsService;
    
    @Autowired
    private TbVehicleMapper tbVehicleMapper;
    
    @Autowired
    private TbInspectionTaskMapper tbInspectionTaskMapper;
    
    @Autowired
    private TbCustomerFollowMapper tbCustomerFollowMapper;
    
	DecimalFormat df2 =new DecimalFormat("#.0");

	/**
	 * 获取全部租户合同统计
	 * @return
	 */
	@Override
	public ProjectContractVo getProjectContractTotal() {
		LambdaQueryWrapper<Projects> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Projects::getStatus, "1");
		int projectCount = projectsService.count(queryWrapper);
		
        List<TbVehicle> pageList = tbVehicleMapper.getProjectVehicle();
		
		ProjectContractVo vo = new ProjectContractVo();
		List<ProjectContractVo> list = getProjectContractList(null);
		for (ProjectContractVo projectContractVo : list) {
			vo.setTotalIncome(vo.getTotalIncome()+projectContractVo.getTotalIncome());
			vo.setConfirmIncome(vo.getConfirmIncome()+projectContractVo.getConfirmIncome());
			vo.setSurplusIncome(vo.getSurplusIncome()+projectContractVo.getSurplusIncome());
		}
		vo.setTotalIncome(formatDouble(vo.getTotalIncome()));
		vo.setConfirmIncome(formatDouble(vo.getConfirmIncome()));
		vo.setSurplusIncome(formatDouble(vo.getSurplusIncome()));
		vo.setProjectCount(projectCount);
		vo.setVehicleCount(pageList.size());
		return vo;
	}
	
	/**
	 * 获取项目合同收支统计
	 */
	@Override
	public List<ProjectContractVo> getProjectContractList(String pay) {
		//租户合同
		List<TbContract> list = tbContractMapper.getProjectContract();
		Map<String,ProjectContractVo> map = new LinkedHashMap<>();
		Date today = DateUtils.getToday();
		
		Map<String, Double> payMap = new LinkedHashMap<>();
		if("1".equals(pay)) {
			payMap = getProjectPay();
		}
		int jd = 3;
		for (TbContract tbContract : list) {
			if(!map.containsKey(tbContract.getProjectId())) {
				ProjectContractVo vo = new ProjectContractVo();
				vo.setProjectId(tbContract.getProjectId());
				vo.setTotalIncome(formatDouble(tbContract.getTotalPrice()/10000));
				
				int all = DateUtils.differentMonth(tbContract.getStartTime(), tbContract.getEndTime())+1;
				int curr = DateUtils.differentMonth(tbContract.getStartTime(), today)+1;
				if(curr<0) {
					curr = 0;
				}
				//按季度算进度
				int allyu = all/jd;
				if(all%jd!=0) {
					allyu += 1;
				}
				int curryu = curr/jd;
				if(curr%jd!=0) {
					curryu += 1;
				}
				double schedule = new Double(curryu)/new Double(allyu);
				if(schedule>1) {
					schedule = 1;
				}
				double confirmIncome = vo.getTotalIncome()*schedule;
				double surplusIncome = vo.getTotalIncome()-confirmIncome;
				int surplusDay = DateUtils.differentDays(today, tbContract.getEndTime());
				if(surplusDay<0) {
					surplusDay = 0;
				}
				vo.setSchedule(new Double(100*schedule).intValue());
				vo.setConfirmIncome(formatDouble(confirmIncome));
				vo.setSurplusIncome(formatDouble(surplusIncome));
				vo.setSurplusDay(surplusDay);
				if(payMap.containsKey(vo.getProjectId())) {
					vo.setPay(formatDouble(payMap.get(vo.getProjectId())/10000));
				}
				
				map.put(tbContract.getProjectId(), vo);
			}
		}
		return new ArrayList<>(map.values());
	}
	
	public Double formatDouble(double price) {
		return new Double(df2.format(price));
	}
	
	/**
	 * 获取保险、维修、保养、年检项目支出
	 * @return
	 */
	public Map<String, Double> getProjectPay() {
		Map<String,Double> map = new LinkedHashMap<>();
		//保险
		/*List<ProjectContractVo> insurance = tbRepairOfferMapper.getInsuranceTotalPrice();
		for (ProjectContractVo projectContractVo : insurance) {
			Double pay = map.getOrDefault(projectContractVo.getProjectId(), 0d);
			map.put(projectContractVo.getProjectId(), pay+projectContractVo.getTotalIncome());
		}*/
		//年检
		/*List<ProjectContractVo> inspection = tbRepairOfferMapper.getInspectionTotalPrice();
		for (ProjectContractVo projectContractVo : inspection) {
			Double pay = map.getOrDefault(projectContractVo.getProjectId(), 0d);
			map.put(projectContractVo.getProjectId(), pay+projectContractVo.getTotalIncome());
		}*/
		//维修
		List<ProjectContractVo> repair = tbRepairOfferMapper.getRepairTotalPrice();
		for (ProjectContractVo projectContractVo : repair) {
			Double pay = map.getOrDefault(projectContractVo.getProjectId(), 0d);
			map.put(projectContractVo.getProjectId(), pay+projectContractVo.getTotalIncome());
		}
		//保养
		List<ProjectContractVo> upkeep = tbRepairOfferMapper.getUpkeepTotalPrice();
		for (ProjectContractVo projectContractVo : upkeep) {
			Double pay = map.getOrDefault(projectContractVo.getProjectId(), 0d);
			map.put(projectContractVo.getProjectId(), pay+projectContractVo.getTotalIncome());
		}
		return map;
	}
	
	/**
	 * 获取维修车务支出
	 */
	@Override
	public Map<String, List<RepairPayMonthVo>> getRepairPay(RepairPayMonthVo param) {
		Map<String,List<RepairPayMonthVo>> map = new LinkedHashMap<>();
		if("2".equals(param.getType())) {
			map = getRepairPayQuarter(param);
		}else if("3".equals(param.getType())) {
			map = getRepairPayYear(param);
		}else {
			map = getRepairPayMonth(param);
		}
		return map;
	}
	
	public Map<String, List<RepairPayMonthVo>> getRepairPayMonth(RepairPayMonthVo param) {
		Map<String,List<RepairPayMonthVo>> map = new LinkedHashMap<>();
		Date today = new Date();
		today = DateUtils.getFirstDayForMonth(today);
		String month1 = DateUtils.formatDate(today, DateUtils.HYPHENS_MONTH);
		List<RepairPayMonthVo> list1 = tbRepairOfferMapper.getRepairPayMonth(month1);
		for (RepairPayMonthVo repairPayMonthVo : list1) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list1", list1);
		
		Date last = DateUtils.addMonth(today, -1);;
		String month2 = DateUtils.formatDate(last, DateUtils.HYPHENS_MONTH);
		List<RepairPayMonthVo> list2 = tbRepairOfferMapper.getRepairPayMonth(month2);
		for (RepairPayMonthVo repairPayMonthVo : list2) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list2", list2);
		
		Date lastYear = DateUtils.addYear(today, -1);;
		String month3 = DateUtils.formatDate(lastYear, DateUtils.HYPHENS_MONTH);
		List<RepairPayMonthVo> list3 = tbRepairOfferMapper.getRepairPayMonth(month3);
		for (RepairPayMonthVo repairPayMonthVo : list3) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list3", list3);
		return map;
	}
	

	public Map<String, List<RepairPayMonthVo>> getRepairPayQuarter(RepairPayMonthVo param) {
		Map<String,List<RepairPayMonthVo>> map = new LinkedHashMap<>();
		Date today = new Date();
		today = DateUtils.getFirstDayForMonth(today);
		String[] month1 = DateUtils.getQuarter(today);
		List<RepairPayMonthVo> list1 = tbRepairOfferMapper.getRepairPayQuarter(month1[0],month1[2]);
		for (RepairPayMonthVo repairPayMonthVo : list1) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list1", list1);
		
		Date last = DateUtils.addMonth(today, -3);
		String[] month2 = DateUtils.getQuarter(last);
		List<RepairPayMonthVo> list2 = tbRepairOfferMapper.getRepairPayQuarter(month2[0],month2[2]);
		for (RepairPayMonthVo repairPayMonthVo : list2) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list2", list2);
		
		Date lastYear = DateUtils.addYear(today, -1);;
		String[] month3 = DateUtils.getQuarter(lastYear);
		List<RepairPayMonthVo> list3 = tbRepairOfferMapper.getRepairPayQuarter(month3[0],month3[2]);
		for (RepairPayMonthVo repairPayMonthVo : list3) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list3", list3);
		return map;
	}

	public Map<String, List<RepairPayMonthVo>> getRepairPayYear(RepairPayMonthVo param) {
		Map<String,List<RepairPayMonthVo>> map = new LinkedHashMap<>();
		Date today = new Date();
		today = DateUtils.getFirstDayForMonth(today);
		String month1 = DateUtils.formatDate(today, DateUtils.HYPHENS_YEAR);
		List<RepairPayMonthVo> list1 = tbRepairOfferMapper.getRepairPayYear(month1);
		for (RepairPayMonthVo repairPayMonthVo : list1) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list1", list1);

		Date lastYear = DateUtils.addYear(today, -1);;
		String month3 = DateUtils.formatDate(lastYear, DateUtils.HYPHENS_YEAR);
		List<RepairPayMonthVo> list3 = tbRepairOfferMapper.getRepairPayYear(month3);
		for (RepairPayMonthVo repairPayMonthVo : list3) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list2", list3);
		
		Date lastYear4 = DateUtils.addYear(today, -2);;
		String month4 = DateUtils.formatDate(lastYear4, DateUtils.HYPHENS_YEAR);
		List<RepairPayMonthVo> list4 = tbRepairOfferMapper.getRepairPayYear(month4);
		for (RepairPayMonthVo repairPayMonthVo : list4) {
			repairPayMonthVo.setPay(formatDouble(repairPayMonthVo.getPayOrigin()/10000));
		}
		map.put("list3", list4);
		return map;
	}
	

	//巡检情况项目列表
	@Override
	public List<InspectionTaskVo> getInspectionTaskStatis(InspectionTaskVo params) {
    	try {
    		Date today = new Date();
    		//统计类型 1按月，2按季度，3按年
    		if("2".equals(params.getType())) {
    			String[] quarterDate = DateUtils.getQuarterDate(today);
    			Date end = DateUtils.parseDate(quarterDate[2], DateUtils.HYPHENS_DATE);
    			params.setInspectionTimeStart(DateUtils.parseDate(quarterDate[0], DateUtils.HYPHENS_DATE));
    			params.setInspectionTimeEnd(DateUtils.getLastDayForMonth(end,2));
    		}else if("3".equals(params.getType())) {
    			params.setInspectionTimeStart(DateUtils.getFirstDayForYear(today));
    			params.setInspectionTimeEnd(DateUtils.getDayEnd(today));
    		}else {
    			params.setInspectionTimeStart(DateUtils.getFirstDayForMonth(today));
    			params.setInspectionTimeEnd(DateUtils.getLastDayForMonth(today,2));
    		}
			List<InspectionTaskVo> list = tbInspectionTaskMapper.getInspectionTaskStatis(params);
			return list;
		} catch (Exception e) {
			log.error("业务中心-巡检情况项目查询出错", e);
		}
    	return new ArrayList<>();
	}

	//巡检情况整体统计
	@Override
	public List<InspectionTaskVo> getInspectionTaskTotalStatis(InspectionTaskVo params) {
    	try {
    		List<InspectionTaskVo> totals = new ArrayList<>();
    		Date today = new Date();
    		params.setInspectionTimeStart(DateUtils.getFirstDayForMonth(today));
    		params.setInspectionTimeEnd(DateUtils.getLastDayForMonth(today,2));
			List<InspectionTaskVo> list = tbInspectionTaskMapper.getInspectionTaskMonthStatis(params);
			Map<String,Integer> map = list.stream().collect(Collectors.toMap(InspectionTaskVo::getTitle,InspectionTaskVo::getTotal));
			
			String month = DateUtils.formatDate(today, DateUtils.HYPHENS_MONTH);
			InspectionTaskVo mvo = new InspectionTaskVo();
			mvo.setTitle("month");
			if(map.containsKey(month)) {
				mvo.setTotal(map.get(month));
			}
			totals.add(mvo);

			String[] quarterDate = DateUtils.getQuarter(today);
			InspectionTaskVo qvo = new InspectionTaskVo();
			qvo.setTitle("quarter");
			for(String str:quarterDate) {
				if(map.containsKey(str)) {
					qvo.setTotal(qvo.getTotal()+map.get(str));
				}
			}
			totals.add(qvo);

			InspectionTaskVo yvo = new InspectionTaskVo();
			yvo.setTitle("year");
			for(InspectionTaskVo item:list) {
				yvo.setTotal(yvo.getTotal()+item.getTotal());
			}
			totals.add(yvo);

			return totals;
		} catch (Exception e) {
			log.error("业务中心-巡检情况统计出错", e);
		}
    	return new ArrayList<>();
	}
    

	//客户拜访情况项目列表
	@Override
	public List<CustomerFollowVo> getCustomerFollowStatis(CustomerFollowVo params) {
    	try {
    		Date today = new Date();
    		//统计类型 1按月，2按季度，3按年
    		if("2".equals(params.getType())) {
    			String[] quarterDate = DateUtils.getQuarterDate(today);
    			Date end = DateUtils.parseDate(quarterDate[2], DateUtils.HYPHENS_DATE);
    			params.setReviewTimeStart(DateUtils.parseDate(quarterDate[0], DateUtils.HYPHENS_DATE));
    			params.setReviewTimeEnd(DateUtils.getLastDayForMonth(end,2));
    		}else if("3".equals(params.getType())) {
    			params.setReviewTimeStart(DateUtils.getFirstDayForYear(today));
    			params.setReviewTimeEnd(DateUtils.getDayEnd(today));
    		}else {
    			params.setReviewTimeStart(DateUtils.getFirstDayForMonth(today));
    			params.setReviewTimeEnd(DateUtils.getLastDayForMonth(today,2));
    		}
			List<CustomerFollowVo> list = tbCustomerFollowMapper.getCustomerFollowStatis(params);
			return list;
		} catch (Exception e) {
			log.error("业务中心-客户拜访情况项目查询出错", e);
		}
    	return new ArrayList<>();
	}

	//客户拜访情况整体统计
	@Override
	public List<CustomerFollowVo> getCustomerFollowTotalStatis(CustomerFollowVo params) {
    	try {
    		List<CustomerFollowVo> totals = new ArrayList<>();
    		Date today = new Date();
			params.setReviewTimeStart(DateUtils.getFirstDayForYear(today));
			params.setReviewTimeEnd(DateUtils.getDayEnd(today));
			List<CustomerFollowVo> list = tbCustomerFollowMapper.getCustomerFollowMonthStatis(params);
			Map<String,Integer> map = list.stream().collect(Collectors.toMap(CustomerFollowVo::getTitle,CustomerFollowVo::getTotal));
			
			String month = DateUtils.formatDate(today, DateUtils.HYPHENS_MONTH);
			CustomerFollowVo mvo = new CustomerFollowVo();
			mvo.setTitle("month");
			if(map.containsKey(month)) {
				mvo.setTotal(map.get(month));
			}
			totals.add(mvo);

			String[] quarterDate = DateUtils.getQuarter(today);
			CustomerFollowVo qvo = new CustomerFollowVo();
			qvo.setTitle("quarter");
			for(String str:quarterDate) {
				if(map.containsKey(str)) {
					qvo.setTotal(qvo.getTotal()+map.get(str));
				}
			}
			totals.add(qvo);

			CustomerFollowVo yvo = new CustomerFollowVo();
			yvo.setTitle("year");
			for(CustomerFollowVo item:list) {
				yvo.setTotal(yvo.getTotal()+item.getTotal());
			}
			totals.add(yvo);

			return totals;
		} catch (Exception e) {
			log.error("业务中心-客户拜访情况统计出错", e);
		}
    	return new ArrayList<>();
	}
    
    
}
