package com.cftech.cms.exhibi_material.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.cms.exhibi_material.model.Exhibi_material;
import com.cftech.cms.exhibi_material.service.Exhibi_materialService;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.SystemConfig;
import com.cftech.core.util.UploadUtils;
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.PermissionSign;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
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.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String EXHIBI_MATERIAL_VIEW = "qy:exhibi_material:view"
 * 查看:public static final String EXHIBI_MATERIAL_EDIT = "qy:exhibi_material:edit"
 *
 * @author byj
 * @date: 2019-03-05 15:00
 */
@Slf4j
@Controller
@RequestMapping("/a/exhibi_material")
public class Exhibi_materialController {

    public static final String EXHIBI_MATERIAL_VIEW = "qy:exhibi_material:view";
    public static final String EXHIBI_MATERIAL_EDIT = "qy:exhibi_material:edit";

    private CosService cosService;
    private Cosconfig cosconfig ;
    @Autowired
    private CosconfigService cosconfigService;


    @Autowired
    private Exhibi_materialService exhibi_materialService;
    @Autowired
    private CodingruleUtils codingruleUtils;


    //列表页面
    @RequiresPermissions(value = EXHIBI_MATERIAL_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,String exhibi_id) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        if(!StringUtils.isEmpty(exhibi_id)){
            model.addAttribute("exhibi_id",exhibi_id);
        }
        return "exhibi_material/exhibi_materiallist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = EXHIBI_MATERIAL_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model ,String exhibi_id) {
        if (!StringUtils.isEmpty(id)) {
            Exhibi_material exhibi_material = exhibi_materialService.fetchById(id);
            model.addAttribute("data", exhibi_material);
        }
        if(!StringUtils.isEmpty(exhibi_id)){
            model.addAttribute("exhibi_id",exhibi_id);
        }
        return "exhibi_material/exhibi_materialform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = EXHIBI_MATERIAL_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData( Model model, HttpServletRequest request, MultipartHttpServletRequest mhsr,Long exhibi_id) {
        Long accountId = UserUtils.getmpaccounts(request);
        Exhibi_material exhibi_material = new Exhibi_material();
        JSONObject rtnJson = new JSONObject();
        Long userid = UserUtils.getUser().getId();
        Long cosconfigId = Long.valueOf(3);
        cosconfig = cosconfigService.fetchById(cosconfigId);
        MultipartFile imgArr = mhsr.getFile("qqfile");
        exhibi_material.setMaterial_name(imgArr.getOriginalFilename());
        exhibi_material.setSize(Double.valueOf(imgArr.getSize()/1024));
        if(Double.valueOf(imgArr.getSize()/1024)>20480){
            exhibi_material.setSobig("0");
        }
        try {

            boolean resultTemp=getUploadService(cosconfig.getCosType());
            JSONObject jsonObject=null;
            CosFileUploader cosFileUploader = new CosFileUploader(cosconfig,cosService);
            String format = imgArr.getOriginalFilename().substring(imgArr.getOriginalFilename().lastIndexOf(".")+1);
            //  jsonObject=cosFileUploader.uploadFile(imgArr.getBytes(),format);

            try {
                Map<String,Object> map =   UploadUtils.uploadImageFilesByQcloudInputStearm(request, "newRecommend",imgArr,"/gogi/newReCommend/");  // cosFileUploader.uploadFile(file.getBytes(),format);

                String url = map.get("fileUrl")==null?"":map.get("fileUrl").toString();
                //url+= SystemConfig.p.getProperty("Qcloud_STYLE_NAME");
                StringBuffer sb = new StringBuffer(url);
                //sb.insert(4,"s");
                exhibi_material.setFile_path(sb.toString());
            } catch (Exception e) {
                log.error(e.getMessage());
            }

            exhibi_material.setCreateBy(userid);
            exhibi_material.setDelFlag("0");
            exhibi_material.setUpdateBy(userid);
            exhibi_material.setAccountsId(accountId);
            exhibi_material.setExhibi_id(exhibi_id);
            Boolean result=exhibi_materialService.save(exhibi_material);
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
            e.printStackTrace();
        }
        rtnJson.put("success","ok");
        return rtnJson;
    }

    //获取上传服务位置
    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;
    }

    //获取列表数据
    @RequiresPermissions(value = EXHIBI_MATERIAL_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Exhibi_material exhibi_material, HttpServletRequest request,String exhibi_id) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(exhibi_material.getNumber())) {
            conds.like("number", exhibi_material.getNumber());
        }
        if (!StringUtils.isEmpty(exhibi_material.getMaterial_name())) {
            conds.like("material_name", exhibi_material.getMaterial_name());
        }
        if(!StringUtils.isEmpty(exhibi_id)){
            conds.equal("exhibi_id",exhibi_id);
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

        List<Exhibi_material> list = exhibi_materialService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = exhibi_materialService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = EXHIBI_MATERIAL_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            exhibi_materialService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

}
