package com.thinkgem.jeesite.modules.youka.service;

import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.dao.DictDao;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.youka.dao.YoukaCardDao;
import com.thinkgem.jeesite.modules.youka.dao.YoukaSettlementDao;
import com.thinkgem.jeesite.modules.youka.entity.YoukaBenefit;
import com.thinkgem.jeesite.modules.youka.entity.YoukaCardEntity;
import com.thinkgem.jeesite.modules.youka.entity.YoukaSettlement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 结算
 */
@Service
@Transactional(readOnly = true)
public class YoukaSettlementService extends BaseService{

    @Autowired
    private YoukaSettlementDao dao;

    @Autowired
    private YoukaBenefitService youkaBenefitService;

    @Autowired
    private DictService dictService;

    /**
     * 结算
     * @param settlement
     */
    @Transactional(readOnly = false)
    public void save(YoukaSettlement settlement){
        settlement.setCreateDate(new Date());
        settlement.setCreateBy(UserUtils.getUser().getId());
        dao.insert(settlement);
        String date = settlement.getSettlementDate();
        if(!StringUtils.isBlank(date)){
            int year = Integer.valueOf(date.substring(0,4));
            int month = Integer.valueOf(date.substring(5));

            String endTime = DateUtils.getLastDayOfMonth(year,month)+" 23:59:59";
            YoukaBenefit youkaBenefit = new YoukaBenefit();
            youkaBenefit.setPayChannel(settlement.getPayChannel());
            youkaBenefit.setPayMethod(settlement.getPayMethod());
            youkaBenefit.setEndDate(endTime);
            youkaBenefitService.updateBenefitByDate(youkaBenefit);
        }
    }

    /**
     * 查看是否已经结算
     * @param youkaSettlement
     * @return
     */
    public YoukaSettlement get(YoukaSettlement youkaSettlement){
        return dao.get(youkaSettlement);
    }

    public List<YoukaSettlement> getList(YoukaSettlement youkaSettlement){
        List<YoukaSettlement> list = new ArrayList<>();
        Dict dict = new Dict();
        dict.setType("pay_method");
        List<Dict> dictList = dictService.findList(dict);

        for(Dict dict1:dictList){
            youkaSettlement.setPayMethod(dict1.getValue());
            list.addAll(dao.getYoukaSettlementList(youkaSettlement));
        }

        return list;
    }
    
}
