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.WxBillPropertyDeposit;
import com.iformall.enums.EnumBillRentStatus;
import com.iformall.enums.EnumDelStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxBillPropertyDepositMapper;
import com.iformall.service.WxBillPropertyDepositService;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    WxBillPropertyDepositMapper wxBillPropertyDepositMapper;


    @Override
    public PageInfo<Map<String, Object>> listAsPage(WxBillPropertyDeposit record, Integer pageIndex, Integer pageSize) {
        //更新账单状态
        //updateBillStatus(record);
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> billDepositList = wxBillPropertyDepositMapper.queryBillDepositList(record);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(billDepositList);
        return pageInfo;
    }

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


    @Transactional(rollbackFor = {Exception.class})
    public void updateWaidPayStatus(WxBillPropertyDeposit 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 {
            wxBillPropertyDepositMapper.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(WxBillPropertyDeposit 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 {
            wxBillPropertyDepositMapper.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) {
        WxBillPropertyDeposit record = new WxBillPropertyDeposit();
        record.setId(id);
        return wxBillPropertyDepositMapper.queryBillDepositList(record).get(0);
    }

    @Override
    public ResultData saveOrUpdate(WxBillPropertyDeposit 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.setCreatetime(date);
            record.setUpdatetime(date);
            record.setOwe(record.getReceivePay()-record.getPay());
            record.setIsDel(EnumDelStatus.NOT_DEL.getCode());
            try {
                wxBillPropertyDepositMapper.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("更新押金账单");
            WxBillPropertyDeposit wxBillDeposit = wxBillPropertyDepositMapper.selectByPrimaryKey(record.getId());
            if(record==null){
                return new ResultData(ErrorCode.BILL_PROPERTY_DEPOSIT_IS_NOT_FOUND);
            }
            wxBillDeposit.setPayDate(record.getPayDate());
            wxBillDeposit.setPay(record.getPay());
            wxBillDeposit.setReceivePay(record.getReceivePay());
            wxBillDeposit.setOwe(record.getReceivePay()-record.getPay());
            wxBillDeposit.setStatus(record.getPay().equals(record.getReceivePay())?EnumBillRentStatus.PAID.getCode():wxBillDeposit.getStatus());
            wxBillDeposit.setUpdatetime(new Date());
            try {
                wxBillPropertyDepositMapper.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 void deleteById(Long id) {
        wxBillPropertyDepositMapper.deleteByPrimaryKey(id);
    }

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

    @Override
    public ResultData returnDeposit(WxBillPropertyDeposit record) {
        logger.info("物业押金退还");
        WxBillPropertyDeposit wxBillDeposit = wxBillPropertyDepositMapper.selectByPrimaryKey(record.getId());
        if (wxBillDeposit == null) {
            return new ResultData(ErrorCode.BILL_PROPERTY_DEPOSIT_IS_NOT_FOUND);
        }
        wxBillDeposit.setReturnPrice(record.getReturnPrice());
        wxBillDeposit.setStatus(EnumBillRentStatus.RETURN.getCode());
        wxBillDeposit.setUpdatetime(new Date());
        try {
            wxBillPropertyDepositMapper.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(WxBillPropertyDeposit record) {
        logger.info("物业押金调整");
        WxBillPropertyDeposit wxBillDeposit = wxBillPropertyDepositMapper.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 {
            wxBillPropertyDepositMapper.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);
    }


}
