package com.liquidnet.service.sweet.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.dto.vo.returns.KylinOrderRefundsVo;
import com.liquidnet.service.sweet.entity.SweetPerformanceShow;
import com.liquidnet.service.sweet.mapper.SweetPerformanceMapper;
import com.liquidnet.service.sweet.param.SweetPerformanceShowParam;
import com.liquidnet.service.sweet.vo.SweetPerformanceShowVo;
import com.liquidnet.service.sweet.service.ISweetPerformanceService;
import com.liquidnet.service.sweet.utils.RedisDataUtils;
import com.mongodb.BasicDBObject;
import org.bson.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

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 SweetPerformanceServiceImpl extends ServiceImpl<SweetPerformanceMapper, SweetPerformanceShow> implements ISweetPerformanceService {

    @Value("${liquidnet.service.goblin.url}")
    private String goblinUrl;
    @Autowired
    private SweetPerformanceMapper sweetPerformanceMapper;
    @Autowired
    private RedisDataUtils redisUtils;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoConverter mongoConverter;
    @Autowired
    Environment environment;

    @Override
    public ResponseDto<Boolean> add(String performanceId, String performanceName, String arName, String picOne, String picTwo, String arUrl, String timeStart, String timeEnd, String fileSize) {
        try {
            int count = sweetPerformanceMapper.selectCount(Wrappers.lambdaUpdate(SweetPerformanceShow.class).eq(SweetPerformanceShow::getPerformanceId, performanceId));
            if (count > 0) {
                return ResponseDto.failure("该演出已关联活动");
            }
            String offlineUrl = goblinUrl + "/goblin/inner/ar/data"; //离线地址
            SweetPerformanceShow show = SweetPerformanceShow.getNew();
            show.setArId(IDGenerator.nextTimeId2());
            show.setPerformanceId(performanceId);
            show.setPerformanceName(performanceName);
            show.setPicOne(picOne);
            show.setPicTwo(picTwo);
            show.setArUrl(arUrl);
            show.setArName(arName);
            show.setStatus(0);
            show.setOfflineUrl(offlineUrl);
            show.setFileSize(fileSize);
            show.setTimeStart(LocalDateTime.parse(timeStart, DTF_YMD_HMS));
            show.setTimeEnd(LocalDateTime.parse(timeEnd, DTF_YMD_HMS));
            //redis
            List<SweetPerformanceShow> performanceARList = redisUtils.getPerformanceAR();
            performanceARList.add(show);
            redisUtils.setPerformanceAR(performanceARList);
            //新增 mongo数据
            mongoTemplate.insert(show, SweetPerformanceShow.class.getSimpleName());
            //mysql
            sweetPerformanceMapper.insert(show);
            return ResponseDto.success();
        } catch (Exception e) {
            return ResponseDto.failure();
        }
    }

    @Override
    public ResponseDto<Boolean> change(SweetPerformanceShowParam show) {
        try {
            int count = sweetPerformanceMapper.selectCount(Wrappers.lambdaUpdate(SweetPerformanceShow.class).eq(SweetPerformanceShow::getPerformanceId, show.getPerformanceId()).ne(SweetPerformanceShow::getArId, show.getArId()));
            if (count > 0) {
                return ResponseDto.failure("该演出已关联活动");
            }

            String id = show.getArId();
            //修改redis
            List<SweetPerformanceShow> performanceARList = redisUtils.getPerformanceAR();
            SweetPerformanceShow data = SweetPerformanceShow.getNew();
            for (int i = 0; i < performanceARList.size(); i++) {
                if (performanceARList.get(i).getArId().equals(id)) {
                    //覆盖要修改的原数据
                    BeanUtils.copyProperties(show, data);
                    data.setTimeStart(LocalDateTime.parse(show.getTimeStart(), DTF_YMD_HMS));
                    data.setTimeEnd(LocalDateTime.parse(show.getTimeEnd(), DTF_YMD_HMS));
                    data.setStatus(performanceARList.get(i).getStatus());
                    data.setOfflineUrl(performanceARList.get(i).getOfflineUrl());
                    data.setFileSize(show.getFileSize());
                    performanceARList.set(i, data);
                    redisUtils.setPerformanceAR(performanceARList);
                    break;
                }
            }
            if (data.getArId() == null || data.getArId().equals("")) {
                return ResponseDto.failure();
            }
            //修改 mongo数据
            Query query = Query.query(Criteria.where("arId").is(id));
            Update update = Update.fromDocument(Document.parse(JsonUtils.toJson(data)));
            mongoTemplate.updateFirst(query, update, SweetPerformanceShow.class, SweetPerformanceShow.class.getSimpleName());
            //修改mysql
            sweetPerformanceMapper.update(data, Wrappers.lambdaUpdate(SweetPerformanceShow.class).eq(SweetPerformanceShow::getArId, id));
            return ResponseDto.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDto.failure();
        }
    }

    @Override
    public ResponseDto<Boolean> del(String arId) {
        //删除
        List<SweetPerformanceShow> performanceARList = redisUtils.getPerformanceAR();
        for (SweetPerformanceShow performanceShow : performanceARList) {
            if (performanceShow.getArId().equals(arId)) {
                //删除要修改的原数据
                performanceARList.remove(performanceShow);
                redisUtils.setPerformanceAR(performanceARList);
                break;
            }
        }
        mongoTemplate.remove(Query.query(Criteria.where("arId").is(arId)), SweetPerformanceShow.class.getSimpleName());
        sweetPerformanceMapper.delete(Wrappers.lambdaQuery(SweetPerformanceShow.class).eq(SweetPerformanceShow::getArId, arId));
        return ResponseDto.success();
    }

    //ar列表
    @Override
    public ResponseDto<PageInfo<SweetPerformanceShowVo>> getList(Integer page, Integer size, String performanceName) {
        PageInfo<SweetPerformanceShowVo> pageInfo = null;
        try {
            List<SweetPerformanceShow> data;
            PageHelper.startPage(page, size);
            List<SweetPerformanceShowVo> listData = new ArrayList();
            if (performanceName != null) {
                data = sweetPerformanceMapper.selectList(Wrappers.lambdaQuery(SweetPerformanceShow.class).like(SweetPerformanceShow::getPerformanceName, performanceName));
            } else {
                data = sweetPerformanceMapper.selectList(Wrappers.lambdaQuery(SweetPerformanceShow.class));
            }
            for (SweetPerformanceShow entity : data) {
                SweetPerformanceShowVo rdata = SweetPerformanceShowVo.getNew();
                BeanUtils.copyProperties(entity, rdata);
                rdata.setTimeStart(DateUtil.Formatter.yyyyMMddHHmmss.format(entity.getTimeStart()));
                rdata.setTimeEnd(DateUtil.Formatter.yyyyMMddHHmmss.format(entity.getTimeEnd()));
                listData.add(rdata);
            }
            pageInfo = new PageInfo(listData);
            return ResponseDto.success(pageInfo);
        } catch (Exception e) {
            return ResponseDto.success(pageInfo);
        }
    }

    @Override
    public ResponseDto<SweetPerformanceShowVo> details(String arId) {
        SweetPerformanceShow entity = sweetPerformanceMapper.selectOne(Wrappers.lambdaQuery(SweetPerformanceShow.class).eq(SweetPerformanceShow::getArId, arId));
        SweetPerformanceShowVo rdata = SweetPerformanceShowVo.getNew();
        BeanUtils.copyProperties(entity, rdata);
        rdata.setTimeStart(DateUtil.Formatter.yyyyMMddHHmmss.format(entity.getTimeStart()));
        rdata.setTimeEnd(DateUtil.Formatter.yyyyMMddHHmmss.format(entity.getTimeEnd()));
        return ResponseDto.success(rdata);
    }

    @Override
    public ResponseDto<Boolean> changeStatus(String arId, Integer status) {
        List<SweetPerformanceShow> performanceARList = redisUtils.getPerformanceAR();
        SweetPerformanceShow data = null;
        for (int i = 0; i < performanceARList.size(); i++) {
            SweetPerformanceShow performanceShow = performanceARList.get(i);
            if (performanceShow.getArId().equals(arId)) {
                //覆盖要修改的原数据\
                performanceShow.setStatus(status);
                performanceARList.set(i, performanceShow);
                redisUtils.setPerformanceAR(performanceARList);
                data = performanceShow;
                break;
            }
        }
        //修改 mongo数据
        BasicDBObject cv = new BasicDBObject("$set", mongoConverter.convertToMongoType(data));
        mongoTemplate.getCollection(KylinOrderRefundsVo.class.getSimpleName()).updateMany(
                Query.query(Criteria.where("arId").is("arId")).getQueryObject(),
                cv
        );

        //修改mysql
        sweetPerformanceMapper.update(data, Wrappers.lambdaUpdate(SweetPerformanceShow.class).eq(SweetPerformanceShow::getArId, arId));
        return ResponseDto.success();
    }

}
