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.enums.*;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxBillActionMapper;
import com.iformall.mapper.WxBillPropertyDepositMapper;
import com.iformall.mapper.WxBillPropertyMapper;
import com.iformall.service.*;
import com.iformall.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
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.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    WxBillPropertyMapper wxBillPropertyMapper;

    @Autowired
    WxBillPropertyDepositMapper wxBillPropertyDepositMapper;

    @Autowired
    WxBillActionService wxBillActionService;

    @Autowired
    ExcelService excelService;

    @Autowired
    WxBillActionMapper wxBillActionMapper;
    @Autowired
    WxPayAccountBillService wxPayAccountBillService;
    @Autowired
    WxBillPropertyDepositService wxBillPropertyDepositService;


    @Override
    public PageInfo<WxBillProperty> listAsPage(WxBillProperty record, Integer pageIndex, Integer pageSize) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(record.getTenantId());
        PageHelper.startPage(pageIndex, pageSize);
        List<WxBillProperty> billRentList = wxBillPropertyMapper.queryBillPropertyList(record);
        billRentList.stream().forEach(e -> {
            computeTotalMoney(wxPayAccountBill, e);

        });
        PageInfo<WxBillProperty> pageInfo = new PageInfo<>(billRentList);
        return pageInfo;
    }

    public void computeTotalMoney(WxPayAccountBill wxPayAccountBill, WxBillProperty e) {
        //手续费 = 合同应收+手续费+滞纳金
        if (e.getReceivePay() != null) {
            if (e.getLatePayPrice() == null) {
                long latePayPrice = 0L;
                e.setLatePayPrice(latePayPrice);
            }
            BigDecimal servicePay;
            if (e.getServiceChargePay() != null) {
                servicePay = new BigDecimal(e.getServiceChargePay());
            } else {
                servicePay = new BigDecimal(e.getReceivePay()).multiply(new BigDecimal(wxPayAccountBill.getServiceChargeRate())).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
            }
            Long realReceivePay = servicePay.longValue() + e.getLatePayPrice() + e.getReceivePay();
            e.setRealReceivePay(realReceivePay);
            e.setServiceChargePay(servicePay.intValue());
        }
    }

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

    @Transactional(rollbackFor = {Exception.class})
    public void updateWaidPayStatus(WxBillProperty 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 {
            wxBillPropertyMapper.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(WxBillProperty 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 {
            wxBillPropertyMapper.updateNotPaidStatus(params);
        } catch (Exception e) {
            logger.error("更新物业欠缴账单状态失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
        }
    }

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

    @Override
    public ResultData saveOrUpdate(WxBillProperty 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 {
                wxBillPropertyMapper.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("更新物业账单");
            WxBillProperty property = wxBillPropertyMapper.selectById(record.getId());
            if (property == null) {
                return new ResultData(ErrorCode.BILL_PROPERTY_IS_NOT_FOUND);
            }

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

            try {
                wxBillPropertyMapper.updateById(property);
            } 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(property.getId());

            wxBillAction.setDetails(message + price + "元");
            if (record.getServiceChargePayUpdate() != null) {
                wxBillAction.setDetails(record.getServiceChargePayBefore() + "元变更为" + record.getServiceChargePayUpdate() + "元");
                wxBillAction.setAction(EnumBillAction.UPDATE_SERVICE_MONEY.getCode());
            } else {
                wxBillAction.setAction(EnumBillAction.OFFLINE_PAY.getCode());
            }
            wxBillAction.setUserId(user.getId());
            wxBillAction.setUserName(user.getName());
            wxBillAction.setPhone(user.getPhone());
            wxBillAction.setTenantId(property.getTenantId());
            wxBillAction.setPayDate(property.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, "更新物业账单成功", property);
        }
    }

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

    @Override
    public PageInfo<WxBillProperty> findByPropertyContractId(Long id, String tenantId, Integer pageIndex, Integer pageSize) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(tenantId);
        WxBillProperty record = new WxBillProperty();
        record.setPropertyContractId(id);
        record.setTenantId(tenantId);
        record.setSortColumns(BaseEntity.SortField.Id_ASC);
        updateBillStatus(record);
        PageHelper.startPage(pageIndex, pageSize);
        List<WxBillProperty> billRentList = wxBillPropertyMapper.queryBillPropertyList(record);
        billRentList.stream().forEach(e -> {
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });

        PageInfo<WxBillProperty> pageInfo = new PageInfo<>(billRentList);
        return pageInfo;
    }


    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillProperty record = wxBillPropertyMapper.selectById(id);
        if (record == null) {
            return new ResultData(ErrorCode.BILL_PROPERTY_IS_NOT_FOUND);
        }
        record.setStatus(EnumBillRentStatus.PAID.getCode());
        Date d = new Date();
        record.setPayDate(d);
        record.setUpdatetime(d);
        try {
            wxBillPropertyMapper.updateById(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, "结单成功");
    }

    @Override
    public Object detail(Long id) {
        //物业
        WxBillProperty property = getById(id);
        //押金
        WxBillPropertyDeposit depositParam = new WxBillPropertyDeposit();
        depositParam.setPropertyContractId(property.getPropertyContractId());
        WxBillPropertyDeposit deposit = null;
        List<WxBillPropertyDeposit> billDepositList = wxBillPropertyDepositMapper.queryBillDepositList(depositParam);
        if (!billDepositList.isEmpty()) {
            WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(property.getTenantId());
            deposit = billDepositList.get(0);
            wxBillPropertyDepositService.computeTotalMoney(wxPayAccountBill, deposit);
            deposit.setOwe(deposit.getRealReceivePay() - deposit.getPay());

        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("property", property);
        result.put("deposit", deposit);
        return result;
    }

    @Override
    public ResultData updateLatePayStatus(WxBillProperty record) {
        record.setLatePayStatus(EnumBillDailyStatus.PAID.getCode());
        record.setUpdatetime(new Date());
        try {
            wxBillPropertyMapper.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, WxBillProperty wxBillProperty) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(wxBillProperty.getTenantId());
        String billName = wxBillProperty.getRentShopType().equals(EnumRentShopType.SHOP.getCode()) ? "商铺物业账单" : "多经点位物业账单";

        List<WxBillProperty> billPropertyList = wxBillPropertyMapper.queryBillPropertyList(wxBillProperty);
        billPropertyList.stream().forEach(e -> {
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });
        Map<Long, List<WxBillProperty>> collect = billPropertyList.parallelStream()
                .collect(Collectors.groupingBy(WxBillProperty::getMerchantId));
        Set<Map.Entry<Long, List<WxBillProperty>>> entries = collect.entrySet();
        List<WxBillProperty> datalist = new ArrayList<>();
        for (Map.Entry<Long, List<WxBillProperty>> entry : entries) {
            List<WxBillProperty> list = entry.getValue();
            for (WxBillProperty property : list) {
                if (property.getDepositStatus() == null) {
                    property.setDepositStatus(0);
                }
                String shopNumber = property.getShopNumber();
                if (StringUtils.isEmpty(shopNumber)) {
                    String shopInfo = property.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(","));
                        property.setShopNumber(sb.deleteCharAt(sb.length() - 1).toString());
                    }
                }
                datalist.add(property);
            }
        }
        excelService.exportExcel(datalist, null, billName, WxBillProperty.class, billName + ".xlsx", response, false);
    }

    @Override
    public ResultData updateLatePayMoney(WxBillProperty 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);
        }
        wxBillPropertyMapper.updateById(record);
        return new ResultData();
    }
}
