package com.cftech.upload.web;


import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.util.QcloudUploadUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.core.util.UploadUtils;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by wuxianfei on 2017/3/10.
 */

@Controller
@RequestMapping(value = "/a/fileinput")
@Slf4j
public class FileUploadController {

    @Autowired
    private  MpAccountsService accountsService;

    // 图片目录
    public static final String USER_IMAGES_DIR = SystemConfig.p.getProperty("userfiles.imgdir");

    /**
     * 文件上传
     *
     * @param className 类名
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public JSONObject fileupload(@RequestParam String className, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        try {
            Long accountsId = UserUtils.getmpaccounts(request);
            MpAccountsEntity entity = accountsService.getDetail(accountsId);
            int type = Integer.valueOf(entity.getUploadType());
            rtnJson.put("errorNo", "0");
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (multipartResolver.isMultipart(request)) {
                JSONArray imgArr=new JSONArray();
                JSONArray configArr=new JSONArray();
                List<MultipartFile> files = new ArrayList<MultipartFile>();
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                StringBuffer imgStr = new StringBuffer();
                String contextName = request.getContextPath();
                while (iter.hasNext()) {
                    files = multiRequest.getFiles(iter.next());
                    int size = files.size();
                    if (size > 3) {
                        rtnJson.put("errorNo", "1");
                        rtnJson.put("errorMsg", "图片最多三张");
                        return rtnJson;
                    }
                    for (int i = 0; i < size; i++) {
                        MultipartFile file = files.get(i);
                        if (type == 0) {//上传本地
                            String uploadPath = SystemConfig.p.getProperty("filepath") + File.separator + className + System.currentTimeMillis() / 1000;
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {//如文件夹不存在 则创建文件夹
                                uploadDir.mkdir();
                            }
                            Map<String,Object> rtnMap =UploadUtils.uploadMedia(accountsId,className,file,request);
                            String localFilePath = rtnMap.get("localPath").toString();
                            String mediaUrl = rtnMap.get("mediaUrl").toString();
                            imgArr.add("<img class='kv-preview-data file-preview-image' alt='" + localFilePath + "' style='width:auto;height:180px;'  src='" + mediaUrl  + "' >");
                            JSONObject config=new JSONObject();
                            config.put("caption",file.getOriginalFilename());
                            config.put("url",contextName+"/a/fileinput/delete");
                            config.put("key",mediaUrl);
                            JSONObject extra=new JSONObject();
                            extra.put("id",mediaUrl);
                            config.put("extra",extra);
                            configArr.add(config);
                            imgStr.append(mediaUrl + ",");
                        } else if (type == 1) {//上传cos
                            Map<String, Object> uploadResult = UploadUtils.uploadImageFilesByQcloudInputStearm(request, "faye5", file, "/"+className + System.currentTimeMillis() / 1000);
                            if (uploadResult != null && Integer.valueOf(uploadResult.get("errCode").toString()) == 0) {
                                if (StringUtil.isNotBlank(uploadResult.get("fileUrl").toString())) {
                                    String img=uploadResult.get("fileUrl").toString();
                                    imgArr.add("<img class='kv-preview-data file-preview-image' alt='" + img + "' style='width:auto;height:180px;'  src='" + img  + "' >");
                                    JSONObject config=new JSONObject();
                                    config.put("caption",file.getName());
                                    config.put("url",contextName+"/a/fileinput/delete");
                                    config.put("key",img);
                                    JSONObject extra=new JSONObject();
                                    extra.put("id",img);
                                    config.put("extra",extra);
                                    configArr.add(config);
                                    imgStr.append(uploadResult.get("fileUrl").toString() + ",");
                                }
                            } else {
                                rtnJson.put("errorNo", "1");
                                rtnJson.put("errorMsg", "上传图片失败 errcode : " + uploadResult);
                            }
                        } else {
                            rtnJson.put("errorNo", "1");
                            rtnJson.put("errorMsg", "暂不支持的上传类型！");
                        }
                    }

                }
                rtnJson.put("initialPreview",imgArr);
                rtnJson.put("initialPreviewConfig",configArr);
                rtnJson.put("data", imgStr.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", "1");
            rtnJson.put("errorMsg", "服务器异常: " + e);
            log.error("文件上传异常" + e);
        }
        log.error(rtnJson.toString());
        return rtnJson;
    }


    /**
     * 文件删除
     *
     * @param id 文件id
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public JSONObject delete(@RequestParam String id,HttpServletRequest request) {

        JSONObject rtnJson = new JSONObject();
        Long accountsId = UserUtils.getmpaccounts(request);
        MpAccountsEntity entity = accountsService.getDetail(accountsId);

        int type = Integer.valueOf(entity.getUploadType());
        try {
            rtnJson.put("errorNo", "1");

            if (type == 0) {
                String filePath = USER_IMAGES_DIR + accountsId;
                id = id.substring(id.lastIndexOf("=")+1);
                filePath=filePath+File.separator+id;
                File file = new File(filePath);
                file.delete();
            } else if (type == 1) {
                String cosPath = id.replace("http://", "");
                cosPath=cosPath.substring(cosPath.indexOf("/"));
                String bucketName = SystemConfig.p.getProperty("Qcloud_BUCKET_NAME");
                String result = QcloudUploadUtils.delfile(bucketName, cosPath);
                log.info(result);
                JSONObject json = JSONObject.fromObject(result);
                if (!json.getString("code").equals("0")) {
                    rtnJson.put("errorNo", "1");
                    rtnJson.put("errorMsg", "删除失败: " + json.getString("message"));
                }
            } else {
                rtnJson.put("errorNo", "1");
                rtnJson.put("errorMsg", "暂不支持的操作类型！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件删除失败 ： " + e);
            rtnJson.put("errorNo", "1");
            rtnJson.put("errorMsg", "文件删除失败" + e);
        }
        return rtnJson;
    }

}
