package com.goafanti.order.service.impl;

import com.goafanti.admin.service.DepartmentService;
import com.goafanti.common.dao.TOrderNewMapper;
import com.goafanti.common.dao.TOrderTaskMapper;
import com.goafanti.common.dao.UserMidMapper;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.order.bo.*;
import com.goafanti.order.bo.outStatistics.OutOrderNewSignBo;
import com.goafanti.order.enums.NewProjectStatus;
import com.goafanti.order.service.UserStaticticsService;
import groovy.util.logging.Log4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j
public class UserStatisticsServiceImpl extends BaseMybatisDao<UserMidMapper> implements UserStaticticsService {

	@Resource
	private DepartmentService departmentService;
	@Resource
	private TOrderTaskMapper tOrderTaskMapper;
	@Resource
	private TOrderNewMapper tOrderNewMapper;

	@Override
	public Pagination<OutSignSummary> signSummary(InputSignSummary in) {
		Map<String, Object> map = new HashMap<>();
		addSignSummaryParam(in, map);
		return (Pagination<OutSignSummary>) findPage("selectSignSummaryList","selectSignSummaryCount",map,in.getPageNo(),in.getPageSize());
	}

	private void addSignSummaryParam(InputSignSummary in, Map<String, Object> map) {
		if (in.getUserName()!=null) map.put("userName", in.getUserName());
		if (StringUtils.isNotBlank(in.getAid())) map.put("aid", in.getAid());
		if (in.getFollowAid()!=null) map.put("followAid", in.getFollowAid());
		if (in.getMember()!=null) map.put("member", in.getMember());
		if (in.getChargeback()!=null) map.put("chargeback", in.getChargeback());
		if (in.getBigCustomer()!=null) map.put("bigCustomer", in.getBigCustomer());
		if (in.getLastFollowType()!=null) map.put("lastFollowType", in.getLastFollowType());
		if (in.getDepId()!=null) map.put("depId", in.getDepId());
		if (in.getLastFollowTimeStart()!=null) map.put("lastFollowTimeStart", in.getLastFollowTimeStart());
		if (in.getLastFollowTimeEnd()!=null) map.put("lastFollowTimeEnd", in.getLastFollowTimeEnd()+" 23:59:59");
		if (in.getFirstSigningTimeStart()!=null) map.put("firstSigningTimeStart", in.getFirstSigningTimeStart());
		if (in.getFirstSigningTimeEnd()!=null) map.put("firstSigningTimeEnd", in.getFirstSigningTimeEnd()+" 23:59:59");
		if (in.getLastSigningTimeStart()!=null) map.put("lastSigningTimeStart", in.getLastSigningTimeStart());
		if (in.getLastSigningTimeEnd()!=null) map.put("lastSigningTimeEnd", in.getLastSigningTimeEnd()+" 23:59:59");
		if (in.getSignNumber()!=null) map.put("signNumber", in.getSignNumber());
		if (in.getLastSalesType()!=null) map.put("lastSalesType", in.getLastSalesType());
	}

	@Override
	public List<OutSignSummary> signSummaryList(InputSignSummary in) {
		Map<String, Object> map = new HashMap<>();
		addSignSummaryParam(in, map);
		return (List<OutSignSummary>) findList("selectSignSummaryList",map,1,9999);
	}

	@Override
	public Pagination<OutSignStatistics> signStatistics(InputSignStatistics in) {
		Map<String, Object> map = new HashMap<>();
		addsignStatisticsParam(in, map);
		return (Pagination<OutSignStatistics>) findPage("selectsignStatisticsList","selectsignStatisticsCount",map,in.getPageNo(),in.getPageSize());
	}
	@Override
	public List<OutSignStatistics> signStatisticsGetList(InputSignStatistics in) {
		Map<String, Object> map = new HashMap<>();
		addsignStatisticsParam(in, map);
		return (List<OutSignStatistics>) findList("selectsignStatisticsList",map,1,9999);
	}




    private void addsignStatisticsParam(InputSignStatistics in, Map<String, Object> map) {
		if (in.getDeps()!=null){
			map.put("deps",departmentService.parseArray(in.getDeps()));
		}
		if (StringUtils.isNotBlank(in.getAid())) map.put("aid", in.getAid());
		if (StringUtils.isNotBlank(in.getUid())) map.put("uid", in.getUid());
		if (in.getAmountType()!=null)map.put("amountType",in.getAmountType());
		if (in.getSignTimeStart()!=null)map.put("signTimeStart",in.getSignTimeStart());
		if (in.getSignTimeEnd()!=null)map.put("signTimeEnd",in.getSignTimeEnd()+" 23:59:59");
		if (in.getOrderType()!=null)map.put("orderType",in.getOrderType());
	}

	@Override
	public Pagination<TOrderNewBo> signStatisticsOrderList(InputSignStatistics in) {
		Map<String, Object> map = new HashMap<>();
		addsignStatisticsParam(in, map);
		return (Pagination<TOrderNewBo>) findPage("selectsignStatisticsOrderList","selectsignStatisticsOrderCount",map,in.getPageNo(),in.getPageSize());
	}

	@Override
	public Pagination<OutOrderProject> orderProject(InputOrderProject in) {
		Map<String, Object> map =new HashMap<>();
		if (in.getEndDate()!=null)in.setEndDate(in.getEndDate()+" 23:59:59");
		if (in.getProjectEndDate()!=null)in.setProjectEndDate(in.getProjectEndDate()+" 23:59:59");
		if (in.getSignEndDate()!=null)in.setSignEndDate(in.getSignEndDate()+" 23:59:59");
		if (in.getProjectCompleteEndTime()!=null)in.setProjectCompleteEndTime(in.getProjectCompleteEndTime()+" 23:59:59");
		pushOrderProjectParam(in, map);
		Pagination<OutOrderProject> page = (Pagination<OutOrderProject>) findPage("selectStatisticsOrderProjectList", "selectStatisticsOrderProjectCount", map, in.getPageNo(), in.getPageSize());
		List<OutOrderProject> outOrderProject = (List<OutOrderProject>) page.getList();
		for (OutOrderProject e : outOrderProject) {
			//计算比例 数据原型修改返回
			BigDecimal orderReceivables=BigDecimal.ZERO;
			if (e.getOrderReceivables()!=null)orderReceivables=e.getOrderReceivables();
			if (orderReceivables.compareTo(BigDecimal.ZERO)!=0){
				BigDecimal settlementAmount=BigDecimal.ZERO;
				if (e.getSettlementAmount()!=null)settlementAmount=e.getSettlementAmount();
				BigDecimal divide = settlementAmount.divide(orderReceivables, 2, RoundingMode.HALF_UP);
				BigDecimal multiply = divide.multiply(new BigDecimal(100));
				e.setContractAmountProportion(multiply+"%");
			}else {
				e.setContractAmountProportion("100%");
			}
			if (e.getRefundType()!=null&&e.getRefundType().equals("1")){
				e.setRefundType("是");
			}else {
				e.setRefundType("否");
			}
			if (e.getRestatementType()!=null&&e.getRestatementType().equals("1")){
				e.setRestatementType("是");
			}else {
				e.setRestatementType("否");
			}
			if (e.getSortType()!=null&&e.getSortType().equals("3")){
				StringBuilder sb = new StringBuilder();
				sb.append("是");
				if (e.getLvlType()==1)sb.append("，国家级");
				if (e.getLvlType()==2)sb.append("，省级");
				if (e.getLvlType()==3)sb.append("，市级");
				e.setSortType(sb.toString());
			}else {
				e.setSortType("否");
			}
			if (e.getProjectStatus()!=null){
				String valueByCode = NewProjectStatus.getValueByCode(Integer.valueOf(e.getProjectStatus()));
				e.setProjectStatus(valueByCode);
			}
			if(e.getSettlementAmount()!=null){
				if (e.getOrderReceivables().compareTo(BigDecimal.ZERO)==0){
					e.setArrearsAmount(BigDecimal.ZERO);
				}else {
					e.setArrearsAmount(e.getOrderReceivables().subtract(e.getSettlementAmount()));
				}
			}
			if(e.getChangeType().equals("0")){
				e.setChangeType("无");
			}else {
				e.setChangeType("更新"+e.getChangeType()+"次");
			}
			if (e.getOrderStatus()!=null){
				//0=待签单，1=签单待审，2=签单审核通过，3=签单审核拒绝，4=已结项，5=已驳回，6=已退单
				switch(e.getOrderStatus())
					{
					case "0":
						e.setOrderStatus("待签单");
						break;
					case "1":
						e.setOrderStatus("签单待审核");
						break;
					case "2":
						e.setOrderStatus("签单审核通过");
						break;
					case "3":
						e.setOrderStatus("签单审核拒绝");
						break;
					case "4":
						e.setOrderStatus("已结项");
						break;
					case "5":
						e.setOrderStatus("已驳回");
						break;
					case "6":
						e.setOrderStatus("已退单");
						break;
					default:
						e.setOrderStatus("未知");
				}
			}

		}
		return page;
	}



	@Override
	public String getOrderNewSignTime(InputOrderNewSignBo in) {
		if(in.getType()==null||in.getType()==0){
			in.setStartTime(DateUtils.parseDate(in.getStartTimeStr()));
			in.setEndTime(DateUtils.parseDate(in.getEndTimeStr()));
		}else if(in.getType()==1){
			//获取本周起止时间开始时间和结束时间
			// 获取当前日期
			LocalDate today = LocalDate.now();

			// 获取本周的开始时间（星期一）
			LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
			// 获取下周的周一作为结束时间
			LocalDate endOfWeek = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
			Date startDate = Date.from(startOfWeek.atStartOfDay(ZoneId.systemDefault()).toInstant());
			Date endDate = Date.from(endOfWeek.atStartOfDay(ZoneId.systemDefault()).toInstant());
			in.setStartTime(startDate);
			in.setEndTime(endDate);
		}else if(in.getType()==2){
			//获取本月第一天和下月第一天
			// 获取当前日期
			LocalDate today = LocalDate.now();
			// 获取本月的第一天
			LocalDate firstDayOfMonth = today.withDayOfMonth(1);
			// 获取下月的第一天
			LocalDate firstDayOfNextMonth = firstDayOfMonth.plusMonths(1);
			Date startDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
			Date endDate = Date.from(firstDayOfNextMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
			in.setStartTime(startDate);
			in.setEndTime(endDate);
		}
		String str=DateUtils.formatDateChineseYYYYMMdd(in.getStartTime())
				+"-"+DateUtils.formatDateChineseYYYYMMdd(in.getEndTime())
				+"订单新老客签单统计";
		return str;
	}

	@Override
	public List<OutOrderNewSignBo> orderNewSignToList(InputOrderNewSignBo in) {
		List<OutOrderNewSignBo> list=tOrderTaskMapper.orderNewSignToList(in);
		return list;
	}

	private void pushOrderProjectParam(InputOrderProject in, Map<String, Object> map) {
		Class<InputOrderProject> clazz= (Class<InputOrderProject>) in.getClass();
		Field[] declaredFields = clazz.getDeclaredFields();
		for (Field field : declaredFields) {
			field.setAccessible(true);

            try {
				String fieldName = field.getName();
                Object fieldValue =field.get(in);
				map.put(fieldName,fieldValue);
            } catch (IllegalAccessException e) {

                throw new BusinessException("");
            }
        }
	}
}
