package com.yc.education.controller.admin;

import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.BaseState;
import com.github.pagehelper.PageInfo;
import com.yc.education.model.Technology;
import com.yc.education.service.TechnologyService;
import com.yc.education.util.AjaxMessage;
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.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 org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * huangpan
 * 2019/10/9
 * energy
 */
@Controller
public class TechnologyController {
    @Autowired
    TechnologyService technologyService;

    private static Random rand = new Random();
    private static String[] str = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
    /*查询所有*/
    @RequestMapping("admin/technology-list.html")
    public ModelAndView seletctAllTech(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum ,
                                       @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize, String titleName){
        ModelAndView modelAndView=new ModelAndView();
        List<Technology> technologies = technologyService.selectAllTechnology(pageNum, pageSize, titleName);
        modelAndView.addObject("pageInfo", new PageInfo<>(technologies));
        modelAndView.addObject("titileName", titleName);
        modelAndView.addObject("technologies", technologies);
        return modelAndView;
    }
    /*查询单条*/
    @RequestMapping("admin/technologyByid.html")
    public ModelAndView selTechnologyById(Integer id, HttpSession session){
        ModelAndView modelAndView =new ModelAndView("admin/technology-update");
        Technology technology = technologyService.selectTechnologyById(id);
        modelAndView.addObject("technology", technology);
        session.setAttribute("technologys", technology);
        return modelAndView;
    }
    /*执行修改*/
    @RequestMapping("admin/technology-update.html")
    public void updateTechnology(Technology technology, HttpSession session, HttpServletResponse response)throws  Exception{
        Technology technology1=(Technology)session.getAttribute("technologys");
        if (technology.getIcon()==null||technology.getIcon().equals("")){
            technology.setIcon(technology1.getIcon());
        }
        if (technology.getLthumbnail()==null||technology.getLthumbnail().equals("")){
            technology.setLthumbnail(technology1.getLthumbnail());
        }
        if (technology.getNthumbnail()==null||technology.getNthumbnail().equals("")){
            technology.setNthumbnail(technology1.getNthumbnail());
        }
       /* SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String commentdatemin = df.format(new Date());
        technology.setDatechanged(commentdatemin);*/
        technologyService.updateNotNull(technology);
        response.sendRedirect("technology-list.html");
    }
    /*新增*/
    @RequestMapping("admin/technology-add.html")
    public ModelAndView technologyAdd(){
        ModelAndView modelAndView=new ModelAndView();
        return modelAndView;
    }
    /*执行新增*/
    @RequestMapping("admin/technology-save.html")
    public void saveTechnology(Technology technology, HttpServletRequest request, HttpServletResponse response)throws Exception{
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        String contextPath = request.getSession().getServletContext().getContextPath();
        BaseState state = (BaseState) new ActionEnter(request, rootPath, contextPath, "img").invoke(ActionMap.UPLOAD_FILE);
        String url = state.getInfo("url");
        if (url!=null&& !url.equals("")) {
           /* technology.setSurfaceplot(url);*/
        }
        if (technology.getDatechanged().equals("")){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String commentdatemin = df.format(new Date());
        technology.setDatechanged(commentdatemin);}
        technologyService.save(technology);
        response.sendRedirect("technology-list.html");
    }
    /*执行删除*/
    @RequestMapping("admin/delTechnologyById.html")
    @ResponseBody
    public void delTechnologyById(@RequestParam( value = "id")Integer id){
        technologyService.deleteTechnologyById(id);
    }
    /*批量删除*/
    @RequestMapping("admin/delTechnologyAll.html")
    public void delTechnologyAll(@RequestParam( value = "chkvalue") String chkvalue,HttpServletResponse response)throws  Exception{
        String[] chkv=chkvalue.split(",");
        for (int i=0;i<chkv.length;i++){
             Integer item=Integer.parseInt(chkv[i]);
             technologyService.deleteTechnologyById(item);
        }
        response.sendRedirect("technology-list.html");
    }


    /*ajax上传*/
    @ResponseBody
    @RequestMapping("admin/uploadFindSkillImages")
    public AjaxMessage<Object> uploadFindSkillImages(HttpServletRequest request)
            throws IllegalStateException, IOException
    {
        AjaxMessage<Object> ajax = new AjaxMessage<Object>();
        System.out.println("进入控制层");
        String pathString = "";
        String allpath = "";
        List<String> paths = new ArrayList<String>();

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request))
        {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext())
            {
                MultipartFile file = multiRequest.getFile((String)iter.next());
                System.out.println("file:" + file.getSize());
                if (!file.isEmpty())
                {
                    String sms = "";

                    StringBuffer buf = new StringBuffer();
                    for (int i = 0; i < 3; i++) {
                        buf.append(str[rand.nextInt(10)]);
                    }
                    String originalFileName = file.getOriginalFilename();



                    ajax.setData(originalFileName);


                    String suffixString = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);


                    String fileName = sms + new Date().getTime() + "." + suffixString;


                    String path = request.getSession().getServletContext().getRealPath("/");
                    String contextPath = request.getSession().getServletContext().getContextPath();

                    File localFile = new File(path + "findskill/" + fileName);
                    System.err.println(path + "findskill/" + fileName);
                    try
                    {
                        file.transferTo(localFile);

                        paths.add("/picat/" + fileName);
                        pathString = contextPath + "/findskill/" + fileName;
                        allpath = path + "findskill/" + fileName;
                    }
                    catch (IllegalStateException e)
                    {
                        e.printStackTrace();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
        ajax.setMsg(pathString);
        return ajax;
    }

}
