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.WxBillOtherDeposit;
import com.iformall.domain.po.WxShop;
import com.iformall.enums.EnumBillDailyStatus;
import com.iformall.enums.EnumBillRentStatus;
import com.iformall.enums.EnumDelStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxBillOtherDepositMapper;
import com.iformall.mapper.WxShopMapper;
import com.iformall.service.WxBillOtherDepositService;
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.util.*;

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

    @Autowired
    WxBillOtherDepositMapper wxBillOtherDepositMapper;

    @Autowired
    WxShopMapper wxShopMapper;

    @Override
    public PageInfo<Map<String, Object>> listAsPage(WxBillOtherDeposit record, Integer pageIndex, Integer pageSize) {
        //更新账单状态
        //updateBillStatus(record);
        //分页对象设置页数和条数
        PageHelper.startPage(pageIndex, pageSize);
        //查询
        List<Map<String, Object>> billList = wxBillOtherDepositMapper.queryBillList(record);
        //结果放入分页对象
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(billList);
        return pageInfo;

    }

    @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 Map<String, Object> getById(Long id) {
        WxBillOtherDeposit record = new WxBillOtherDeposit();
        record.setId(id);
        Map<String, Object> wxBillOther = wxBillOtherDepositMapper.queryBillList(record).get(0);

        if (wxBillOther.get("shopId") != null) {
            WxShop shop = new WxShop();
            shop.setId((Long) wxBillOther.get("shopId"));
            List<Map<String, Object>> shoplist = wxShopMapper.findListMap(shop);
            wxBillOther.put("shops", shoplist);
        } else {
            wxBillOther.put("shops", Collections.EMPTY_LIST);
        }

        return wxBillOther;
    }

    @Override
    public ResultData saveOrUpdate(WxBillOtherDeposit record) {
        int receivepay = record.getReceivePay().intValue();
        int pay = record.getPay().intValue();
        if (pay > receivepay) {
            return new ResultData(ErrorCode.BILL_PAY_ERROR.getCode(), "实收金额不能大于实际应收金额");
        }
        if (record.getId() == null) {
            logger.info("新增其他账单");
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            Date date = new Date();
            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.insertSelective(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.selectByPrimaryKey(record.getId());
            if (wxBillOtherDeposit == null) {
                return new ResultData(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND);
            }
            wxBillOtherDeposit.setPayDate(record.getPayDate());
            wxBillOtherDeposit.setPay(record.getPay());
            wxBillOtherDeposit.setReceivePay(record.getReceivePay());
            wxBillOtherDeposit.setOwe(record.getReceivePay() - record.getPay());
            wxBillOtherDeposit.setStatus(record.getPay().equals(record.getReceivePay()) ? EnumBillDailyStatus.PAID.getCode() : wxBillOtherDeposit.getStatus());
            wxBillOtherDeposit.setUpdatetime(new Date());
            try {
                wxBillOtherDepositMapper.updateByPrimaryKeySelective(wxBillOtherDeposit);
            } 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.deleteByPrimaryKey(id);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillOtherDeposit wxBillOtherDeposit = wxBillOtherDepositMapper.selectByPrimaryKey(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.updateByPrimaryKeySelective(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) {
        logger.info("其他押金退还");
        WxBillOtherDeposit wxBillDeposit = wxBillOtherDepositMapper.selectByPrimaryKey(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.updateByPrimaryKeySelective(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 ResultData adjustDeposit(WxBillOtherDeposit record) {
        logger.info("其他押金调整");
        WxBillOtherDeposit wxBillDeposit = wxBillOtherDepositMapper.selectByPrimaryKey(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.updateByPrimaryKeySelective(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);
    }


}
