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.WxBillDaily;
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.WxBillDailyMapper;
import com.iformall.mapper.WxShopMapper;
import com.iformall.service.WxBillDailyService;
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 WxBillDailyServiceImpl implements WxBillDailyService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxBillDailyMapper wxBillDailyMapper;

    @Autowired
    WxShopMapper wxShopMapper;

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

    }

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

    @Transactional(rollbackFor = {Exception.class})
    public void updateWaidPayStatus(WxBillDaily 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 {
            wxBillDailyMapper.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(WxBillDaily 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 {
            wxBillDailyMapper.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) {
        WxBillDaily record = new WxBillDaily();
        record.setId(id);
        Map<String, Object> wxBillDaily = wxBillDailyMapper.queryBillDailyList(record).get(0);

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

        return wxBillDaily;
    }

    @Override
    public ResultData saveOrUpdate(WxBillDaily 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(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 {
                wxBillDailyMapper.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("更新日常押金账单");
            WxBillDaily wxBillDaily = wxBillDailyMapper.selectByPrimaryKey(record.getId());
            if(wxBillDaily==null){
                return new ResultData(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND);
            }
            wxBillDaily.setPayDate(record.getPayDate());
            wxBillDaily.setPay(record.getPay());
            wxBillDaily.setReceivePay(record.getReceivePay());
            wxBillDaily.setOwe(record.getReceivePay()-record.getPay());
            wxBillDaily.setStatus(record.getPay().equals(record.getReceivePay()) ? EnumBillDailyStatus.PAID.getCode() : wxBillDaily.getStatus());
            wxBillDaily.setUpdatetime(new Date());
            try {
                wxBillDailyMapper.updateByPrimaryKeySelective(wxBillDaily);
            } 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) {
        wxBillDailyMapper.deleteByPrimaryKey(id);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public ResultData updatePaid(Long id) {
        WxBillDaily wxBillDaily = wxBillDailyMapper.selectByPrimaryKey(id);
        if(wxBillDaily==null){
            return new ResultData(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND);
        }
        wxBillDaily.setStatus(EnumBillDailyStatus.PAID.getCode());
        Date d =new Date();
        wxBillDaily.setPayDate(d);
        wxBillDaily.setUpdatetime(d);
        try {
            wxBillDailyMapper.updateByPrimaryKeySelective(wxBillDaily);
        } catch (Exception e) {
            logger.error("日常账单结单失败,e:" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL.getCode(),e.getMessage());
        }
        return new ResultData(Result.SUCCESS, "日常账单结单成功");
    }
    
    
    
    
    
    
}
