package com.iformall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.*;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.vo.RatioVo;
import com.iformall.enums.*;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.*;
import com.iformall.service.*;
import com.iformall.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author gongbiao
 */
@Service
public class WxBillRentServiceImpl implements WxBillRentService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxBillRentMapper wxBillRentMapper;
    @Autowired
    WxBillDepositMapper wxBillDepositMapper;
    @Autowired
    WxBillActionService wxBillActionService;
    @Autowired
    ExcelService excelService;
    @Autowired
    WxBillActionMapper wxBillActionMapper;
    @Autowired
    WxRentContractMapper wxRentContractMapper;
    @Autowired
    WxMerchantTradeDailyMapper wxMerchantTradeDailyMapper;
    @Autowired
    WxPayAccountBillService wxPayAccountBillService;
    @Autowired
    WxBillDepositService wxBillDepositService;

    @Override
    public PageInfo<WxBillRent> listAsPage(WxBillRent record, Integer pageIndex, Integer pageSize) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(record.getTenantId());

        PageHelper.startPage(pageIndex, pageSize);
        List<WxBillRent> billRentList = wxBillRentMapper.queryBillRentList(record);
        billRentList.stream().forEach(e->{
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });
        PageInfo<WxBillRent> pageInfo = new PageInfo<>(billRentList);
        return pageInfo;
    }

    public void computeTotalMoney(WxPayAccountBill wxPayAccountBill, WxBillRent rent) {
        if (rent.getReceivePay() != null) {
            if (rent.getLatePayPrice() == null) {
                rent.setLatePayPrice(0L);
            }
            BigDecimal servicePay;
            if (rent.getServiceChargePay() != null) {
                servicePay = new BigDecimal(rent.getServiceChargePay());
            } else {
                servicePay = new BigDecimal(rent.getReceivePay()).multiply(new BigDecimal(wxPayAccountBill.getServiceChargeRate())).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
            }
            Long realReceivePay = servicePay.longValue() + rent.getLatePayPrice() + rent.getReceivePay();
            rent.setRealReceivePay(realReceivePay);
            rent.setServiceChargePay(servicePay.intValue());
        }
    }

    @Override
    public void updateBillStatus(WxBillRent record) {
        logger.info("更新租赁账单状态开始...");
        //更新逾期天数及状态
        updateNotPaidStatus(record);
        //更新待缴的状态
        updateWaidPayStatus(record);
        logger.info("更新租赁账单状态结束...");
    }

    @Transactional(rollbackFor = {Exception.class})
    public void updateWaidPayStatus(WxBillRent record) {
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", record.getTenantId());
        params.put("waitPay", EnumBillRentStatus.WAIT_PAY.getCode());
        params.put("paid", EnumBillRentStatus.PAID.getCode());

        try {
            wxBillRentMapper.updateWaitPayStatus(params);
        } catch (Exception e) {
            logger.error("更新物业待缴账单状态失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
        }
    }


    @Transactional(rollbackFor = {Exception.class})
    public void updateNotPaidStatus(WxBillRent record) {
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", record.getTenantId());
        params.put("notPaid", EnumBillRentStatus.NOT_PAID.getCode());
        params.put("paid", EnumBillRentStatus.PAID.getCode());
        try {
            wxBillRentMapper.updateNotPaidStatus(params);
        } catch (Exception e) {
            logger.error("更新物业欠缴账单状态失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
        }
    }

    @Override
    public WxBillRent getById(Long id) {
        WxBillRent record = new WxBillRent();
        record.setId(id);
        WxBillRent rent = wxBillRentMapper.queryBillRentList(record).get(0);
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(record.getTenantId());
        //手续费 = 合同应收+手续费+滞纳金
        computeTotalMoney(wxPayAccountBill, rent);
        rent.setOwe(rent.getRealReceivePay() - rent.getPay());
        return rent;
    }

    @Override
    public ResultData saveOrUpdate(WxBillRent record, MallUserInfo user) {
        int receivepay = record.getReceivePay()==null?0:record.getReceivePay().intValue();
        int pay = record.getPay()==null?0:record.getPay().intValue();
        if(pay>receivepay){
            return new ResultData(ErrorCode.BILL_PAY_ERROR,"实收金额不能大于实际应收金额");
        }
        Date date = new Date();
        if (record.getId() == null) {
            logger.info("新增租赁账单");
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            record.setCreatetime(date);
            record.setUpdatetime(date);
            record.setOwe(record.getReceivePay()-record.getPay());
            record.setIsDel(EnumDelStatus.NOT_DEL.getCode());
            try {
                wxBillRentMapper.insert(record);
            } catch (Exception e) {
                logger.error("保存租赁账单失败,e:" + e.getMessage());
                throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
            }
            return new ResultData(Result.SUCCESS, "保存租赁账单成功");
        } else {
            logger.info("更新租赁账单");
            WxBillRent wxBillRent = wxBillRentMapper.selectById(record.getId());
            if(wxBillRent==null){
                return new ResultData(ErrorCode.BILL_RENT_IS_NOT_FOUND);
            }

            String price = "";
            String message ="";
            if(record.getServiceChargePayUpdate() != null){
                Double l = Double.valueOf(record.getServiceChargePayUpdate())*100;
                wxBillRent.setServiceChargePay(l.intValue());
            }else{
                Long addpay = wxBillRent.getPay();
                wxBillRent.setRevenue(record.getRevenue());
                wxBillRent.setLatePayRatio(record.getLatePayRatio());
                wxBillRent.setLatePayTime(record.getLatePayTime());
                wxBillRent.setLatePayStatus(record.getLatePayStatus());
                wxBillRent.setPay(record.getPay());
                wxBillRent.setReceivePay(record.getReceivePay());
                wxBillRent.setOwe(record.getRealReceivePay() - record.getPay());
                if (record.getPay().equals(record.getReceivePay())) {
                    wxBillRent.setStatus(EnumBillRentStatus.PAID.getCode());
                    Date payDate = record.getPayDate();
                    Date receiveDate = wxBillRent.getReceiveDate();
                    wxBillRent.setExpiredDay(0L);
                    if (payDate.after(receiveDate)) {
                        int expiredDay = DateUtils.daysBetween(receiveDate, payDate);
                        wxBillRent.setExpiredDay((long) expiredDay);
                    }
                }
                wxBillRent.setPayDate(record.getPayDate());
                wxBillRent.setUpdatetime(date);
                wxBillRent.setPayWay(record.getPayWay());
                price = new BigDecimal(record.getPay() - addpay).divide(new BigDecimal(100)).toPlainString();
            }

            try {
                wxBillRentMapper.updateById(wxBillRent);
            } catch (Exception e) {
                logger.error("更新租赁账单失败,e:" + e.getMessage());
                throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
            }
            //日志
            WxBillAction wxBillAction = new WxBillAction();
            wxBillAction.setBillId(wxBillRent.getId());
            if(record.getServiceChargePayUpdate() != null){
                wxBillAction.setDetails(record.getServiceChargePayBefore()+"元变更为" +record.getServiceChargePayUpdate()+"元");
                wxBillAction.setAction(EnumBillAction.UPDATE_SERVICE_MONEY.getCode());
            }else{
                wxBillAction.setAction(EnumBillAction.OFFLINE_PAY.getCode());
                message = EnumBillPayWay.getEnum(record.getPayWay()).getMessage();
            }
            wxBillAction.setDetails(message + price + "元");
            wxBillAction.setUserId(user.getId());
            wxBillAction.setUserName(user.getName());
            wxBillAction.setPhone(user.getPhone());
            wxBillAction.setTenantId(wxBillRent.getTenantId());
            wxBillAction.setPayDate(wxBillRent.getPayDate());
            try {
                wxBillActionService.save(wxBillAction);
            } catch (Exception e) {
                logger.error("添加租赁账单行为日志,e:" + e.getMessage());
                throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
            }
            return new ResultData(Result.SUCCESS, "更新租赁账单成功", wxBillRent);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxBillRentMapper.deleteById(id);
    }

    @Override
    public PageInfo<WxBillRent> findByRentContractId(Long id, String tenantId, Integer pageIndex, Integer pageSize) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(tenantId);
        WxBillRent record = new WxBillRent();
        record.setRentContractId(id);
        record.setTenantId(tenantId);
        record.setSortColumns(BaseEntity.SortField.Id_ASC);
        PageHelper.startPage(pageIndex, pageSize);
        List<WxBillRent> billRentList = wxBillRentMapper.queryBillRentList(record);
        billRentList.stream().forEach(e->{
            if(e.getPayRatio() == null){
                e.setPayRatio(0l);
            }
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });
        PageInfo<WxBillRent> pageInfo = new PageInfo<>(billRentList);
        return pageInfo;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillRent wxBillRent = wxBillRentMapper.selectById(id);
        if(wxBillRent==null){
            return new ResultData(ErrorCode.BILL_RENT_IS_NOT_FOUND);
        }
        wxBillRent.setStatus(EnumBillRentStatus.PAID.getCode());
        Date d =new Date();
        wxBillRent.setPayDate(d);
        wxBillRent.setUpdatetime(d);
        try {
            wxBillRentMapper.updateById(wxBillRent);
        } catch (Exception e) {
            logger.error("租赁账单结单失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
        }
        return new ResultData(Result.SUCCESS, "租赁账单结单成功");
    }

    @Override
    public Object detail(Long id) {
        //租赁
        WxBillRent rent = getById(id);
        //押金
        WxBillDeposit depositParam = new WxBillDeposit();
        depositParam.setRentContractId(rent.getRentContractId());
        WxBillDeposit deposit = null;
        List<WxBillDeposit> billDepositList = wxBillDepositMapper.queryBillDepositList(depositParam);
        if (!billDepositList.isEmpty()) {
            WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(rent.getTenantId());
            deposit = billDepositList.get(0);
            wxBillDepositService.computeTotalMoney(wxPayAccountBill, deposit);
            deposit.setOwe(deposit.getRealReceivePay() - deposit.getPay());
        }
        //周期
        Map<String, Object> result = new HashMap<>(3);
        result.put("rent", rent);
        result.put("deposit", deposit);

        //解单金额
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        WxBillRent billRent = wxBillRentMapper.selectById(id);
        WxMerchantTradeDaily merchantTradeDaily = new WxMerchantTradeDaily();
        merchantTradeDaily.setMerchantId(billRent.getMerchantId());
        merchantTradeDaily.setStartTime(sd.format(billRent.getStarttime()));
        merchantTradeDaily.setEndTime(sd.format(billRent.getEndtime()));
        String money = wxMerchantTradeDailyMapper.findSumMoney(merchantTradeDaily);
        result.put("solutionBillMoney", StringUtils.isBlank(money)?0:money);

        return result;
    }


    public static int getMonths(String startStr,String endStr){
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        DateTime start = formatter.parseDateTime(startStr);
        DateTime end = formatter.parseDateTime(endStr);
        int months = Months.monthsBetween(start, end).getMonths();
        return months;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ResultData updateRevenue(WxBillRent record, MallUserInfo user) {
        WxBillRent wxBillRent = wxBillRentMapper.selectById(record.getId());
        WxRentContract wxRentContract = wxRentContractMapper.selectById(wxBillRent.getRentContractId());
        SimpleDateFormat sdD = new SimpleDateFormat("d");
        SimpleDateFormat sdM = new SimpleDateFormat("yyyy-MM");

        int startInt = Integer.parseInt(sdD.format(wxBillRent.getStarttime()));
        int endInt = Integer.parseInt(sdD.format(DateUtils.getDaySet(wxBillRent.getEndtime(),Calendar.DATE,1)));
        int months = getMonths(sdM.format(wxBillRent.getStarttime())+"-01",sdM.format(DateUtils.getDaySet(wxBillRent.getEndtime(),Calendar.DATE,1))+"-01");

        wxBillRent.setRevenue(record.getRevenue());

        Integer ratio = 0;
        RatioVo ratioVo = null;
        if(wxRentContract.getPayRatio() != null && wxRentContract.getPayRatio().intValue() > 0){
            ratio = wxRentContract.getPayRatio();
        }else{
            if(StringUtils.isNotBlank(wxRentContract.getBusDiscountRatio())){
                long dayCount = DateUtils.startToEnd(wxBillRent.getStarttime(),wxBillRent.getEndtime()) + 1;
                if(EnumBusRatioTime.YEAR.getCode().equals(wxRentContract.getBusDiscountTime())){
                    if(startInt == endInt && months == 12){
                        //刚好1年
                        ratioVo = WxRentContractServiceImpl.getPayRatio(EnumGetRatioFrom.BILL.getCode(),wxBillRent.getRevenue(),wxRentContract.getBusDiscountRatio(),EnumMissTimeType.OTHER.getCode(),dayCount,0);
                    }else{
                        ratioVo = WxRentContractServiceImpl.getPayRatio(EnumGetRatioFrom.BILL.getCode(),wxBillRent.getRevenue(),wxRentContract.getBusDiscountRatio(),EnumMissTimeType.YEAR.getCode(),dayCount,0);
                    }
                }else if(EnumBusRatioTime.MONTH.getCode().equals(wxRentContract.getBusDiscountTime())){
                    if(startInt == endInt && months == 1){
                        //刚好1个月
                        ratioVo = WxRentContractServiceImpl.getPayRatio(EnumGetRatioFrom.BILL.getCode(),wxBillRent.getRevenue(),wxRentContract.getBusDiscountRatio(),EnumMissTimeType.OTHER.getCode(),dayCount,0);
                    }else{
                        ratioVo = WxRentContractServiceImpl.getPayRatio(EnumGetRatioFrom.BILL.getCode(),wxBillRent.getRevenue(),wxRentContract.getBusDiscountRatio(),EnumMissTimeType.MONTH.getCode(),dayCount,0);
                    }
                }else if(EnumBusRatioTime.PERIOD.getCode().equals(wxRentContract.getBusDiscountTime())){
                    ratioVo = WxRentContractServiceImpl.getPayRatio(EnumGetRatioFrom.BILL.getCode(),wxBillRent.getRevenue(),wxRentContract.getBusDiscountRatio(),EnumMissTimeType.PERIOD.getCode(),dayCount,wxRentContract.getReceivePeriod());
                }
            }
        }

        long newReceivePay;
        if(ratioVo != null){
            newReceivePay = ratioVo.getPrice();
            //wxBillRent.setPayRatio(ratioVo.getRatio().longValue());
            //如果在跳点区间中，修改扣点率
            if(StringUtils.isNotBlank(wxRentContract.getBusDiscountRatio())){
                wxBillRent.setBusDiscountRatio(ratioVo.getUseRatio());
            }
        }else{
            BigDecimal hundred = new BigDecimal(100);
            BigDecimal revenue = new BigDecimal(record.getRevenue() == null ? 0 : record.getRevenue()).divide(hundred);
            BigDecimal payRatio = new BigDecimal(ratio).divide(new BigDecimal(10000));
            BigDecimal price = revenue.multiply(payRatio).setScale(2, RoundingMode.HALF_EVEN);
            newReceivePay = price.multiply(hundred).longValue();
        }
        wxBillRent.setJoinRentPrice(newReceivePay);
        if(newReceivePay > wxBillRent.getReceivePay()){
            wxBillRent.setReceivePay(newReceivePay);
        }

        Long oldPrice = wxBillRent.getReceivePay();
        Long newPrice = newReceivePay;
        wxBillRent.setUpdatetime(new Date());

        wxBillRentMapper.updateById(wxBillRent);

        if (!oldPrice.equals(newPrice)) {
            //日志
            WxBillAction wxBillAction = new WxBillAction();
            wxBillAction.setBillId(wxBillRent.getId());
            String oldPriceStr = new BigDecimal(oldPrice).divide(new BigDecimal(100)).toPlainString();
            String newPriceStr = new BigDecimal(newPrice).divide(new BigDecimal(100)).toPlainString();
            wxBillAction.setDetails("录入营业额时应收金额" + oldPriceStr + "元变更成" + newPriceStr + "元");
            wxBillAction.setAction(EnumBillAction.UPDATE_BILL.getCode());
            wxBillAction.setUserId(user.getId());
            wxBillAction.setUserName(user.getName());
            wxBillAction.setPhone(user.getPhone());
            wxBillAction.setTenantId(wxBillRent.getTenantId());
            try {
                wxBillActionService.save(wxBillAction);
            } catch (Exception e) {
                logger.error("添加租赁账单行为日志,e:" + e.getMessage());
                throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "修改营业额失败");
            }
        }
        return new ResultData(Result.SUCCESS, "修改营业额成功", wxBillRent);
    }

    @Override
    public ResultData updateLatePayStatus(WxBillRent record) {
        record.setLatePayStatus(EnumBillDailyStatus.PAID.getCode());
        record.setUpdatetime(new Date());
        try {
            wxBillRentMapper.updateById(record);
        } catch (Exception e) {
            logger.error("修改营业额失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "滞纳金结单失败");
        }
        return new ResultData(Result.SUCCESS, "滞纳金结单成功", record);
    }

    @Override
    public void exportBill(HttpServletRequest request, HttpServletResponse response, WxBillRent wxBillRent) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(wxBillRent.getTenantId());

        String billName = wxBillRent.getRentShopType().equals(EnumRentShopType.SHOP.getCode()) ? "商铺租金账单" : "多经点位租金账单";
        List<WxBillRent> billRentList = wxBillRentMapper.queryBillRentList(wxBillRent);
        billRentList.stream().forEach(e->{
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });
        Map<Long, List<WxBillRent>> collect = billRentList.parallelStream()
                .collect(Collectors.groupingBy(WxBillRent::getMerchantId));
        Set<Map.Entry<Long, List<WxBillRent>>> entries = collect.entrySet();
        List<WxBillRent> datalist = new ArrayList<>();
        for (Map.Entry<Long, List<WxBillRent>> entry : entries) {
            List<WxBillRent> list = entry.getValue();
            for (WxBillRent rent : list) {
                if (rent.getDepositStatus() == null) {
                    rent.setDepositStatus(0);
                }
                String shopNumber = rent.getShopNumber();
                if (StringUtils.isEmpty(shopNumber)) {
                    String shopInfo = rent.getShopInfo();
                    if (StringUtils.isNotEmpty(shopInfo) && !shopInfo.equals("[]")) {
                        JSONObject jsonObject = JSONObject.parseObject(shopInfo);
                        StringBuffer sb = new StringBuffer();
                        Set<Map.Entry<String, Object>> sets = jsonObject.entrySet();
                        sets.forEach(x -> sb.append(x.getKey()).append(","));
                        rent.setShopNumber(sb.deleteCharAt(sb.length() - 1).toString());
                    }
                }
                datalist.add(rent);
            }
        }
        excelService.exportExcel(datalist, null, billName, WxBillRent.class, billName + ".xlsx", response, false);
    }

    @Override
    public ResultData updateLatePayMoney(WxBillRent record, MallUserInfo user) {
        final IdWorker idWorker = IdWorker.get();
        WxBillAction billAction = new WxBillAction();

        if(record.getLatePayMoneyUpdate() != null) {
            record.setLatePayPrice(Long.parseLong(record.getLatePayMoneyUpdate()) * 100);

            billAction.setId(idWorker.nextId());
            billAction.setCreatetime(new Date());
            billAction.setUserName("系统端");
            billAction.setAction(EnumBillAction.UPDATE_LATE_PAY_MONEY.getCode());
            billAction.setBillId(record.getId());
            billAction.setDetails(record.getLatePayMoneyBefore()+"元变更为" +record.getLatePayMoneyUpdate()+"元");
            billAction.setUpdatetime(new Date());
            wxBillActionMapper.insert(billAction);
        }
        wxBillRentMapper.updateById(record);
        return new ResultData();
    }
}
