package com.lightinit.hsdataportal.controller.open;

import com.lightinit.hsdataportal.common.ConfigUtils;
import com.lightinit.hsdataportal.common.SysContants;
import com.lightinit.hsdataportal.controller.BaseController;
import com.lightinit.hsdataportal.dictionary.*;
import com.lightinit.hsdataportal.entity.BaseExample;
import com.lightinit.hsdataportal.impl.MyDataServiceImpl;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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.*;
import java.util.List;

/**
 * @Author: sunxiang
 * @Date: 2018/6/9 16:47
 * @Description:
 **/
@Controller
@RequestMapping(value = "/open/data")
public class DataOpenController extends BaseController{

    @Autowired
    private IOderService oderService;
    @Autowired
    private IResourceAuthService resourceAuthService;
    @Autowired
    private IDataService dataService;
    @Autowired
    private IResourceCatelogService resourceCatelogService ;
    @Autowired
    private IMyDataService myDataService;
    /*
    *@Description 数据查看首页
    *@Param catelogName:分类/机构;  openType:开放类型
    *@Date 2018/6/9
    *@return
    **/
    @RequestMapping(value="index.htm")
    public ModelAndView  getDataIndex(DataSearchModel inputModel,@RequestParam(defaultValue = "1") int pageNo){
        ModelAndView modelAndView = new ModelAndView("open/data/index");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        inputModel.setSortCategory(DicSortCategory.DEFAULT_SORT);
        List<DataListModel> list=dataService.getDataIndex(inputModel,1);//1：开放平台的标识符
        //取出图片映射路径
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        for (DataListModel dataListModel : list) {
            dataListModel.setResourceImg(imageContextPath+dataListModel.getResourceImg());
        }
        pager.setTotal(dataService.getIndexCount(inputModel,1));
        modelAndView.addObject("list",list);
        modelAndView.addObject("themes",resourceCatelogService.getResourceCatelogNameByType(DicResourceCatelogType.THEME,DicResourceType.DATA,DicPlatformType.OPEN)) ;
        modelAndView.addObject("sectors",resourceCatelogService.getSectorNameList()) ;
        modelAndView.addObject("chargeMethods",DicPublishSettingChargeMethod.getInstacne().getDicMap()) ;
        modelAndView.addObject("searchModel", inputModel);
        modelAndView.addObject("pager",pager);
        return modelAndView;
    }

    /*
    *@Description 查询开放平台某一个数据的详细情况
    *@Param
    *@Date 2018/6/9
    *@return
    **/
    @RequestMapping(value="detail.htm/{id}")
    public ModelAndView getDataDetail(@PathVariable Long id,HttpSession session,HttpServletRequest req,HttpServletResponse resp){
        ModelAndView modelAndView = new ModelAndView("open/data/detail");
        String paramType=(String)req.getAttribute("paramType");//是否已经申请标识符
        String toPayed=(String)req.getAttribute("toPayed");//支付标志符
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        Long userId=null;
        if(loginUser !=null){
            userId=loginUser.getId();
        }
        DataDetailModel dataDetailModel=dataService.getDataDetail(id,userId,1);//1：开放平台的标识符
        //取出图片映射路径
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        if(dataDetailModel!=null){
            dataDetailModel.setResourceImg(imageContextPath+dataDetailModel.getResourceImg());
            if(dataDetailModel.getDataFile()!=null){
                dataDetailModel.setDataFileName(StringUtils.substringAfterLast(dataDetailModel.getDataFile(),File.separator));
            }
            if(dataDetailModel.getDemoFile()!=null){
                dataDetailModel.setDemoFileName(StringUtils.substringAfterLast(dataDetailModel.getDemoFile(),File.separator));
            }
        }
        modelAndView.addObject("paramType",paramType);//是否已经申请标识符
        modelAndView.addObject("toPayed",toPayed);//支付标志符
        modelAndView.addObject("outputModel",dataDetailModel);
        return modelAndView;
    }

    /*
     *@Description 开放数据申请，从数据库中判断是否 免费/收费数据/需申请
     *@Param    id:publish_setting表     applyReasn:如果是申请，申请理由
     *@Date 2018/6/10
     *@return  免费/收费数据/
     **/
    @RequiresAuthentication
    @RequestMapping(value="apply.action")
    @ResponseBody
    public ResultState<Long> getDataOpenType(MyDataShareListModel inputModel, HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        //判断是否已经申请过
        Long resourceAuthId= myDataService.getResourceAuthId(inputModel.getPublishSettingId(),loginUser.getId(), DicPlatformType.OPEN);
        if(resourceAuthId !=null){
            ResultState resultState = new ResultState();
            resultState.setMsg("已经申请过了，请前往用户中心下载");
            return resultState;
        }

        DataApplyPriceModel dataApplyPriceModel =dataService.getDataOpenType(inputModel.getPublishSettingId());
        if(dataApplyPriceModel !=null){
            BeanUtils.copyProperties(dataApplyPriceModel,inputModel);
           inputModel.setPlatformType(DicPlatformType.OPEN);
           inputModel.setUserORAdminId(loginUser.getId());
        }
        ResultState<Long> resultState=new ResultState<>();
        if(DicResourceOpenType.UNCONDITIONAL.equals(dataApplyPriceModel ==null?null:dataApplyPriceModel.getOpenType())) {
            if (DicPublishSettingChargeMethod.FREE.equals(dataApplyPriceModel.getChargeMethod())) {
                resultState = dataService.insertDataApply(inputModel, DicPublishSettingChargeMethod.FREE, 1);
            }else{
                resultState = dataService.insertDataApply(inputModel, DicPublishSettingChargeMethod.BY_NUMBER_OF_TIMES, 1);
            }
        } else if(DicResourceOpenType.NEED_TO_APPLY.equals(dataApplyPriceModel ==null?null:dataApplyPriceModel.getOpenType())){
            resultState = dataService.insertDataApply(inputModel, null, 2);
        }else{
            resultState.setMsg("操作失败");
        }
        return resultState;
    }


    /*
    *@Description 关注
    *@Param id:关注的publishSettingId
    *@Date 2018/6/14
    *@return
    **/
    @RequiresAuthentication
    @RequestMapping(value="follow.action/{id}")
    @ResponseBody
    public ResultState<Long> follow(@PathVariable Long id,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        return dataService.follow(DicPlatformType.OPEN,id,loginUser.getId());
    }

    /**
     *取消关注
     * 关注表id
     * @param
     * @param
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "delfollow.action/{delId}")
    @ResponseBody
    public ResultState delfollow(@PathVariable long delId,HttpSession session) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResultState  resultState = dataService.delfollow(delId, loginUser.getId());
        return resultState;
    }

    /*
    *@Description 洽谈
    *@Param
    *@Date 2018/6/14
    *@return
    **/
    @RequiresAuthentication
    @RequestMapping(value = "offlineConference.action")
    @ResponseBody
    public ResultState offlineConference(@Validated DataOfflineConferenceModel inputModel, BindingResult bindingResult, HttpSession session){
        if(bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        return dataService.offlineConference(inputModel,loginUser.getId());
    }

    /*
    *@Description 数据视图
    *@Param
    *@Date 2018/7/1
    *@return
    **/
    @RequestMapping(value="dataview.htm")
    public ModelAndView  getDateView(@RequestParam(defaultValue = "1") int pageNo){
        ModelAndView modelAndView = new ModelAndView("open/data/view");
        List<DataViewListModel> dataViewList=dataService.getDataViewList(DicPlatformType.OPEN);
        List<DataStructListModel> dataStructModel=dataService.getDataStructreList(DicPlatformType.OPEN);
        Long sectorTotal=dataService.getSectorTotal(DicPlatformType.OPEN);
        Long sectorDataTotal=dataService.getSectorDataTotal(DicPlatformType.OPEN);
        //取出图片映射路径
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        for (DataViewListModel dataListModel : dataViewList) {
            dataListModel.setCatelogImg(imageContextPath+dataListModel.getCatelogImg());
        }
        modelAndView.addObject("dataViewList",dataViewList);//结构视图
        modelAndView.addObject("dataStructModel",dataStructModel);//结构视图
        modelAndView.addObject("sectorTotal",sectorTotal);//部门总数
        modelAndView.addObject("sectorDataTotal",sectorDataTotal);//所有部门的数据总数
        return modelAndView;
    }

    /*
    *@Description 文件下载
    *@Param Id:publishSettingId     type:示例/数据类型
    *@Date 2018/7/9
    *@return 
    **/
    @RequiresAuthentication
    @RequestMapping(value="download.action/{type}/{id}")
    public String  download(@PathVariable int type,@PathVariable Long id,HttpSession session,HttpServletRequest req,HttpServletResponse resp) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        Long resourceAuthId= myDataService.getResourceAuthId(id,loginUser.getId(), DicPlatformType.OPEN);
        if(resourceAuthId ==null){
            //申请页面
            req.setAttribute("paramType","1");//未申请标识符
            return "forward:/open/data/detail.htm/"+id;
        }
        MyDataShareListModel myDataShareListModel = myDataService.selectResourceAuth(loginUser.getId(), resourceAuthId, DicPlatformType.OPEN);
        if(myDataShareListModel ==null){
            //申请页面
            req.setAttribute("paramType","1");
            return "forward:/open/data/detail.htm/"+id;
        }else if(DicOrderState.PAY_SUCCESS.equals(myDataShareListModel.getOrderState())){
            BufferedInputStream bis = null;
            try {
                String demoFile="";
                if (type == 1) {
                    demoFile =  myDataShareListModel.getDemoFile();//示例文件下载
                }
                if (type == 2) {
                    demoFile = myDataShareListModel.getDataFile();//数据文件下载
                }
                String filename = StringUtils.substringAfterLast(demoFile, File.separator);
                filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
                String urlPath= ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.UPLOAD_FILE_ROOT_DIR);
                File file =new File(urlPath+demoFile);
                resp.reset();
                resp.setContentType("application/octet-stream");
                resp.setCharacterEncoding("utf-8");
                resp.setContentLength((int) file.length());
                resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
                byte[] buff = new byte[1024];
                OutputStream os = null;
                os = resp.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = 0;
                while ((i = bis.read(buff)) != -1) {
                    os.write(buff, 0, i);
                    os.flush();
                }
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }else{
            //return new ResponseEntity<byte[]>(null,headers, HttpStatus.OK);
            req.setAttribute("paramType","2");//已经申请过标识符
            req.setAttribute("toPayed","3");//付费标识符
            return "forward:/open/data/detail.htm/"+id;
        }
    }
}

