package com.iformall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxBusiness;
import com.iformall.domain.po.WxPropertyContract;
import com.iformall.domain.po.WxRentContract;
import com.iformall.enums.*;
import com.iformall.mapper.WxBusinessMapper;
import com.iformall.mapper.WxPropertyContractMapper;
import com.iformall.mapper.WxRentContractMapper;
import com.iformall.service.WxBusinessService;
import com.iformall.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class WxBusinessServiceImpl implements WxBusinessService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxBusinessMapper wxBusinessMapper;
    @Autowired
    private WxRentContractMapper wxRentContractMapper;
    @Autowired
    private WxPropertyContractMapper wxPropertyContractMapper;

    @Override
    public PageInfo<WxBusiness> listAsPage(WxBusiness record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxBusinessMapper.findList(record));
    }

    @Override
    public List<WxBusiness> findList(WxBusiness record) {
        return wxBusinessMapper.findList(record);
    }

    @Override
    public List<WxBusiness> findListAll(String tenantId, Integer filter) {
        if (filter == null)
            return wxBusinessMapper.findListAll();
        else if (filter.equals(EnumBusinessFilter.FILTER_BY_COUPON.getCode()))
            return wxBusinessMapper.findListForCoupon(tenantId);
        else if (filter.equals(EnumBusinessFilter.FILTER_BY_MERCHANT.getCode()))
            return wxBusinessMapper.findListForMerchant(tenantId);
        else
            return wxBusinessMapper.findListAll();
    }


    @Override
    public WxBusiness getById(Integer id) {
        return wxBusinessMapper.selectById(id);
    }

    @Override
    public List<WxBusiness> getByIds(Collection<? extends Serializable> ids) {
        return wxBusinessMapper.selectBatchIds(ids);
    }


    @Override
    public List<Map<String, Object>> businessDataList(WxBusiness wxBusiness, Long userid) {
        //1 得到天数+1
        int day = DateUtils.daysBetween(wxBusiness.getStartdate(), wxBusiness.getEnddate()) + 1;
        List<Map<String, Object>> resultList = wxBusinessMapper.businessDataList(wxBusiness);
        resultList.stream().forEach(e -> {
            BigDecimal businessSumMoney = new BigDecimal(0);
            WxRentContract query = new WxRentContract();
            query.setBusinessId((Integer) e.get("id"));
            List<WxRentContract> rentContractList = wxRentContractMapper.selectList(new QueryWrapper<>(query));
            for (WxRentContract dbRent : rentContractList) {
                if (dbRent.getStatus().equals(EnumRentContractStatus.INTENTION.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.WAIT_SIGN.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.CONTRACT_END.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.CONTRACT_TERMINATE.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.INVALID.getCode())) {
                    System.out.println("rent rentInfo is null:{}" + dbRent.getId());
                    continue;
                }
                Long price = dbRent.getPrice();
                Integer priceUnit = dbRent.getPriceUnit();
                Integer type = dbRent.getType();
                Integer period = dbRent.getReceivePeriod();
                Integer busDiscountTime = dbRent.getBusDiscountTime();
                BigDecimal priceDecimal = getPriceDecimal(day, price, priceUnit, type, period, busDiscountTime);
                businessSumMoney = businessSumMoney.add(priceDecimal);
            }

            WxPropertyContract pquery = new WxPropertyContract();
            pquery.setBusinessId((Integer) e.get("id"));
            List<WxPropertyContract> propertyContractList = wxPropertyContractMapper.selectList(new QueryWrapper<>(pquery));
            for (WxPropertyContract dbRent : propertyContractList) {
                if (dbRent.getStatus().equals(EnumRentContractStatus.INTENTION.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.WAIT_SIGN.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.CONTRACT_END.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.CONTRACT_TERMINATE.getCode()) ||
                        dbRent.getStatus().equals(EnumRentContractStatus.INVALID.getCode())) {
                    System.out.println("property rentInfo is null:{}" + dbRent.getId());
                    continue;
                }
                logger.info("业态分析>>>>>>>>>>>>>>>>>>物业合同ID:" + dbRent.getId());
                Long price = dbRent.getPrice();
                Integer priceUnit = dbRent.getPriceUnit();
                BigDecimal priceDecimal = getPriceDecimal(day, price, priceUnit, EnumRentContractType.RENT_BY_AREA.getCode(), null, null);
                businessSumMoney = businessSumMoney.add(priceDecimal);
            }
            logger.info("业态分析>>>>>>>>>>>>>>>>>>商铺面积:" + e.get("area").toString());
            if (e.get("area") == null || "0".equals(e.get("area").toString()) ||
                    "0.0".equals(e.get("area").toString())) {
                e.put("rent", 0);
            } else {
                BigDecimal area = new BigDecimal(e.get("area").toString());
                if (area.doubleValue() > 0) {
                    BigDecimal areaRatio = businessSumMoney.divide(area, 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    e.put("rent", areaRatio.toPlainString());
                }
            }
        });
        return resultList;
    }


    /**
     * 1按面积 1日(price*day) 2月(price/31*day) 3年(price/365*day)
     * 2联营 1年(price/365*day) 2月(price/31*day) 3周期 (price/period/31*day)
     * 3取其高 与按面积 相同
     */
    public BigDecimal getPriceDecimal(int day, Long price, Integer priceUnit, Integer type, Integer period, Integer busDiscountTime) {
        if (EnumRentContractType.RENT_BY_JOINT.getCode().equals(type)) {
            if (EnumBusRatioTime.YEAR.getCode().equals(busDiscountTime)) {
                return new BigDecimal(price).divide(new BigDecimal(365), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(day));
            }
            if (EnumBusRatioTime.MONTH.getCode().equals(busDiscountTime)) {
                return new BigDecimal(price).divide(new BigDecimal(31), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(day));
            }
            return new BigDecimal(price).divide(new BigDecimal(31).multiply(new BigDecimal(period)), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(day));
        } else {
            if (EnumPriceUnit.D.getCode().equals(priceUnit)) {
                return new BigDecimal(price).multiply(new BigDecimal(day));
            }
            if (EnumPriceUnit.M.getCode().equals(priceUnit)) {
                return new BigDecimal(price).divide(new BigDecimal(31), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(day));
            }
            return new BigDecimal(price).divide(new BigDecimal(365), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(day));
        }
    }

    @Override
    public ResultData devoteList(WxBusiness wxBusiness, Integer pageNum, Integer pageSize) {
        wxBusiness.setLimitStart(0);
        wxBusiness.setLimitEnd(Integer.MAX_VALUE);
        List totalList = wxBusinessMapper.devoteList(wxBusiness);
        if (CollectionUtils.isEmpty(totalList)) {
            PageHelper.startPage(pageNum, pageSize);
            PageInfo<List<Map<String, Object>>> pageInfo = new PageInfo(new ArrayList());
            pageInfo.setPages(0);
            pageInfo.setTotal(0);
            PageHelper.clearPage();
            return new ResultData(pageInfo);
        }

        int total = totalList.size();
        int pages;
        if (total % pageSize == 0) {
            pages = total / pageSize;
        } else {
            pages = total / pageSize + 1;
        }
        wxBusiness.setLimitStart((pageNum - 1) * pageSize);
        wxBusiness.setLimitEnd(pageSize);
        List<Map<String, Object>> list = wxBusinessMapper.devoteList(wxBusiness);

        PageHelper.startPage(pageNum, pageSize);
        PageInfo<List<Map<String, Object>>> pageInfo = new PageInfo(list);
        pageInfo.setPages(pages);
        pageInfo.setTotal(total);
        PageHelper.clearPage();
        return new ResultData(pageInfo);
    }

}
