package com.iformall.service.impl;

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.MallUserInfo;
import com.iformall.domain.po.WxBillAction;
import com.iformall.domain.po.WxBillDeposit;
import com.iformall.domain.po.WxPayAccountBill;
import com.iformall.enums.EnumBillAction;
import com.iformall.enums.EnumBillPayWay;
import com.iformall.enums.EnumBillRentStatus;
import com.iformall.enums.EnumDelStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxBillDepositMapper;
import com.iformall.service.WxBillActionService;
import com.iformall.service.WxBillDepositService;
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 java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    WxBillDepositMapper wxBillDepositMapper;

    @Autowired
    WxBillActionService wxBillActionService;

    @Autowired
    WxPayAccountBillService wxPayAccountBillService;

    @Override
    public PageInfo<WxBillDeposit> listAsPage(WxBillDeposit record, Integer pageIndex, Integer pageSize) {
        WxPayAccountBill wxPayAccountBill = wxPayAccountBillService.getByTenantId(record.getTenantId());
        PageHelper.startPage(pageIndex, pageSize);
        List<WxBillDeposit> billDepositList = wxBillDepositMapper.queryBillDepositList(record);
        billDepositList.stream().forEach(e->{
            //手续费 = 合同应收+手续费+滞纳金
            computeTotalMoney(wxPayAccountBill, e);
        });
        PageInfo<WxBillDeposit> pageInfo = new PageInfo<>(billDepositList);
        return pageInfo;
    }

    @Override
    public void computeTotalMoney(WxPayAccountBill wxPayAccountBill, WxBillDeposit deposit) {
        if (deposit.getReceivePay() != null) {
            Long receivePayB = deposit.getReceivePay();
            BigDecimal servicePay;
            if (deposit.getServiceChargePay() != null) {
                servicePay = new BigDecimal(deposit.getServiceChargePay());
            } else {
                servicePay = new BigDecimal(receivePayB).multiply(new BigDecimal(wxPayAccountBill.getServiceChargeRate())).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP);
            }
            Long realReceivePay = servicePay.longValue() + receivePayB;
            deposit.setRealReceivePay(realReceivePay);
            deposit.setServiceChargePay(servicePay.intValue());
        }
    }

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

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

    @Override
    public WxBillDeposit getById(Long id) {
        WxBillDeposit record = new WxBillDeposit();
        record.setId(id);
        return wxBillDepositMapper.queryBillDepositList(record).get(0);
    }

    @Override
    public ResultData saveOrUpdate(WxBillDeposit 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("新增租赁押金账单");
            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 {
                wxBillDepositMapper.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("更新租赁押金账单");
            WxBillDeposit wxBillDeposit = wxBillDepositMapper.selectById(record.getId());
            if(wxBillDeposit==null){
                return new ResultData(ErrorCode.BILL_RENT_DEPOSIT_IS_NOT_FOUND);
            }
            Long addpay = wxBillDeposit.getPay();
            wxBillDeposit.setPay(record.getPay());
            wxBillDeposit.setReceivePay(record.getReceivePay());
            wxBillDeposit.setOwe(record.getReceivePay()-record.getPay());
            if (record.getPay().equals(record.getReceivePay())) {
                wxBillDeposit.setStatus(EnumBillRentStatus.PAID.getCode());
                Date receiveDate = wxBillDeposit.getReceiveDate();
                wxBillDeposit.setExpiredDay(0L);
                if (date.after(receiveDate)) {
                    int expiredDay = DateUtils.daysBetween(receiveDate, date);
                    wxBillDeposit.setExpiredDay((long) expiredDay);
                }
            }
            wxBillDeposit.setPayDate(date);
            wxBillDeposit.setUpdatetime(date);
            wxBillDeposit.setPayWay(record.getPayWay());
            try {
                wxBillDepositMapper.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.getPay() - addpay).divide(new BigDecimal(100)).toPlainString();
            wxBillAction.setDetails(message + price + "元");
            wxBillAction.setAction(EnumBillAction.OFFLINE_PAY.getCode());
            wxBillAction.setUserId(user.getId());
            wxBillAction.setUserName(user.getName());
            wxBillAction.setPhone(user.getPhone());
            wxBillAction.setTenantId(wxBillDeposit.getTenantId());
            wxBillAction.setPayDate(wxBillDeposit.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, "更新租赁押金账单成功", wxBillDeposit);
        }
    }

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

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillDeposit wxBillDeposit = wxBillDepositMapper.selectById(id);
        if(wxBillDeposit==null){
            return new ResultData(ErrorCode.BILL_RENT_DEPOSIT_IS_NOT_FOUND);
        }
        wxBillDeposit.setStatus(EnumBillRentStatus.PAID.getCode());
        Date d =new Date();
        wxBillDeposit.setPayDate(d);
        wxBillDeposit.setUpdatetime(d);
        try {
            wxBillDepositMapper.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, "租赁押金结单成功");
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData returnDeposit(WxBillDeposit record, MallUserInfo user) {
        logger.info("租赁押金退还");
        WxBillDeposit wxBillDeposit = wxBillDepositMapper.selectById(record.getId());
        if (wxBillDeposit == null) {
            return new ResultData(ErrorCode.BILL_RENT_DEPOSIT_IS_NOT_FOUND);
        }
        wxBillDeposit.setPayWay(record.getPayWay());
        wxBillDeposit.setReturnPrice(record.getReturnPrice());
        wxBillDeposit.setStatus(EnumBillRentStatus.RETURN.getCode());
        wxBillDeposit.setUpdatetime(new Date());
        try {
            wxBillDepositMapper.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(WxBillDeposit record) {
        logger.info("租赁押金调整");
        WxBillDeposit wxBillDeposit = wxBillDepositMapper.selectById(record.getId());
        if (wxBillDeposit == null) {
            return new ResultData(ErrorCode.BILL_RENT_DEPOSIT_IS_NOT_FOUND);
        }
        wxBillDeposit.setReceivePay(record.getReceivePay());
        wxBillDeposit.setOwe(record.getReceivePay() - record.getPay());
        wxBillDeposit.setUpdatetime(new Date());
        try {
            wxBillDepositMapper.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);
    }


}
