package com.iformall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.domain.po.WxMall;
import com.iformall.domain.po.WxMallBuilding;
import com.iformall.domain.po.WxMallFloor;
import com.iformall.mapper.WxMallBuildingMapper;
import com.iformall.mapper.WxMallFloorMapper;
import com.iformall.mapper.WxMallMapper;
import com.iformall.service.WxMallService;
import com.iformall.utils.Constant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.iformall.common.IdWorker;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class WxMallServiceImpl implements WxMallService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxMallMapper wxMallMapper;

    @Autowired
    WxMallBuildingMapper wxMallBuildingMapper;

    @Autowired
    WxMallFloorMapper wxMallFloorMapper;

    @Autowired
    @Qualifier("mallRedisTemplate")
    RedisTemplate<String, WxMall> mallRedisTemplate;

    @Override
    public PageInfo<WxMall> listAsPage(WxMall record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxMallMapper.findList(record));
    }

    @Override
    public WxMall getById(Long id) {
        String key = Constant.MALL_KEY_PREV + String.valueOf(id);
        ValueOperations<String, WxMall> operations = mallRedisTemplate.opsForValue();

        // 缓存
        boolean hasKey = mallRedisTemplate.hasKey(key);
        if(hasKey) {
            // 从缓存获取用户信息
            WxMall mall = operations.get(key);
            return mall;
        }
        WxMall mall = wxMallMapper.selectById(id);
        // 插入缓存
        logger.info("getById: " + mall.toString());
        operations.set(key, mall, 3600, TimeUnit.SECONDS);
        return mall;
    }

    @Override
    public int save(WxMall record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
			Long id = idWorker.nextId();
        	record.setId(id);
        }

        if(StringUtils.isBlank(record.getTenantId())) {
            record.setTenantId(String.valueOf(record.getId()));
        }

        int ret = wxMallMapper.insert(record);

        String key = Constant.MALL_KEY_PREV + String.valueOf(record.getId());
        // 缓存已存在，删除
        boolean hasKey = mallRedisTemplate.hasKey(key);
        if(hasKey) {
            mallRedisTemplate.delete(key);
            logger.info("更新mall，从缓存中删除mall token >> " + record.getId());
        }
        return ret;
    }

    @Override
    public int update(WxMall record) {
        int ret = wxMallMapper.updateById(record);

        String key = Constant.MALL_KEY_PREV + String.valueOf(record.getId());
        // 缓存已存在，删除
        boolean hasKey = mallRedisTemplate.hasKey(key);
        if(hasKey) {
            mallRedisTemplate.delete(key);
            logger.info("更新mall，从缓存中删除mall >> " + record.getId());
        }
        return ret;
    }

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

        String key = Constant.MALL_KEY_PREV + String.valueOf(id);
        // 缓存已存在，删除
        boolean hasKey = mallRedisTemplate.hasKey(key);
        if(hasKey) {
            mallRedisTemplate.delete(key);
            logger.info("更新mall，从缓存中删除mall >> " + id);
        }
    }

    @Override
    public WxMall getByTenantId(String id) {
        String key = Constant.MALL_KEY_PREV + String.valueOf(id);
        ValueOperations<String, WxMall> operations = mallRedisTemplate.opsForValue();

        // 缓存
        boolean hasKey = mallRedisTemplate.hasKey(key);
        if(hasKey) {
            // 从缓存获取用户信息
            WxMall mall = operations.get(key);
            return mall;
        }
        WxMall mall =  wxMallMapper.getByTenantId(id);
        logger.info("getByTenantId: " + mall.toString());
        // 插入缓存
        operations.set(key, mall, 3600, TimeUnit.SECONDS);
        return mall;
    }

    @Override
    public WxMall getByTenantIdExt(String id) {
        WxMall wxMall = wxMallMapper.getByTenantId(id);
        if(wxMall == null) {
            return null;
        }

        WxMallBuilding wxMallBuilding = new WxMallBuilding();
        wxMallBuilding.setTenantId(id);
        List<WxMallBuilding> buildings = wxMallBuildingMapper.findList(wxMallBuilding);
        List<WxMallBuilding> wxMallBuildings = buildings.stream().map(b -> {
            WxMallBuilding tempb = new WxMallBuilding();
            tempb.setId(b.getId());
            tempb.setName(b.getName());
            return tempb;
        }).collect(Collectors.toList());

        for(WxMallBuilding building:wxMallBuildings){
            WxMallFloor wxMallFloor = new WxMallFloor();
            wxMallFloor.setBuildingId(building.getId());
            List<WxMallFloor> wxMallFloors = wxMallFloorMapper.findList(wxMallFloor).stream().map(f -> {
                WxMallFloor tempf = new WxMallFloor();
                tempf.setId(f.getId());
                tempf.setFloorName(f.getFloorName());
                tempf.setTotalArea(f.getTotalArea());
                tempf.setOperatingArea(f.getOperatingArea());
                return tempf;
            }).collect(Collectors.toList());
            building.setFloors(wxMallFloors);

        }
        wxMall.setBuildings(wxMallBuildings);
        return wxMall;
    }


}
