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.WxBillProperty;
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.mapper.WxBillPropertyMapper;
import com.iformall.service.WxBillPropertyService;
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 WxBillPropertyServiceImpl implements WxBillPropertyService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxBillPropertyMapper wxBillPropertyMapper;

    @Autowired
    WxBillPropertyDepositMapper wxBillPropertyDepositMapper;

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

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

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

    @Override
    public ResultData saveOrUpdate(WxBillProperty 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 {
                wxBillPropertyMapper.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("更新物业账单");
            WxBillProperty property = wxBillPropertyMapper.selectByPrimaryKey(record.getId());
            if(property==null){
                return new ResultData(ErrorCode.BILL_PROPERTY_IS_NOT_FOUND);
            }
            property.setRevenue(record.getRevenue());
            property.setLatePayRatio(record.getLatePayRatio());
            property.setLatePayTime(record.getLatePayTime());
            property.setPayDate(record.getPayDate());
            property.setPay(record.getPay());
            property.setReceivePay(record.getReceivePay());
            property.setOwe(record.getReceivePay()-record.getPay());
            property.setStatus(record.getPay().equals(record.getReceivePay())?EnumBillRentStatus.PAID.getCode():property.getStatus());
            property.setUpdatetime(new Date());
            try {
                wxBillPropertyMapper.updateByPrimaryKeySelective(property);
            } catch (Exception e) {
                logger.error("更新物业账单失败,e:" + e.getMessage());
                throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage());
            }
            return new ResultData(Result.SUCCESS, "更新物业账单成功", property);
        }
    }

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

    @Override
    public PageInfo<Map<String, Object>> findByPropertyContractId(Long id, String tenantId, Integer pageIndex, Integer pageSize) {
        WxBillProperty record = new WxBillProperty();
        record.setPropertyContractId(id);
        record.setTenantId(tenantId);
        record.setSortColumns(WxBillProperty.Field.Id_ASC);
        updateBillStatus(record);
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> billRentList = wxBillPropertyMapper.queryBillPropertyList(record);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(billRentList);
        return pageInfo;
    }


    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillProperty record = wxBillPropertyMapper.selectByPrimaryKey(id);
        if(record==null){
            return new ResultData(ErrorCode.BILL_PROPERTY_IS_NOT_FOUND);
        }
        record.setStatus(EnumBillRentStatus.PAID.getCode());
        Date d =new Date();
        record.setPayDate(d);
        record.setUpdatetime(d);
        try {
            wxBillPropertyMapper.updateByPrimaryKeySelective(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, "结单成功");
    }

    @Override
    public Object detail(Long id) {
        //物业
        Map<String, Object> property = getById(id);
        //押金
        WxBillPropertyDeposit depositParam = new WxBillPropertyDeposit();
        depositParam.setPropertyContractId((Long) property.get("propertyContractId"));
        Map<String, Object> deposit = null;
        List<Map<String, Object>> billDepositList = wxBillPropertyDepositMapper.queryBillDepositList(depositParam);
        if (!billDepositList.isEmpty()) {
            deposit = billDepositList.get(0);
        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("property", property);
        result.put("deposit", deposit);
        return result;
    }


}
