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

    @Autowired
    WxBillOtherMapper wxBillOtherMapper;

    @Autowired
    WxShopMapper wxShopMapper;

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

    }

    @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 Map<String,Object> getById(Long id) {
        WxBillOther record = new WxBillOther();
        record.setId(id);
        Map<String, Object> wxBillOther = wxBillOtherMapper.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(WxBillOther 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.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.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("更新其他押金账单");
            WxBillOther wxBillOther = wxBillOtherMapper.selectByPrimaryKey(record.getId());
            if(wxBillOther==null){
                return new ResultData(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND);
            }
            wxBillOther.setPayDate(record.getPayDate());
            wxBillOther.setPay(record.getPay());
            wxBillOther.setReceivePay(record.getReceivePay());
            wxBillOther.setOwe(record.getReceivePay()-record.getPay());
            wxBillOther.setStatus(record.getPay().equals(record.getReceivePay()) ? EnumBillDailyStatus.PAID.getCode() : wxBillOther.getStatus());
            wxBillOther.setUpdatetime(new Date());
            try {
                wxBillOtherMapper.updateByPrimaryKeySelective(wxBillOther);
            } 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.deleteByPrimaryKey(id);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillOther wxBillOther = wxBillOtherMapper.selectByPrimaryKey(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.updateByPrimaryKeySelective(wxBillOther);
        } catch (Exception e) {
            logger.error("其他账单结单失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(),e.getMessage());
        }
        return new ResultData(Result.SUCCESS, "其他账单结单成功");
    }
    
    
    
    
    
    
}
