package com.liquidnet.client.admin.zhengzai.stone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.common.utils.DateUtils;
import com.liquidnet.client.admin.zhengzai.stone.service.IItemService;
import com.liquidnet.client.admin.zhengzai.stone.service.utils.StoneMongoUtils;
import com.liquidnet.client.admin.zhengzai.stone.service.utils.StoneRedisUtils;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.stone.entity.StoneScoreItems;
import com.liquidnet.service.stone.mapper.StoneScoreItemsMapper;
import com.liquidnet.service.stone.param.StoneItemBuildParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class ItemServiceImpl implements IItemService {

    @Autowired
    StoneScoreItemsMapper stoneScoreItemsMapper;
    @Autowired
    StoneRedisUtils redisUtils;
    @Autowired
    StoneMongoUtils mongoUtils;

    @Override
    /**
     * 积分商品列表
     *
     * @param title  名称
     * @param status 状态[-999-全部|1-上架中|2-待上架|7-已下架]
     * @param type   类型[1-券]
     * @return
     */
    public PageInfo<StoneScoreItems> itemList(String title, Integer status, Integer type) {
        PageInfo<StoneScoreItems> pageInfo;
        LocalDateTime now = LocalDateTime.now();
        List<StoneScoreItems> newList = new ArrayList();
        LambdaQueryWrapper<StoneScoreItems> queryWrapper = Wrappers.lambdaQuery(StoneScoreItems.class).ne(StoneScoreItems::getStatus, -1);
        if (!(title == null || title.equals(""))) {
            queryWrapper.like(StoneScoreItems::getTargetTitle, title);
        }
        if (status != null) {
            if (status != -999) {
                if (status == 2) {//待上架
                    queryWrapper.eq(StoneScoreItems::getStatus, 2).gt(StoneScoreItems::getStartTime, now);
                } else if (status == 7) {//已下架
                    queryWrapper.eq(StoneScoreItems::getStatus, 7).or().eq(StoneScoreItems::getStatus, 2).lt(StoneScoreItems::getEndTime, now);
                } else if (status == 1) {
                    queryWrapper.eq(StoneScoreItems::getStatus, 1).or().lt(StoneScoreItems::getStartTime, now).gt(StoneScoreItems::getEndTime, now);
                }
            }
        }
        if (type != null) {
            if (type != -1) {
                queryWrapper.eq(StoneScoreItems::getType, type);
            }
        }
        List<StoneScoreItems> voList = stoneScoreItemsMapper.selectList(queryWrapper);
        for (StoneScoreItems item : voList) {
            if (item.getStatus() == 2) {
                if (now.isAfter(item.getStartTime())) {//未上架
                    item.setStatus(2);
                } else if (now.isBefore(item.getEndTime())) {//已下架
                    item.setStatus(7);
                } else {
                    item.setStatus(1);//上架中
                }
            }
            newList.add(item);
        }
        pageInfo = new PageInfo(newList);
        return pageInfo;
    }

    @Override
    /**
     * 修改 积分物品 状态
     *
     * @param itemId ID
     * @param status 状态[-1-删除|1-上架|7-下架]
     * @return
     */
    public String changeStatus(String itemId, Integer status) {
        if (status != 1 && status != 7 && status != -1) {
            return "状态异常";
        }
        StoneScoreItems data = new StoneScoreItems();
        data.setStatus(status);
        //mysql
        int result = stoneScoreItemsMapper.update(data, Wrappers.lambdaQuery(StoneScoreItems.class).eq(StoneScoreItems::getItemId, itemId));
        StoneScoreItems redisData = redisUtils.getItemData(data.getItemId());
        redisData.setStatus(status);
        //mongo
        mongoUtils.itemUpdateById(redisData);
        //redis
        redisUtils.setItemData(data.getItemId(), redisData);
        //修改 List
        redisUtils.updateItemDataList(redisData);

        if (result <= 0) {
            return "修改失败";
        }
        return "修改成功";
    }

    @Override
    /**
     * 获取 积分物品 详情
     *
     * @param itemId ID
     * @return
     */
    public StoneScoreItems itemDetails(String itemId) {
        StoneScoreItems data = stoneScoreItemsMapper.selectOne(Wrappers.lambdaQuery(StoneScoreItems.class).eq(StoneScoreItems::getItemId, itemId));
        return data;
    }

    @Override
    public String createItem(StoneItemBuildParam param) {
        LocalDateTime now = LocalDateTime.now();
        if (param.getStatus() == 2 & (param.getStartTime() == null || param.getEndTime() == null)) {
            return "时间有误";
        }
        StoneScoreItems data = BaseData(param);
        int generalPoor = param.getGeneralTotal() - 0;
        data.setItemId(IDGenerator.nextTimeId2());
        data.setGeneralSurplus(redisUtils.changeStoneGeneralSurplus(data.getItemId(), generalPoor));
        data.setCreatedAt(now);
        //mysql
        int count = stoneScoreItemsMapper.insert(data);
        //mongo
        mongoUtils.itemCreate(data);
        //redis
        redisUtils.setItemData(data.getItemId(), data);
        //修改 List
        redisUtils.addItemDataList(data);
        if (count <= 0) {
            return "创建失败";
        }
        return "创建成功";
    }

    @Override
    public String updateItem(StoneItemBuildParam param) {
        LocalDateTime now = LocalDateTime.now();
        if (param.getStatus() == 2 & (param.getStartTime() == null || param.getEndTime() == null)) {
            return "时间有误";
        }
        StoneScoreItems data = BaseData(param);
        StoneScoreItems dataSingle = stoneScoreItemsMapper.selectOne(Wrappers.lambdaQuery(StoneScoreItems.class).eq(StoneScoreItems::getItemId, param.getItemId()));
        int generalPoor = param.getGeneralTotal() - dataSingle.getGeneralTotal();
        data.setItemId(param.getItemId());
        data.setGeneralSurplus(redisUtils.changeStoneGeneralSurplus(data.getItemId(), generalPoor));
        data.setUpdatedAt(now);
        //mysql
        int count = stoneScoreItemsMapper.update(data, Wrappers.lambdaQuery(StoneScoreItems.class).eq(StoneScoreItems::getItemId, param.getItemId()));
        //mongo
        mongoUtils.itemUpdateById(data);
        //redis
        redisUtils.setItemData(data.getItemId(), data);
        //修改 List
        redisUtils.updateItemDataList(data);
        if (count <= 0) {
            return "修改失败";
        }
        return "修改成功";
    }

    /**
     * 构建 基础 积分商品数据
     *
     * @param param
     * @return
     */
    private StoneScoreItems BaseData(StoneItemBuildParam param) {
        StoneScoreItems data = new StoneScoreItems();
        data.setTargetId(param.getTargetId());
        data.setTargetTitle(param.getTargetTitle());
        data.setType(1);
        data.setImg(param.getImg());
        data.setScore(param.getScore());
        data.setPrice(BigDecimal.ZERO);
        data.setGeneralTotal(param.getGeneralTotal());
        data.setLimitCount(param.getLimitCount());
        data.setDetails(param.getDetails());
        data.setNotice(param.getNotice());
        data.setStatus(param.getStatus());
        if(param.getStartTime()!=null) {
            data.setStartTime(LocalDateTime.parse(param.getStartTime(), DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD_HH_MM_SS)));
        }
        if(param.getEndTime()!=null) {
            data.setEndTime(LocalDateTime.parse(param.getEndTime(), DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD_HH_MM_SS)));
        }
        return data;
    }
}
