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.WxBillDeposit;
import com.iformall.domain.po.WxBillRent;
import com.iformall.enums.EnumBillRentStatus;
import com.iformall.enums.EnumDelStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxBillDepositMapper;
import com.iformall.mapper.WxBillRentMapper;
import com.iformall.service.WxBillRentService;
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 WxBillRentServiceImpl implements WxBillRentService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxBillRentMapper wxBillRentMapper;

    @Autowired
    WxBillDepositMapper wxBillDepositMapper;

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

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

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

    @Override
    public ResultData saveOrUpdate(WxBillRent record) {
        int receivepay = record.getReceivePay().intValue();
        int pay = record.getPay().intValue();
        if(pay>receivepay){
            return new ResultData(ErrorCode.BILL_PAY_ERROR,"实收金额不能大于实际应收金额");
        }
        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 {
                wxBillRentMapper.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("更新租赁账单");
            WxBillRent wxBillRent = wxBillRentMapper.selectByPrimaryKey(record.getId());
            if(wxBillRent==null){
                return new ResultData(ErrorCode.BILL_RENT_IS_NOT_FOUND);
            }
            wxBillRent.setRevenue(record.getRevenue());
            wxBillRent.setLatePayRatio(record.getLatePayRatio());
            wxBillRent.setLatePayTime(record.getLatePayTime());
            wxBillRent.setPayDate(record.getPayDate());
            wxBillRent.setPay(record.getPay());
            wxBillRent.setReceivePay(record.getReceivePay());
            wxBillRent.setOwe(record.getReceivePay()-record.getPay());
            wxBillRent.setStatus(record.getPay().equals(record.getReceivePay())?EnumBillRentStatus.PAID.getCode():wxBillRent.getStatus());
            wxBillRent.setUpdatetime(new Date());
            try {
                wxBillRentMapper.updateByPrimaryKeySelective(wxBillRent);
            } 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) {
        wxBillRentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<Map<String, Object>> findByRentContractId(Long id, String tenantId, Integer pageIndex, Integer pageSize) {
        WxBillRent record = new WxBillRent();
        record.setRentContractId(id);
        record.setTenantId(tenantId);
        record.setSortColumns(WxBillRent.Field.Id_ASC);
        updateBillStatus(record);
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> billRentList = wxBillRentMapper.queryBillRentList(record);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(billRentList);
        return pageInfo;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillRent wxBillRent = wxBillRentMapper.selectByPrimaryKey(id);
        if(wxBillRent==null){
            return new ResultData(ErrorCode.BILL_RENT_IS_NOT_FOUND);
        }
        wxBillRent.setStatus(EnumBillRentStatus.PAID.getCode());
        Date d =new Date();
        wxBillRent.setPayDate(d);
        wxBillRent.setUpdatetime(d);
        try {
            wxBillRentMapper.updateByPrimaryKeySelective(wxBillRent);
        } 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 Object detail(Long id) {
        //租赁
        Map<String, Object> rent = getById(id);
        //押金
        WxBillDeposit depositParam = new WxBillDeposit();
        depositParam.setRentContractId((Long) rent.get("rentContractId"));
        Map<String, Object> deposit = null;
        List<Map<String, Object>> billDepositList = wxBillDepositMapper.queryBillDepositList(depositParam);
        if (!billDepositList.isEmpty()) {
            deposit = billDepositList.get(0);
        }
        //周期
        Map<String, Object> result = new HashMap<>(3);
        result.put("rent", rent);
        result.put("deposit", deposit);
        return result;
    }

    @Override
    public ResultData updateRevenue(WxBillRent record) {
        WxBillRent wxBillRent = wxBillRentMapper.selectByPrimaryKey(record.getId());
        wxBillRent.setRevenue(record.getRevenue());
        wxBillRent.setUpdatetime(new Date());
        try {
            wxBillRentMapper.updateByPrimaryKeySelective(wxBillRent);
        } catch (Exception e) {
            logger.error("修改营业额失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
        }
        return new ResultData(Result.SUCCESS, "修改营业额成功");
    }

}
