package com.fdkankan.scene.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fdkankan.common.constant.CommonStatus;
import com.fdkankan.common.constant.ConstantFilePath;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.PayStatus;
import com.fdkankan.common.constant.SceneStatus;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.constant.UploadFilePath;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.Result;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.common.util.DateExtUtil;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.platform.api.feign.PlatformGoodsClient;
import com.fdkankan.platform.api.feign.PlatformUserClient;
import com.fdkankan.scene.bean.CameraBean;
import com.fdkankan.scene.bean.UserIncrementBean;
import com.fdkankan.scene.callback.FdkkMiniReqErrorCallback;
import com.fdkankan.scene.callback.FdkkMiniReqSuccessCallback;
import com.fdkankan.scene.entity.ScenePlus;
import com.fdkankan.scene.httpclient.FdkankanMiniClient;
import com.fdkankan.scene.service.ISceneEditInfoExtService;
import com.fdkankan.scene.service.ISceneEditInfoService;
import com.fdkankan.scene.service.ISceneEditService;
import com.fdkankan.scene.service.IScenePlusService;
import com.fdkankan.scene.service.ISceneProService;
import com.fdkankan.scene.service.ISceneUploadService;
import com.fdkankan.scene.vo.BaseDataParamVO;
import com.fdkankan.scene.vo.BaseSceneParamVO;
import com.fdkankan.scene.vo.DeleteFileParamVO;
import com.fdkankan.scene.vo.LocalesParamVO;
import com.fdkankan.scene.vo.SceneAuthVO;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/3/11
 **/
@Service
@RefreshScope
public class SceneEditServiceImpl implements ISceneEditService {

    @Value("${oss.bucket:4dkankan}")
    private String bucket;
    @Value("${http.host.4dkankanMini}")
    private String fkankanMiniHost;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    PlatformGoodsClient platformGoodsClient;
    @Autowired
    PlatformUserClient platformUserClient;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    private UploadToOssUtil uploadToOssUtil;
    @Autowired
    private ISceneUploadService sceneUploadService;
    @Autowired
    private ISceneEditInfoService sceneEditInfoService;
    @Autowired
    private ISceneEditInfoExtService sceneEditInfoExtService;
    @Autowired
    private FdkankanMiniClient fdkankanMiniClient;
    @Value("${http.api.isLogin}")
    private String URL_ISLOGIN;

    @Override
    public SceneAuthVO getAuth(BaseSceneParamVO param, String token) throws Exception{

        ScenePlus scenePlus = scenePlusService.getOne(
            new LambdaQueryWrapper<ScenePlus>().eq(ScenePlus::getNum, param.getNum())
                .eq(ScenePlus::getPayStatus, PayStatus.PAY.code()));
//                .in(ScenePlus::getSceneStatus, SceneStatus.SUCCESS.code(), SceneStatus.NO_DISPLAY.code()));
        if(scenePlus == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
        }
        if(scenePlus.getSceneStatus() == SceneStatus.FAILD.code()
            || scenePlus.getSceneStatus() == SceneStatus.wait.code()){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5033);
        }
        //判断该场景是否属于增值权益
        boolean isVip = false;
        //获取该相机是否有权益
        boolean isExpired  = false;
//        ResultData<Camera> cameraResultData = platformGoodsClient.getCameraById(scenePlus.getCameraId());
//        if(!cameraResultData.getSuccess()){
//            throw new Exception(ServerCode.FEIGN_REQUEST_FAILD.message());
//        }
//        Camera camera = cameraResultData.getData();
//        if(camera != null){
//            ResultData<UserIncrement> incrementResultData = platformUserClient
//                .getUserIncrementByCameraId(camera.getId());
//            if(!incrementResultData.getSuccess()){
//                throw new Exception(ServerCode.FEIGN_REQUEST_FAILD.message());
//            }
//            UserIncrement userIncrement = incrementResultData.getData();
//            if(userIncrement != null){
//                if( userIncrement.getIsExpired().intValue() == 0){
//                    isVip = true;
//                }
//                if(userIncrement.getIsExpired().intValue() == 1){
//                    isExpired  = true;
//                }
//            }else{
//                Date date = DateUtil.parse("2021-09-09 00:00:00", DateExtUtil.dateStyle);
//
//                //非07批次的放开
//                String pc = camera.getSnCode().substring(0,2);
//                if(!pc.equals("07") ){
//                    if(camera.getCreateTime()!=null && date.after(camera.getCreateTime())){
//                        isVip = true;
//                        isExpired  = false;
//                    }
//                }
//            }
//        }
        // TODO: 2022/4/25 v3v4共存过渡期结束需要删除，恢复上面注释内容 ------------------------------------------start
        String url = fkankanMiniHost + URL_ISLOGIN + param.getNum();
        Result<Map<String, Object>> isLoginResult = fdkankanMiniClient
            .getIsLogin(url, token, new FdkkMiniReqSuccessCallback(),
                new FdkkMiniReqErrorCallback());
        Map<String, Object> data = isLoginResult.getData();
        isVip = (boolean)data.get("isIncrement");
        isExpired = (boolean)data.get("isExpired");
        Integer company = data.get("company") == null ? null : (int)data.get("company");
        // TODO: 2022/4/25 v3v4共存过渡期结束需要删除，恢复上面注释内容 ------------------------------------------end

        return SceneAuthVO.builder()
            .isExpired(isExpired).isVip(isVip)
            .company(company)
            .exclude(data.get("exclude"))
            .include(data.get("include"))
            .build();
    }

    @Override
    public ResultData locales(LocalesParamVO param) throws Exception {
        String key = "v4/www/locales/" + param.getFile();
        uploadToOssUtil.upload(JSON.toJSONBytes(param.getData()), key);
        return ResultData.ok();
    }

    @Override
    public ResultData saveTour(BaseDataParamVO param) throws IOException {
        String key = String.format(UploadFilePath.USER_EDIT_PATH, param.getNum()) + "tour.json";
        uploadToOssUtil.upload(param.getData().getBytes(StandardCharsets.UTF_8), key);

        sceneEditInfoExtService.updateToursByNum(
            param.getNum(), Integer.valueOf(CommonStatus.YES.code()));

        return ResultData.ok();
    }

    @Override
    public ResultData deleteTour(BaseSceneParamVO param) throws Exception {
        String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, param.getNum());
        String tourJsonPath = userEditPath + "tour.json";
        String tourJson = uploadToOssUtil.getObjectContent(bucket, tourJsonPath);
        JSONArray tours = JSON.parseArray(tourJson);
        if(CollUtil.isNotEmpty(tours)){
            List<String> fileNames = new ArrayList<>();
            for (Object o : tours) {
                JSONObject tour = (JSONObject)o;

                JSONObject enter = tour.getJSONObject("enter");
                if(Objects.nonNull(enter)){
                    String enterOver = enter.getString("cover");
                    if(StrUtil.isNotEmpty(enterOver)){
                        fileNames.add(enterOver);
                    }
                }

                JSONObject exit = tour.getJSONObject("exit");
                if(Objects.nonNull(exit)){
                    String exitOver = exit.getString("cover");
                    if(StrUtil.isNotEmpty(exitOver)){
                        fileNames.add(exitOver);
                    }
                }

                String music = tour.getString("music");
                if(StrUtil.isNotEmpty(music)){
                    fileNames.add( music);
                }
            }

            //批量删除资源文件
            if(CollUtil.isNotEmpty(fileNames)){
                sceneUploadService.delete(
                    DeleteFileParamVO.builder()
                        .num(param.getNum()).bizType("tour").fileNames(fileNames)
                        .build());
            }
        }
        //删除tour.json文件
        uploadToOssUtil.delete(tourJsonPath);

        sceneEditInfoExtService.updateToursByNum(
            param.getNum(), Integer.valueOf(CommonStatus.NO.code()));

        return ResultData.ok();
    }

}
