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

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.zhengzai.goblin.service.IGoblinZhengzaiMarketService;
import com.liquidnet.client.admin.zhengzai.goblin.utils.GoblinMongoUtils;
import com.liquidnet.client.admin.zhengzai.goblin.utils.GoblinRedisUtils;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.constant.GoblinStatusConst;
import com.liquidnet.service.goblin.dto.GoblinSelfMarketingDto;
import com.liquidnet.service.goblin.dto.GoblinZhengzaiStoreDetailsDto;
import com.liquidnet.service.goblin.dto.GoblinZhengzaiStoreListDto;
import com.liquidnet.service.goblin.dto.manage.GoblinInsertZhengzaiParam;
import com.liquidnet.service.goblin.dto.vo.*;
/*import com.liquidnet.service.goblin.dto.vo.GoblinZhengzaiVo;*/
import com.liquidnet.service.goblin.entity.GoblinMarketingZhengzaiRelation;
import com.liquidnet.service.goblin.entity.GoblinSelfMarketing;
import com.liquidnet.service.goblin.mapper.GoblinMarketingZhengzaiRelationMapper;
import com.liquidnet.service.goblin.mapper.GoblinSelfMarketingMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.liquidnet.commons.lang.util.DateUtil.DTF_YMD_HMS;

/**
 * 正在下单相关
 */
@Service
public class GoblinZhengzaiMarketServiceImpl implements IGoblinZhengzaiMarketService {

    @Value("${liquidnet.service.goblin.url}")
    String goblinUrl;
    @Autowired
    GoblinRedisUtils goblinRedisUtils;
    @Autowired
    GoblinMongoUtils goblinMongoUtils;
    @Autowired
    GoblinSelfMarketingMapper goblinSelfMarketingMapper;
    @Autowired
    GoblinMarketingZhengzaiRelationMapper goblinMarketingZhengzaiRelationMapper;

    @Override
    public ResponseDto<List<GoblinSelfMarketingDto>> zhengzaiList(int page, int size, String purchaseName, int status, String st, String et, String ct) {
//        LambdaUpdateWrapper<GoblinSelfMarketing> queryMapper = Wrappers.lambdaUpdate(GoblinSelfMarketing.getNew()).eq(GoblinSelfMarketing::getDelFlag, 0);
//        switch (status) {
//            case 0://未开始
//                queryMapper = queryMapper.gt(GoblinSelfMarketing::getStartTime, LocalDateTime.now()).ne(GoblinSelfMarketing::getStatus, GoblinStatusConst.MarketingStatus.STORE_PURCHASE_STATUS_STOP.getValue());
//                break;
//            case 1://进行中
//                queryMapper = queryMapper.le(GoblinSelfMarketing::getStartTime, LocalDateTime.now()).ge(GoblinSelfMarketing::getEndTime, LocalDateTime.now()).ne(GoblinSelfMarketing::getStatus, GoblinStatusConst.MarketingStatus.STORE_PURCHASE_STATUS_STOP.getValue());
//                break;
//            case 2://已结束
//                queryMapper = queryMapper.lt(GoblinSelfMarketing::getEndTime, LocalDateTime.now()).ne(GoblinSelfMarketing::getStatus, GoblinStatusConst.MarketingStatus.STORE_PURCHASE_STATUS_STOP.getValue());
//                break;
//            case 7://停用
//                queryMapper = queryMapper.eq(GoblinSelfMarketing::getStatus, GoblinStatusConst.MarketingStatus.STORE_PURCHASE_STATUS_STOP.getValue());
//                break;
//        }
//
//        if (!purchaseName.equals("")) {
//            queryMapper = queryMapper.like(GoblinSelfMarketing::getName, purchaseName);
//        }
//        if ((st != null && !st.equals("")) && (et != null && !et.equals(""))) {
//            queryMapper = queryMapper.ge(GoblinSelfMarketing::getStartTime, st).le(GoblinSelfMarketing::getEndTime, et);
//        }
//        if (ct != null && !ct.equals("")) {
//            queryMapper = queryMapper.eq(GoblinSelfMarketing::getCreatedAt, ct);
//        }
        List<GoblinSelfMarketingDto> marketing = goblinSelfMarketingMapper.getZhengzaiList(purchaseName, status, st, et, ct);
        return ResponseDto.success(marketing);
    }

    @Override
    public ResponseDto<Boolean> zhengzaiStatus(String marketId, int status) {
        GoblinSelfMarketing selfMarketing = GoblinSelfMarketing.getNew();
        String[] marketIdArray = marketId.split(",");
        for (String item : marketIdArray) {
            if (status == -1) {
                selfMarketing.setStatus(0);
                selfMarketing.setDelFlag(1);
                selfMarketing.setUpdatedAt(LocalDateTime.now());
                //mysql
                goblinSelfMarketingMapper.update(selfMarketing, Wrappers.lambdaUpdate(GoblinSelfMarketing.getNew()).eq(GoblinSelfMarketing::getSelfMarketId, item));
                //mongo
                goblinMongoUtils.delSelfMarket(item);
                //redis
                goblinRedisUtils.delSelfMarket(item);
                goblinRedisUtils.delZhengzaiList(item);
            } else {
                selfMarketing.setStatus(status);
                selfMarketing.setUpdatedAt(LocalDateTime.now());
                //mysql
                goblinSelfMarketingMapper.update(selfMarketing, Wrappers.lambdaUpdate(GoblinSelfMarketing.getNew()).eq(GoblinSelfMarketing::getSelfMarketId, item));
                //mongo
                GoblinSelfMarketingVo vo = GoblinSelfMarketingVo.getNew();
                BeanUtils.copyProperties(selfMarketing, vo);
                vo.setStatus(status);
                GoblinSelfMarketingVo changeVo = goblinMongoUtils.updateSelfMarket(item, vo);
                //redis
                goblinRedisUtils.setSelfMarket(item, changeVo);
                goblinRedisUtils.changeZhengzaiList(changeVo);
            }
        }
        return ResponseDto.success();
    }

    @Override
    public ResponseDto<String> zhengzaiInsert(String purchaseName, String performanceId, String img, String st, String et) {
        GoblinSelfMarketing selfMarketing = GoblinSelfMarketing.getNew();
        String SelfMarketId = IDGenerator.nextTimeId2();
        selfMarketing.setSelfMarketId(SelfMarketId);
        selfMarketing.setName(purchaseName);
        selfMarketing.setPerformanceId(performanceId);
        selfMarketing.setType(GoblinStatusConst.MarketingStatus.SELF_TYPE_ZHENGZAI.getValue());
        selfMarketing.setStartTime(LocalDateTime.parse(st, DTF_YMD_HMS));
        selfMarketing.setEndTime(LocalDateTime.parse(et, DTF_YMD_HMS));
        selfMarketing.setCreatedAt(LocalDateTime.now());
        //mysql
        goblinSelfMarketingMapper.insert(selfMarketing);
        //mongo
        GoblinSelfMarketingVo vo = GoblinSelfMarketingVo.getNew();
        BeanUtils.copyProperties(selfMarketing, vo);
        vo.setStartTime(st);
        vo.setEndTime(et);
        vo.setPerformanceId(performanceId);
        vo.setPerformanceImg(img);
        vo.setCreatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(selfMarketing.getCreatedAt()));
        goblinMongoUtils.insertSelfMarket(vo);
        //redis
        goblinRedisUtils.setSelfMarket(SelfMarketId, vo);
        goblinRedisUtils.addZhengzaiList(vo);
        return ResponseDto.success(SelfMarketId);
    }

    @Override
    public ResponseDto<Boolean> zhengzaiUpdate(String marketId, String purchaseName, String performanceId, String img, String st, String et) {
        GoblinSelfMarketing selfMarketing = GoblinSelfMarketing.getNew();
        selfMarketing.setSelfMarketId(marketId);
        selfMarketing.setName(purchaseName);
        selfMarketing.setType(GoblinStatusConst.MarketingStatus.SELF_TYPE_ZHENGZAI.getValue());
        selfMarketing.setStartTime(LocalDateTime.parse(st, DTF_YMD_HMS));
        selfMarketing.setEndTime(LocalDateTime.parse(et, DTF_YMD_HMS));
        selfMarketing.setUpdatedAt(LocalDateTime.now());
        //mysql
        goblinSelfMarketingMapper.update(selfMarketing, Wrappers.lambdaUpdate(GoblinSelfMarketing.getNew()).eq(GoblinSelfMarketing::getSelfMarketId, marketId));
        //mongo
        GoblinSelfMarketingVo vo = GoblinSelfMarketingVo.getNew();
        BeanUtils.copyProperties(selfMarketing, vo);
        vo.setName(purchaseName);
        vo.setStartTime(st);
        vo.setEndTime(et);
        vo.setPerformanceImg(img);
        vo.setPerformanceId(performanceId);
        GoblinSelfMarketingVo changeVo = goblinMongoUtils.updateSelfMarket(marketId, vo);
        //redis
        goblinRedisUtils.setSelfMarket(marketId, changeVo);
        goblinRedisUtils.changeZhengzaiList(changeVo);
        return ResponseDto.success();
    }

    @Override
    public ResponseDto<GoblinSelfMarketingVo> zhengzaiDetails(String marketId) {
        GoblinSelfMarketing bean = goblinSelfMarketingMapper.selectOne(Wrappers.lambdaUpdate(GoblinSelfMarketing.getNew()).eq(GoblinSelfMarketing::getSelfMarketId, marketId));
        GoblinSelfMarketingVo vo = GoblinSelfMarketingVo.getNew();
        BeanUtils.copyProperties(bean, vo);
        vo.setStartTime(DateUtil.Formatter.yyyyMMddHHmmss.format(bean.getStartTime()));
        vo.setEndTime(DateUtil.Formatter.yyyyMMddHHmmss.format(bean.getEndTime()));
        vo.setCreatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(bean.getCreatedAt()));
        return ResponseDto.success(vo);
    }

    @Override
    public ResponseDto<List<GoblinZhengzaiStoreListVo>> zhengzaiStoreList(String marketId) {
        List<GoblinZhengzaiStoreListDto> dtoList = goblinSelfMarketingMapper.getZhengzaiStoreList(marketId);
        List<GoblinZhengzaiStoreListVo> voList = new ArrayList<>();
        for (GoblinZhengzaiStoreListDto item : dtoList) {
            GoblinZhengzaiStoreListVo vo = GoblinZhengzaiStoreListVo.getNew();
            vo.setStoreId(item.getStoreId());
            vo.setStoreName(item.getStoreName());
            vo.setShowTime(item.getShowTime());
            vo.setSpuCount(item.getSpuCount());
            vo.setSkuCount(item.getSkuCount());
            voList.add(vo);
        }
        return ResponseDto.success(voList);
    }

    @Override
    public ResponseDto<Boolean> zhengzaiStore(List<GoblinInsertZhengzaiParam> params) {
        for (GoblinInsertZhengzaiParam item : params) {
            if (item.getNewTag() == 1) {//新增
                String marketId = item.getMarketId();
                String storeId = item.getStoreId();
                String showTime = item.getShowTime();
                GoblinMarketingZhengzaiRelation entity = GoblinMarketingZhengzaiRelation.getNew();
                entity.setSelfMarketId(marketId);
                entity.setStoreId(storeId);
                entity.setShowTime(LocalDateTime.parse(showTime, DTF_YMD_HMS));
                if (goblinRedisUtils.getZhengzaiRelation(storeId).contains(marketId)) {
                    return ResponseDto.failure("禁止重复添加");
                }
                //mysql
                goblinMarketingZhengzaiRelationMapper.insert(entity);
                //mongo
                GoblinMarketingZhengzaiRelationVo vo = GoblinMarketingZhengzaiRelationVo.getNew();
                BeanUtils.copyProperties(entity, vo);
                vo.setShowTime(showTime);
                vo.setCreatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(entity.getCreatedAt()));
                goblinMongoUtils.insertZhengzaiRelation(vo);
                //redis
                goblinRedisUtils.setZhengzaiRelation(marketId, vo);
                goblinRedisUtils.addStoreSelfRelation(marketId, storeId);
            } else {//修改
                int delTag = item.getDelTag();
                String showTime = item.getShowTime();
                String marketId = item.getMarketId();
                String storeId = item.getStoreId();
                if (delTag == 0) {
                    GoblinMarketingZhengzaiRelation entity = GoblinMarketingZhengzaiRelation.getNew();
                    entity.setShowTime(LocalDateTime.parse(showTime, DTF_YMD_HMS));
                    entity.setUpdatedAt(LocalDateTime.now());
                    entity.setStoreId(storeId);
                    entity.setSelfMarketId(marketId);
                    //mysql
                    goblinMarketingZhengzaiRelationMapper.update(entity, Wrappers.lambdaUpdate(GoblinMarketingZhengzaiRelation.getNew()).eq(GoblinMarketingZhengzaiRelation::getSelfMarketId, marketId).eq(GoblinMarketingZhengzaiRelation::getStoreId, storeId));
                    //mongo
                    GoblinMarketingZhengzaiRelationVo vo = GoblinMarketingZhengzaiRelationVo.getNew();
                    BeanUtils.copyProperties(entity, vo);
                    vo.setShowTime(showTime);
                    goblinMongoUtils.updateZhengzaiRelation(marketId, storeId, vo);
                    //redis
                    goblinRedisUtils.setZhengzaiRelation(marketId, vo);
//                    goblinRedisUtils.addStoreSelfRelation(marketId, storeId);
                } else if (delTag == 1) {
                    GoblinMarketingZhengzaiRelation entity = GoblinMarketingZhengzaiRelation.getNew();
                    entity.setDelTag(1);
                    entity.setUpdatedAt(LocalDateTime.now());
                    entity.setStoreId(storeId);
                    entity.setSelfMarketId(marketId);
                    //mysql
                    goblinMarketingZhengzaiRelationMapper.update(entity, Wrappers.lambdaUpdate(GoblinMarketingZhengzaiRelation.getNew()).eq(GoblinMarketingZhengzaiRelation::getSelfMarketId, marketId).eq(GoblinMarketingZhengzaiRelation::getStoreId, storeId));
                    //mongo
                    goblinMongoUtils.delZhengzaiRelation(marketId, storeId);
                    //redis
                    goblinRedisUtils.delZhengzaiRelation(marketId, storeId);
                    goblinRedisUtils.delStoreSelfRelation(marketId, storeId);
                }
            }

        }
        return ResponseDto.success();
    }

    @Override
    public ResponseDto<Boolean> zhengzaiStoreUpdate(List<GoblinInsertZhengzaiParam> params) {
        for (GoblinInsertZhengzaiParam item : params) {
            int delTag = item.getDelTag();
            String showTime = item.getShowTime();
            String marketId = item.getMarketId();
            String storeId = item.getStoreId();
            if (delTag == 0) {
                GoblinMarketingZhengzaiRelation entity = GoblinMarketingZhengzaiRelation.getNew();
                entity.setShowTime(LocalDateTime.parse(showTime, DTF_YMD_HMS));
                entity.setUpdatedAt(LocalDateTime.now());
                //mysql
                goblinMarketingZhengzaiRelationMapper.update(entity, Wrappers.lambdaUpdate(GoblinMarketingZhengzaiRelation.getNew()).eq(GoblinMarketingZhengzaiRelation::getSelfMarketId, marketId).eq(GoblinMarketingZhengzaiRelation::getStoreId, storeId));
                //mongo
                GoblinMarketingZhengzaiRelationVo vo = GoblinMarketingZhengzaiRelationVo.getNew();
                BeanUtils.copyProperties(entity, vo);
                vo.setShowTime(showTime);
                goblinMongoUtils.updateZhengzaiRelation(marketId, storeId, vo);
                //redis
                goblinRedisUtils.setZhengzaiRelation(marketId, vo);
//                goblinRedisUtils.addStoreSelfRelation(marketId, storeId);
            } else if (delTag == 1) {
                GoblinMarketingZhengzaiRelation entity = GoblinMarketingZhengzaiRelation.getNew();
                entity.setDelTag(1);
                entity.setUpdatedAt(LocalDateTime.now());
                //mysql
                goblinMarketingZhengzaiRelationMapper.update(entity, Wrappers.lambdaUpdate(GoblinMarketingZhengzaiRelation.getNew()).eq(GoblinMarketingZhengzaiRelation::getSelfMarketId, marketId).eq(GoblinMarketingZhengzaiRelation::getStoreId, storeId));
                //mongo
                goblinMongoUtils.delZhengzaiRelation(marketId, storeId);
                //redis
                goblinRedisUtils.delZhengzaiRelation(marketId, storeId);
                goblinRedisUtils.delStoreSelfRelation(marketId, storeId);
            }
        }
        return ResponseDto.success();
    }

    @Override
    public List<GoblinMarketSpuListVo> zhengzaiSpuList(String marketId, String storeId, int page) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap();
        params.add("selfMarketId", marketId);
        params.add("storeId", storeId);
        params.add("page", page + "");
        MultiValueMap<String, String> headers = CollectionUtil.linkedMultiValueMapStringString();
        headers.add("Accept", "application/json;charset=UTF-8");
        String returnData = HttpUtil.get(goblinUrl + "/goblin/inner/config/spu?page=" + page + "&selfMarketId=" + marketId + "&storeId=" + storeId, params, headers);
        ResponseDto<PageInfo<GoblinMarketSpuListVo>> rsp = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<PageInfo<GoblinMarketSpuListVo>>>() {
        });
        return rsp.getData().getList();
    }

    @Override
    public List<GoblinSelfZhengzaiSkuVo> zhengzaiSkuList(String marketId, String storeId, String spuId) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap();
        params.add("selfMarketId", marketId);
        params.add("storeId", storeId);
        params.add("spuId", spuId);
        MultiValueMap<String, String> headers = CollectionUtil.linkedMultiValueMapStringString();
        headers.add("Accept", "application/json;charset=UTF-8");
        String returnData = HttpUtil.get(goblinUrl + "/goblin/inner/config/sku?selfMarketId=" + marketId + "&storeId=" + storeId + "&spuId=" + spuId, params, headers);
        ResponseDto<List<GoblinSelfZhengzaiSkuVo>> rsp = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<List<GoblinSelfZhengzaiSkuVo>>>() {
        });
        return rsp.getData();
    }

    @Override
    public ResponseDto<Boolean> zhengzaiSkuDel(String marketId, String storeId, String spuId) {
        //调用goblin商铺配置商铺接口
        MultiValueMap<String, String> params = new LinkedMultiValueMap();
        params.add("selfMarketId", marketId);
        params.add("storeId", storeId);
        params.add("spuId", spuId);
        MultiValueMap<String, String> headers = CollectionUtil.linkedMultiValueMapStringString();
        headers.add("Accept", "application/json;charset=UTF-8");
        String returnData = HttpUtil.post(goblinUrl + "/goblin/inner/config/del/noAuth", params, headers);
        ResponseDto<Boolean> rsp = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<Boolean>>() {
        });
        return rsp;
    }
}
