package com.lightinit.hsdataplatformresdir.controller.admin;

import com.lightinit.hsdataplatformresdir.common.DocUtil;
import com.lightinit.hsdataplatformresdir.dictionary.DicResourceOpenType;
import com.lightinit.hsdataplatformresdir.dictionary.DicResourceShareType;
import com.lightinit.hsdataplatformresdir.entity.BaseExample;
import com.lightinit.hsdataplatformresdir.model.ResultState;
import com.lightinit.hsdataplatformresdir.model.admin.DataCatelogListModel;
import com.lightinit.hsdataplatformresdir.model.admin.DataCatelogSearchModel;
import com.lightinit.hsdataplatformresdir.model.admin.LoginUser;
import com.lightinit.hsdataplatformresdir.service.admin.IDataCatelogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: sunxiang
 * @Date: 2019/3/14 21:53
 * @Description:
 **/
@RequestMapping("/admin/subscribeAndDownload")
@Controller
public class SubscribeAndDownloadController {

    @Autowired
    private IDataCatelogService dataCatelogService;

    @RequestMapping(value="index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/subscribeAndDownload/index");
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value="list.action")
    public ModelAndView list(DataCatelogSearchModel inputModel, @RequestParam(defaultValue = "1")int pageNo, HttpSession session){
        ModelAndView modelAndView = new ModelAndView("admin/subscribeAndDownload/list");
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setSupplier(loginUser.getOrgId());
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        List<DataCatelogListModel> OutputStream=dataCatelogService.getSubscribeAndDownloadDataCatelogList(inputModel);
        pager.setTotal(dataCatelogService.getSubscribeAndDownloadDataCatelogCount(inputModel));
        modelAndView.addObject("list", OutputStream);
        modelAndView.addObject("pager",pager);
        return modelAndView;
    }

    @RequestMapping(value="subcribe.action/{supplierId}/{dataCatelogId}")
    @ResponseBody
    public ResultState subcribe(@PathVariable long supplierId,@PathVariable long dataCatelogId, HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        return dataCatelogService.subcribe( supplierId,dataCatelogId,loginUser);
    }

    static String MODELPATH = "/uploadFiles/";

    @RequestMapping(value = {"/download.action/{supplierId}/{dataCatelogId}"}, produces = "text/html;charset=UTF-8")
    public void getDownloadSource(@PathVariable long supplierId,@PathVariable long dataCatelogId, HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        List<DataCatelogListModel> list=dataCatelogService.getDownloadSource(loginUser.getOrgId(),dataCatelogId);
        if(list==null ||list.size()<1){
            return;
        }
        //引入导出word的工具类
        DocUtil docUtil = new DocUtil();
        //引入处理图片的工具类，包含将base64编码解析为图片并保存本地，获取图片本地路径
        /*ImageUtil imageUtil = new ImageUtil();*/
        //建立map存储所要导出到word的各种数据和图像，不能使用自己项目封装的类型，例如PageData
        Map<String, Object> dataMap = new HashMap<String, Object>();
        /*
         *  这一步，请求所需要导出到word的数据quotaList，把你们的数据处理放到这里就行了
         */


        //这一步，进行图片的处理，获取前台传过来的图片base64编码，在利用工具类解析图片保存到本地，然后利用工具类获取图片本地地址
       /* String barBase64Info = request.getParameter("barBase64Info");
        String path = "D:";
        String image1 = ImageUtil.savePictoServer(barBase64Info, path);
        image1  = imageUtil.getImageStr(image1);*/
        //BizPartyReportModel report = partyService.getReport(77012L);
        //将以上处理的数据都存入dataMap 中
        //dataMap.put("title1","新-word");
        //List<NameAndValueReturnModel> ayList = report.getAyList();
        dataMap.put("alist", list);
        //以下都是进行word文件的处理，直接复制，然后细节按需修改就行了
        request.setCharacterEncoding("utf-8");
        File file = null;
        InputStream fin = null;
        OutputStream out = null;
        String filename = "下载资源文件.xls";
        //dataMap是上面处理完的数据，MODELPATH是模板文件的存储路径，"模板1.ftl"是相应的模板文件
        file = docUtil.createDoc(dataMap, MODELPATH, "excel.ftl", request);
        fin = new FileInputStream(file);
        response.setContentLength((int) file.length());//需要传递这个长度，不然下载文件后，打开提示内容有问题，如docx等
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"), "iso8859-1"));
        out = response.getOutputStream();
        byte[] buffer = new byte[1024]; // 缓冲区
        int bytesToRead = -1;
        // 通过循环将读入的Word文件的内容输出到浏览器中
        while ((bytesToRead = fin.read(buffer)) != -1) {
            out.write(buffer, 0, bytesToRead);
        }
        if (fin != null)
            fin.close();
        if (out != null)
            out.close();
        if (file != null)
            file.delete(); // 删除临时文件
    }


    @RequestMapping(value = "/audit.htm")
    public ModelAndView auditIndex(HttpSession session){
        ModelAndView modelAndView=new ModelAndView("admin/subscribeAndDownload/auditIndex");
       /* LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        List<DataCatelogListModel> list=dataCatelogService.auditIndex(loginUser);
        modelAndView.addObject("list",list);*/
        return modelAndView;
    }

    @RequestMapping(value = "/audit.action")
    public ModelAndView audit( HttpSession session,HttpServletRequest request, HttpServletResponse response,@RequestParam(defaultValue = "1")int pageNo){
        ModelAndView modelAndView=new ModelAndView("admin/subscribeAndDownload/auditList");
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        List<DataCatelogListModel> list=dataCatelogService.auditIndex(loginUser,pager);
        pager.setTotal(dataCatelogService.auditCount(loginUser.getOrgId()));
        modelAndView.addObject("list",list);
        modelAndView.addObject("pager",pager);
        return modelAndView;
    }

    @RequestMapping(value = "/audit.do/{id}/{flag}")
    @ResponseBody
    public ResultState auditDo(@PathVariable long id,@PathVariable int flag, HttpSession session,HttpServletRequest request, HttpServletResponse response){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        return dataCatelogService.auditDo(id,flag,loginUser);
    }

}

