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.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.*;
import com.iformall.enums.*;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxBillOtherDepositMapper;
import com.iformall.mapper.WxShopMapper;
import com.iformall.service.ExcelService;
import com.iformall.service.WxBillActionService;
import com.iformall.service.WxBillOtherDepositService;
import com.iformall.service.WxPayAccountBillService;
import com.iformall.utils.DateUtils;
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.*;

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

    @Autowired
    WxBillOtherDepositMapper wxBillOtherDepositMapper;

    @Autowired
    WxShopMapper wxShopMapper;

    @Autowired
    WxBillActionService wxBillActionService;

    @Autowired
    ExcelService excelService;

    @Autowired
    WxPayAccountBillService wxPayAccountBillService;

    @Override
    public PageInfo<WxBillOtherDeposit> listAsPage(WxBillOtherDeposit record, Integer pageIndex, Integer pageSize) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(record.getTenantId());
        //分页对象设置页数和条数
        PageHelper.startPage(pageIndex, pageSize);
        //查询
        List<WxBillOtherDeposit> billList = wxBillOtherDepositMapper.queryBillList(record);
        billList.stream().forEach(e->{
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });
        //结果放入分页对象
        PageInfo<WxBillOtherDeposit> pageInfo = new PageInfo<>(billList);
        return pageInfo;

    }

    public void computeTotalMoney(WxPayAccountBill wxPayAccountBill, WxBillOtherDeposit e) {
        if (e.getReceivePay() != null) {
            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.getReceivePay();
            e.setRealReceivePay(realReceivePay);
            e.setServiceChargePay(servicePay.intValue());
        }
    }

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

    @Transactional(rollbackFor = {Exception.class})
    public void updateWaidPayStatus(WxBillOtherDeposit record) {
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", record.getTenantId());
        params.put("waitPay", EnumBillDailyStatus.WAIT_PAY.getCode());
        params.put("paid", EnumBillRentStatus.PAID.getCode());
        try {
            wxBillOtherDepositMapper.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(WxBillOtherDeposit record) {
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", record.getTenantId());
        params.put("notPaid", EnumBillDailyStatus.NOT_PAID.getCode());
        params.put("paid", EnumBillRentStatus.PAID.getCode());
        try {
            wxBillOtherDepositMapper.updateNotPaidStatus(params);
        } catch (Exception e) {
            logger.error("更新其他欠缴账单状态失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
        }
    }

    @Override
    public WxBillOtherDeposit getById(Long id) {
        WxBillOtherDeposit record = new WxBillOtherDeposit();
        record.setId(id);
        WxBillOtherDeposit wxBillOther = wxBillOtherDepositMapper.queryBillList(record).get(0);
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(record.getTenantId());
        computeTotalMoney(wxPayAccountBill, record);
        record.setOwe(record.getRealReceivePay() - record.getPay());
        if (wxBillOther.getShopId() != null) {
            WxShop shop = new WxShop();
            shop.setId(wxBillOther.getShopId());
            List<Map<String, Object>> shoplist = wxShopMapper.findListMap(shop);
            wxBillOther.setShops(shoplist);
        } else {
            wxBillOther.setShops(Collections.EMPTY_LIST);
        }
        return wxBillOther;
    }

    @Override
    public ResultData saveOrUpdate(WxBillOtherDeposit 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.getCode(), "实收金额不能大于实际应收金额");
        }
        Date date = new Date();
        if (record.getId() == null) {
            logger.info("新增其他账单");

            WxBillOtherDeposit otherDepositQuery = new WxBillOtherDeposit();
            otherDepositQuery.setTenantId(record.getTenantId());
            otherDepositQuery.setMerchantId(record.getMerchantId());
            otherDepositQuery.setReceiveDate(record.getReceiveDate());
            otherDepositQuery.setComments(record.getComments());
            otherDepositQuery.setIsDel(EnumDelStatus.NOT_DEL.getCode());
            WxBillOtherDeposit otherDeposit = wxBillOtherDepositMapper.selectOne(new QueryWrapper(otherDepositQuery));
            if (otherDeposit != null) {
                return new ResultData(ErrorCode.BILL_IS_FOUND);
            }

            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            record.setStatus(EnumBillDailyStatus.WAIT_PAY.getCode());
            record.setCreatetime(date);
            record.setUpdatetime(date);
            record.setExpiredDay(0L);
            record.setOwe(record.getReceivePay() - record.getPay());
            record.setIsDel(EnumDelStatus.NOT_DEL.getCode());
            try {
                wxBillOtherDepositMapper.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("更新其他押金账单");
            WxBillOtherDeposit wxBillOtherDeposit = wxBillOtherDepositMapper.selectById(record.getId());
            if (wxBillOtherDeposit == null) {
                return new ResultData(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND);
            }
            String message = "";
            String price = "";
            if(record.getServiceChargePayUpdate() != null){
                Double l = Double.valueOf(record.getServiceChargePayUpdate())*100;
                wxBillOtherDeposit.setServiceChargePay(l.intValue());
            }else{
                Long addpay = wxBillOtherDeposit.getPay();
                wxBillOtherDeposit.setPayDate(record.getPayDate());
                wxBillOtherDeposit.setPay(record.getPay());
                wxBillOtherDeposit.setReceivePay(record.getReceivePay());
                wxBillOtherDeposit.setOwe(record.getRealReceivePay() - record.getPay());
                if (record.getPay().equals(record.getReceivePay())) {
                    wxBillOtherDeposit.setStatus(EnumBillRentStatus.PAID.getCode());
                    Date payDate = record.getPayDate();
                    Date receiveDate = wxBillOtherDeposit.getReceiveDate();
                    wxBillOtherDeposit.setExpiredDay(0L);
                    if (payDate.after(receiveDate)) {
                        int expiredDay = DateUtils.daysBetween(receiveDate, payDate);
                        wxBillOtherDeposit.setExpiredDay((long) expiredDay);
                    }
                }
                wxBillOtherDeposit.setPayDate(record.getPayDate());
                wxBillOtherDeposit.setUpdatetime(date);
                wxBillOtherDeposit.setPayWay(record.getPayWay());
                wxBillOtherDeposit.setComments(record.getComments());
                message = EnumBillPayWay.getEnum(record.getPayWay()).getMessage();
                price = new BigDecimal(record.getPay() - addpay).divide(new BigDecimal(100)).toPlainString();
            }

            try {
                wxBillOtherDepositMapper.updateById(wxBillOtherDeposit);
            } 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(wxBillOtherDeposit.getId());
            wxBillAction.setDetails(message + price + "元");
            if(record.getServiceChargePayUpdate() != null){
                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(wxBillOtherDeposit.getTenantId());
            wxBillAction.setPayDate(wxBillOtherDeposit.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, "更新其他账单成功");
        }
    }


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

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillOtherDeposit wxBillOtherDeposit = wxBillOtherDepositMapper.selectById(id);
        if (wxBillOtherDeposit == null) {
            return new ResultData(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND);
        }
        wxBillOtherDeposit.setStatus(EnumBillDailyStatus.PAID.getCode());
        Date d = new Date();
        wxBillOtherDeposit.setPayDate(d);
        wxBillOtherDeposit.setUpdatetime(d);
        try {
            wxBillOtherDepositMapper.updateById(wxBillOtherDeposit);
        } catch (Exception e) {
            logger.error("其他押金账单结单失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), e.getMessage());
        }
        return new ResultData(Result.SUCCESS, "其他押金账单结单成功");
    }

    @Override
    public ResultData returnDeposit(WxBillOtherDeposit record, MallUserInfo user) {
        logger.info("其他押金退还");
        WxBillOtherDeposit wxBillDeposit = wxBillOtherDepositMapper.selectById(record.getId());
        if (wxBillDeposit == null) {
            return new ResultData(ErrorCode.BILL_OTHER_DEPOSIT_IS_NOT_FOUND);
        }
        wxBillDeposit.setReturnPrice(record.getReturnPrice());
        wxBillDeposit.setStatus(EnumBillRentStatus.RETURN.getCode());
        wxBillDeposit.setUpdatetime(new Date());
        try {
            wxBillOtherDepositMapper.updateById(wxBillDeposit);
        } 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(wxBillDeposit.getId());
        String message = EnumBillPayWay.getEnum(record.getPayWay()).getMessage();
        String price = new BigDecimal(record.getReturnPrice()).divide(new BigDecimal(100)).toPlainString();
        wxBillAction.setDetails(message + price + "元");
        wxBillAction.setAction(EnumBillAction.DEPOSIT_RETURN.getCode());
        wxBillAction.setUserId(user.getId());
        wxBillAction.setUserName(user.getName());
        wxBillAction.setPhone(user.getPhone());
        wxBillAction.setTenantId(wxBillDeposit.getTenantId());
        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, "押金退还成功", wxBillDeposit);
    }

    @Override
    public ResultData adjustDeposit(WxBillOtherDeposit record) {
        logger.info("其他押金调整");
        WxBillOtherDeposit wxBillDeposit = wxBillOtherDepositMapper.selectById(record.getId());
        if (wxBillDeposit == null) {
            return new ResultData(ErrorCode.BILL_OTHER_DEPOSIT_IS_NOT_FOUND);
        }
        wxBillDeposit.setReceivePay(record.getReceivePay());
        wxBillDeposit.setOwe(record.getReceivePay() - record.getPay());
        wxBillDeposit.setUpdatetime(new Date());
        try {
            wxBillOtherDepositMapper.updateById(wxBillDeposit);
        } catch (Exception e) {
            logger.error("其他押金退还失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
        }
        return new ResultData(Result.SUCCESS, "其他押金调整成功", wxBillDeposit);
    }

    @Override
    public void exportBill(HttpServletRequest request, HttpServletResponse response, WxBillOtherDeposit wxBillDeposit) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(wxBillDeposit.getTenantId());
        List<WxBillOtherDeposit> datalist = wxBillOtherDepositMapper.queryBillList(wxBillDeposit);
        datalist.stream().forEach(e->{
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });
        excelService.exportExcel(datalist, null, "其他押金账单", WxBillOtherDeposit.class, "其他押金账单.xlsx", response, false);
    }


}
