package com.slodon.b2b2c.ueditor;

import com.alibaba.fastjson.JSONObject;
import com.gexin.fastjson.JSON;
import com.slodon.b2b2c.core.config.DomainUrlUtil;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.model.seller.SellerMediaModel;
import com.slodon.b2b2c.upload.ALiYunUpload;
import com.slodon.b2b2c.upload.MinioUpload;
import com.slodon.b2b2c.upload.QiNiuYunUpload;
import com.slodon.b2b2c.upload.TencentCloudUpload;
import com.slodon.b2b2c.upload.base.Upload;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

import static com.slodon.b2b2c.core.constant.UeditorConst.*;

/**
 * 根据不同的action，执行不同的操作
 */
@Component
public class ActionEnter {

    private final String JSON_FILE_PATH = "config.json";
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SellerMediaModel sellerMediaModel;

    /**
     * 根据不同操作类型，执行不同操作
     *
     * @param actionType
     * @return
     */
    public String exec(String actionType, String callbackName, MultipartFile multipartFile, Integer start, Integer size, Long storeId) {

        if (callbackName != null) {
            return callbackName + "(" + this.invoke(actionType, multipartFile, start, size, storeId) + ");";
        } else {
            return this.invoke(actionType, multipartFile, start, size, storeId);
        }

    }

    /**
     * 执行操作
     *
     * @param actionType 操作类型
     * @param file       文件
     * @return
     */
    public String invoke(String actionType, MultipartFile file, Integer start, Integer size, Long storeId) {
        //获取json配置
        JSONObject jsonObject = JsonFileReadUtil.jsonFileToObject(JSON_FILE_PATH);
        //文件上传后的相对路径
        String savePath = "";
        //文件扩展名，如.jpg
        String extend = null;
        //上传后的文件名
        String saveFileName = null;
        if (file != null && file.getSize() > 0) {
            //有要上传的文件
            saveFileName = UUID.randomUUID().toString();
            extend = file.getOriginalFilename()
                    .substring(file.getOriginalFilename().lastIndexOf("."))
                    .toLowerCase();
            savePath = "/" + saveFileName + extend;
        }

        switch (actionType) {
            case ACTION_TYPE_CONFIG:
                //配置,返回全部配置信息
                return jsonObject.toJSONString();
            case ACTION_TYPE_UPLOADIMAGE:
                //上传图片
                savePath = "/images/ueditor/0" + savePath;
                break;
            case ACTION_TYPE_UPLOADVIDEO:
                //上传视频
                savePath = "/videos/ueditor/0" + savePath;
                break;
            case ACTION_TYPE_UPLOADFILE:
                //上传文件
                savePath = "/files/ueditor/0" + savePath;
                break;
            case ACTION_TYPE_LISTIMAGE:
                //图片在线管理
                return getEditorOnlineListImage(start, size, storeId);
//                break;
            default:
                return new BaseState(false, "操作类型有误").toJSONString();
        }
        if (StringUtils.hasText(savePath)) {
            //执行上传文件

            Upload upload = this.getUpload();
            String saveUrl = upload.upload(file, savePath);

            State storageState = new BaseState(true);
            storageState.putInfo("size", file.getSize());
            storageState.putInfo("title", saveFileName);
            storageState.putInfo("url", saveUrl);
            if (storageState.isSuccess()) {
                storageState.putInfo("type", extend);
                storageState.putInfo("original", saveFileName + extend);
            }
            return storageState.toJSONString();
        }

        return new BaseState(false, "上传文件失败").toJSONString();

    }

    /**
     * 获取系统设置的上传方式
     *
     * @return
     */
    private Upload getUpload() {
        //根据系统配置的上传方式，获取上传对象
        Upload upload;
        switch (DomainUrlUtil.UPLOAD_IMAGE_TYPE) {
            case 1:
                //minio上传
                upload = new MinioUpload(stringRedisTemplate);
                break;
            case 2:
                //七牛云上传
                upload = new QiNiuYunUpload(stringRedisTemplate);
                break;
            case 3:
                //腾讯云上传文件
                upload = new TencentCloudUpload(stringRedisTemplate);
                break;
            case 4:
                //阿里云上传图片
                upload = new ALiYunUpload(stringRedisTemplate);
                break;
            default:
                throw new MallException("上传文件失败");
        }
        return upload;
    }

    /**
     * 图片在线管理
     */
    private String getEditorOnlineListImage(Integer start, Integer size, Long storeId) {
        if (storeId == null) {
            return new BaseState(false, "参数不完整").toJSONString();
        }
        Map<String, Object> warpMap = new HashMap<>();
        warpMap.put("state", "SUCCESS");
        List<Map<String, Object>> picInfoList = new ArrayList<>();
        List<String> picList = sellerMediaModel.getMediaFileByFileType("picture", storeId);
        picList.forEach(c -> {
            Map<String, Object> picInfoMap = new HashMap<>();
            picInfoMap.put("url", c);
            picInfoList.add(picInfoMap);
        });
        warpMap.put("list", picInfoList);
        warpMap.put("start", start);
        warpMap.put("total", picList.size());
        return JSON.toJSONString(warpMap);
    }
}
