package com.iformall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.IdWorker;
import com.iformall.domain.dto.WxCUserBasicInfoDto;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.po.WxLevelConfig;
import com.iformall.domain.po.WxLevelMerchant;
import com.iformall.domain.vo.WxLevelMerchantCVo;
import com.iformall.mapper.WxCUserBasicInfoMapper;
import com.iformall.mapper.WxLevelConfigMapper;
import com.iformall.mapper.WxLevelMerchantMapper;
import com.iformall.service.WxLevelConfigService;
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.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WxLevelConfigServiceImpl implements WxLevelConfigService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final static String CAPABILITY_SEND_CAR_COUPON = "carCouponCount";
	@Autowired
    WxLevelConfigMapper wxLevelConfigMapper;

    @Autowired
    WxLevelMerchantMapper wxLevelMerchantapper;

    @Autowired
    WxCUserBasicInfoMapper wxCUserBasicInfoMapper;

    @Override
    public PageInfo<WxLevelConfig> listAsPage(WxLevelConfig record, Integer pageIndex, Integer pageSize) {
        PageInfo<WxLevelConfig> page = PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxLevelConfigMapper.findList(record));

        for (int i=0;i<page.getList().size();i++)
        {
            WxLevelConfig l = page.getList().get(i);
            if (l.getCapability()!= null){
                JSONObject jo = JSONObject.parseObject(l.getCapability());
                l.setCount(jo.getLong(CAPABILITY_SEND_CAR_COUPON));
            }else {
                l.setCount(0L);
            }

            if(l.getScale()==null) {
                l.setScale(WxLevelConfig.DEFAULT_SCALE);
            }
            WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
            dto.setTenantId(l.getTenantId());
            dto.setLevelStartScore(l.getPoints());
            if (i + 1<page.getList().size())
                dto.setLevelEndScore(page.getList().get(i+1).getPoints());

            l.setUserCount(wxCUserBasicInfoMapper.findCountByScore(dto));

        }
        return page;
    }


    @Override
    public List<WxLevelConfig> listByMerchantId(Long merchantId, WxLevelConfig record) {
        List<WxLevelConfig> list = wxLevelConfigMapper.findList(record);
        list.stream().forEach(l->{
            WxLevelMerchant wxLevelMerchantParam = new WxLevelMerchant();
            wxLevelMerchantParam.setLevelId(l.getId());
            wxLevelMerchantParam.setMerchantId(merchantId);
            WxLevelMerchant wxLevelMerchant = wxLevelMerchantapper.selectOne(new QueryWrapper(wxLevelMerchantParam));
            l.setCount(wxLevelMerchant != null? wxLevelMerchant.getDiscount().longValue():DEFAULT_MERCHANT_DISCOUNT);
        });
        return list;
    }

    @Override
    public void batchSaveByMerchantId(String tenantId, Long merchantId, List<WxLevelConfig> records) {
        final IdWorker idWorker = IdWorker.get();

        records.stream().forEach(l->{
            WxLevelMerchant wxLevelMerchantParam = new WxLevelMerchant();
            wxLevelMerchantParam.setLevelId(l.getId());
            wxLevelMerchantParam.setMerchantId(merchantId);
            WxLevelMerchant wxLevelMerchant = wxLevelMerchantapper.selectOne(new QueryWrapper(wxLevelMerchantParam));
            if (wxLevelMerchant != null) {
                wxLevelMerchant.setCreateDate(new Date());
                wxLevelMerchant.setDiscount(l.getCount().intValue());
                wxLevelMerchantapper.updateById(wxLevelMerchant);
            }else {
                wxLevelMerchantParam.setId(idWorker.nextId());
                wxLevelMerchantParam.setCreateDate(new Date());
                wxLevelMerchantParam.setTenantId(tenantId);
                wxLevelMerchantParam.setDiscount(l.getCount().intValue());
                wxLevelMerchantapper.insert(wxLevelMerchantParam);
            }
        });

    }


    @Override
    public List<WxLevelConfig> findList(WxLevelConfig record){
        return wxLevelConfigMapper.findList(record);
    }

    @Override
    public List<WxLevelConfig> getByTenantId(String tenantId) {
        WxLevelConfig wxLevelConfig = new WxLevelConfig();
        wxLevelConfig.setTenantId(tenantId);
        wxLevelConfig.setSortColumns(BaseEntity.SortField.Points_ASC);
        return wxLevelConfigMapper.findList(wxLevelConfig);
    }

    @Override
    public WxLevelConfig getById(Long id) {
        return wxLevelConfigMapper.selectById(id);
    }

    @Override
    public void saveOrUpdate(WxLevelConfig record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
            wxLevelConfigMapper.insert(record);
        } else {
            wxLevelConfigMapper.updateById(record);
        }
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void batchSave(String tenantId, List<WxLevelConfig> records) {
        final IdWorker idWorker = IdWorker.get();
        wxLevelConfigMapper.deleteAll(tenantId);
        List<WxLevelConfig> levelConfigs = new ArrayList<>();
        for(WxLevelConfig levelConfig: records) {
            if(levelConfig.getId() == null) {
                levelConfig.setId(idWorker.nextId());
                levelConfig.setCreateDate(new Date());
                levelConfig.setUpdateDate(new Date());
            } else {
                levelConfig.setUpdateDate(new Date());
            }
            levelConfig.setTenantId(tenantId);
            levelConfigs.add(levelConfig);
        }
        wxLevelConfigMapper.insertBatch(levelConfigs);
    }

    @Override
    public void batchUpdateCapabilities(String tenantId, List<WxLevelConfig> records) {
        List<WxLevelConfig> levelConfigs = new ArrayList<WxLevelConfig>();
        for(WxLevelConfig levelConfig: records) {
            if(levelConfig.getId() != null && levelConfig.getCount() != null) {
                levelConfig.setTenantId(tenantId);
                levelConfig.setUpdateDate(new Date());
                JSONObject jo = new JSONObject();
                jo.put(CAPABILITY_SEND_CAR_COUPON,levelConfig.getCount());
                levelConfig.setCapability(jo.toJSONString());
                levelConfigs.add(levelConfig);
            }
        }
        wxLevelConfigMapper.batchUpdate(levelConfigs);
    }

    @Override
    public Long getCapabilitiesOfSendCarConpon(JSONObject jo) {
        return jo.getLong(CAPABILITY_SEND_CAR_COUPON);
    }

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

	@Override
	public void deleteAll(String tenantId) {
		wxLevelConfigMapper.deleteAll(tenantId);
		
	}

    @Override
    public String getLevel(String tenantId, int score) {
        return wxLevelConfigMapper.getLevel(tenantId,score);
    }

    @Override
    public List<WxLevelMerchantCVo> findListCVo(WxLevelMerchant record) {
        return wxLevelMerchantapper.findListCVo(record);
    }

}
