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.WxBillOtherMapper;
import com.iformall.mapper.WxShopMapper;
import com.iformall.service.ExcelService;
import com.iformall.service.WxBillActionService;
import com.iformall.service.WxBillOtherService;
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 WxBillOtherServiceImpl implements WxBillOtherService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxBillOtherMapper wxBillOtherMapper;

    @Autowired
    WxShopMapper wxShopMapper;

    @Autowired
    WxBillActionService wxBillActionService;

    @Autowired
    ExcelService excelService;

    @Autowired
    WxPayAccountBillService wxPayAccountBillService;

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

    }

    public void computeTotalMoney(WxPayAccountBill wxPayAccountBill, WxBillOther 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(WxBillOther record) {
        logger.info("更新其他账单状态开始...");
        //更新逾期天数及状态
        updateNotPaidStatus(record);
        //更新待缴的状态
        updateWaidPayStatus(record);
        logger.info("更新其他账单状态结束...");
    }

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

    @Override
    public WxBillOther getById(Long id) {
        WxBillOther record = new WxBillOther();
        record.setId(id);
        WxBillOther wxBillOther = wxBillOtherMapper.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(WxBillOther 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("新增其他账单");
            WxBillOther otherQuery = new WxBillOther();
            otherQuery.setTenantId(record.getTenantId());
            otherQuery.setMerchantId(record.getMerchantId());
            otherQuery.setReceiveDate(record.getReceiveDate());
            otherQuery.setName(record.getName());
            otherQuery.setIsDel(EnumDelStatus.NOT_DEL.getCode());
            WxBillOther other = wxBillOtherMapper.selectOne(new QueryWrapper(otherQuery));
            if (other != null) {
                return new ResultData(ErrorCode.BILL_IS_FOUND);
            }
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            record.setStatus(record.getReceiveDate().after(date)?EnumBillDailyStatus.WAIT_PAY.getCode():EnumBillDailyStatus.NOT_PAID.getCode());
            record.setCreatetime(date);
            record.setUpdatetime(date);
            record.setExpiredDay(0L);
            record.setOwe(record.getReceivePay()-record.getPay());
            record.setIsDel(EnumDelStatus.NOT_DEL.getCode());
            try {
                wxBillOtherMapper.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("更新其他押金账单");
            WxBillOther wxBillOther = wxBillOtherMapper.selectById(record.getId());
            if(wxBillOther==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;
                wxBillOther.setServiceChargePay(l.intValue());
            }else{
                Long addpay = wxBillOther.getPay();
                wxBillOther.setPayDate(record.getPayDate());
                wxBillOther.setPay(record.getPay());
                wxBillOther.setReceivePay(record.getReceivePay());
                wxBillOther.setOwe(record.getRealReceivePay() - record.getPay());
                if (record.getPay().equals(record.getReceivePay())) {
                    wxBillOther.setStatus(EnumBillRentStatus.PAID.getCode());
                    Date payDate = record.getPayDate();
                    Date receiveDate = wxBillOther.getReceiveDate();
                    wxBillOther.setExpiredDay(0L);
                    if (payDate.after(receiveDate)) {
                        int expiredDay = DateUtils.daysBetween(receiveDate, payDate);
                        wxBillOther.setExpiredDay((long) expiredDay);
                    }
                }
                wxBillOther.setPayDate(record.getPayDate());
                wxBillOther.setUpdatetime(date);
                wxBillOther.setPayWay(record.getPayWay());
                wxBillOther.setComments(record.getComments());
                wxBillOther.setName(record.getName());
                message = EnumBillPayWay.getEnum(record.getPayWay()).getMessage();
                price = new BigDecimal(record.getPay() - addpay).divide(new BigDecimal(100)).toPlainString();
            }

            try {
                wxBillOtherMapper.updateById(wxBillOther);
            } 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(wxBillOther.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(wxBillOther.getTenantId());
            wxBillAction.setPayDate(wxBillOther.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) {
        wxBillOtherMapper.deleteById(id);
    }

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

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


}
