package com.cftech.brand.apply.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.brand.apply.model.BrandApply;
import com.cftech.brand.apply.model.BrandApplyProduct;
import com.cftech.brand.apply.service.BrandApplyProductService;
import com.cftech.brand.apply.service.BrandApplyService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.*;
import com.cftech.cos.alioss.AliOssStorageService;
import com.cftech.cos.config.cosconfig.model.Cosconfig;
import com.cftech.cos.config.cosconfig.service.CosconfigService;
import com.cftech.cos.core.CosService;
import com.cftech.cos.qcloud.QcloudStorageService;
import com.cftech.cos.qiniu.QiniuStorageService;
import com.cftech.cos.uploader.CosFileUploader;
import com.cftech.sys.security.UserUtils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.DeleteObjectRequest;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.region.Region;
import org.apache.commons.collections.map.HashedMap;
import org.jboss.resteasy.plugins.server.sun.http.HttpServerResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Package com.cftech.brand.apply.web
 * @Name cftech-platform
 * @Description: TODO 品牌申请单成品
 * @date 2020/6/17
 */
@Slf4j
@Controller
@RequestMapping("/a/brandApplyProduct")
public class BrandApplyProductController {

    private CosService cosService;
    private Cosconfig cosconfig;

    @Autowired
    BrandApplyProductService brandApplyProductService;

    @Autowired
    BrandApplyService brandApplyService;

    @Autowired
    private CosconfigService cosconfigService;

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

    /**
     * 编辑页面（新增、修改）
     *
     * @param applyId 品牌申请ID
     * @param model
     * @return
     */
    @RequestMapping("/form")
    public String form(Long applyId, Model model) {
        if (!StringUtils.isEmpty(applyId)) {
            BrandApply brandApply = brandApplyService.fetchById(applyId);
            if (brandApply != null) {
                List<BrandApplyProduct> brandApplyProducts = brandApplyProductService.fetchByApplyId(applyId);
                if (!CollectionUtils.isEmpty(brandApplyProducts)) {
                    model.addAttribute("data", brandApplyProducts.get(0));
                } else {
                    model.addAttribute("data", null);
                }
            }
            Conds conds = new Conds();
            conds.equal("del_flag", Constants.DEL_FLAG_0);
            List<Cosconfig> cosconfigList = cosconfigService.fetchSearchByPage(conds, null, 0, 0);
            model.addAttribute("cosconfigList", cosconfigList);
            model.addAttribute("applyId", applyId);
        }
        return "brandApply/brandApplyProductform";
    }

    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(BrandApplyProduct brandApplyProduct) {
        JSONObject rtnJson = new JSONObject();
        try {
            BrandApply brandApply = brandApplyService.fetchById(brandApplyProduct.getApplyId());
            if (brandApply == null) {
                rtnJson.put("errorNo", 3);
            } else {
               if(!brandApply.getStatus().equals("3")) {
                   brandApply.setProductName(brandApplyProduct.getName());
                   brandApply.setProductFormat(brandApplyProduct.getFormat());
                   brandApply.setProductLabel(brandApplyProduct.getLabel());
                   brandApply.setUpdateBy(UserUtils.getUser().getId());
                   brandApply.setFilePrefix(brandApplyProduct.getFilePrefix());
                   brandApplyService.update(brandApply);
                   rtnJson.put("errorNo", 0);
               } else {
                   rtnJson.put("errorNo", 4);
               }
            }
        } catch (Exception e) {
            log.error("保存品牌成品异常:" + e.getMessage());
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    // 文件上传
    @RequestMapping("/fileUpload")
    @ResponseBody
    public JSONObject fileUpload(HttpServletRequest request, Long applyId, Long cosconfigId, MultipartHttpServletRequest mhsr, MultipartFile file) {
        BrandApply brandApply = brandApplyService.fetchById(applyId);
        JSONObject rtnJson = new JSONObject();
        cosconfig = cosconfigService.fetchById(cosconfigId);
        MultipartFile imgArr = mhsr.getFile("qqfile");
        try {
            if (cosconfig == null) {
                //上传到本地
                Map<String, Object> resultMap = uploadMedia(UserUtils.getmpaccounts(request), brandApply.getName(), imgArr, request);
                String url = resultMap.get("mediaUrl").toString();
                String key = resultMap.get("localPath").toString();
            } else {
                boolean resultTemp = getUploadService(cosconfig.getCosType());
                JSONObject jsonObject = null;
                CosFileUploader cosFileUploader = new CosFileUploader(cosconfig, cosService);
                String fileName = imgArr.getOriginalFilename();
                String format = imgArr.getOriginalFilename().substring(imgArr.getOriginalFilename().lastIndexOf(".") + 1);
                try {
                    Map<String, Object> map = UploadUtils.uploadImageFilesByQcloudInputStearm(request, "brandProduct", imgArr, "/gogi/brandProduct/");  // cosFileUploader.uploadFile(file.getBytes(),format);
                    String url = map.get("fileUrl") == null ? "" : map.get("fileUrl").toString();
                    BrandApplyProduct brandApplyProduct = new BrandApplyProduct();
                    brandApplyProduct.setApplyId(applyId);
                    brandApplyProduct.setCosconfigId(cosconfigId);
                    brandApplyProduct.setFileUrl(url);
                    brandApplyProduct.setFormat(format);
                    brandApplyProduct.setName(fileName);
                    brandApplyProduct.setDelFlag(false);
                    brandApplyProduct.setCreateBy(UserUtils.getUser().getId());
                    brandApplyProductService.save(brandApplyProduct);
                    rtnJson.put("errorNo", 2);
                    rtnJson.put("fileUrl", url);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
            e.printStackTrace();
        }
        rtnJson.put("success", true);
        return rtnJson;
    }

    @RequestMapping("/fileDownload")
    @ResponseBody
    public void fileDownload(String id, HttpServletResponse response) {
        try {
            BrandApplyProduct bean = brandApplyProductService.fetchById(id);
            if (bean != null) {
                String title = bean.getName().substring(0, bean.getName().lastIndexOf("."));
                String prefix = bean.getName().substring(bean.getName().lastIndexOf(".") + 1);
                downPicture(response, bean.getFileUrl(), title, prefix);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @RequestMapping("/fileDelete")
    @ResponseBody
    public JSONObject fileRemove(String id,String fileUrl) {
        JSONObject rtnJson = new JSONObject();
        try {
            // 删除图片信息
            Conds conds = new Conds();
            conds.equal("apply_id", id);
            conds.equal("file_url", fileUrl);
            conds.equal("del_flag", Constants.DEL_FLAG_0);
            BrandApplyProduct brandApplyProduct = brandApplyProductService.fetchSearchByConds(conds);
            if(brandApplyProduct != null) {
                brandApplyProductService.delete(brandApplyProduct.getId());
            }
            rtnJson.put("errorNo", 0);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        rtnJson.put("success", true);
        return rtnJson;
    }

    /**
     * 上传到本地
     */
    public static Map<String, Object> uploadMedia(Long userId, String moduleName, MultipartFile file, HttpServletRequest request) {
        Map<String, Object> params = new HashedMap();
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        HttpURLConnection conn = null;
        String finalFileName = "";
        try {
            String dir = USER_IMAGES_DIR + "";
            File ff = new File(dir);
            if (!ff.exists()) {
                ff.mkdir();
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//文件扩展名
            String fileName = UUID.randomUUID().toString();
            finalFileName = fileName + suffix;

            String realPath = dir + File.separator + finalFileName;
            params.put("localPath", realPath);
            File localFile = new File(realPath);
            if (!localFile.exists() && !localFile.isFile()) {
                file.transferTo(localFile);
            }
        } catch (IOException e) {
            log.error("上传文件失败：{}", e.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("上传文件失败 IOException：{}", e.getMessage());
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("上传文件失败 IOException：{}", e.getMessage());
                }
            }

            if (conn != null) {
                conn.disconnect();
            }
        }
        String mediaUrl = ImageUrlUtils.formatImageUrl(finalFileName, "");//文件访问URL
        params.put("mediaUrl", mediaUrl);
        return params;
    }

    //获取上传服务位置
    private boolean getUploadService(String cosType) {
        if (cosType.equals("qcloud")) {
            //上传到腾讯
            cosService = new QcloudStorageService();
        } else if (cosType.equals("ali")) {
            //上传到阿里
            cosService = new AliOssStorageService();
        } else if (cosType.equals("qiniu")) {
            //上传到七牛
            cosService = new QiniuStorageService();
        } else {
            //上传到本地
            return false;
        }
        return true;
    }

    public void downPicture(HttpServletResponse response, String urls, String title, String prefix) throws IOException {


        //获取文件
        URL url = new URL(urls);
        URLConnection conn = url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //输出流
        InputStream fs = conn.getInputStream();

        int bytesRead = 0;
        byte[] image = new byte[8192];
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("gb2312"), "ISO8859-1") + "." + prefix);
        try {
            while ((bytesRead = fs.read(image, 0, 8192)) != -1) {
                response.getOutputStream().write(image, 0, bytesRead);

            }
            fs.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }


}
