package com.lightinit.hsdataportal.controller.open;

import com.google.gson.Gson;
import com.lightinit.hsdataportal.common.*;
import com.lightinit.hsdataportal.controller.BaseController;
import com.lightinit.hsdataportal.dictionary.*;
import com.lightinit.hsdataportal.entity.*;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IMicroappService;
import com.lightinit.hsdataportal.service.IMyDataService;
import com.lightinit.hsdataportal.service.IResourceCatelogService;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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 org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RequestMapping(value = "/open/microapp")
@Controller
public class MicroappOpenController extends BaseController {
    @Autowired
    private IMicroappService microappService;
    @Autowired
    private IResourceCatelogService resourceCatelogService ;
    @Autowired
    private IMyDataService myDataService;
    @RequestMapping(value = "openList.action")
    @ResponseBody
    public ModelAndView openList(MicroappSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo) {
        ModelAndView modelAndView = new ModelAndView("/open/microapp/index");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        inputModel.setPublishState(DicPublishApiState.PUBLISH);
        inputModel.setSortCategory(DicSortCategory.DEFAULT_SORT);
        List<MicroappListModel> outputModel = microappService.selectOpenList(inputModel);
        pager.setTotal(microappService.selectOpenCount(inputModel));
        modelAndView.addObject("themes",resourceCatelogService.getResourceCatelogNameByType(DicResourceCatelogType.THEME,DicResourceType.MICROAPP,DicPlatformType.OPEN)) ;
        modelAndView.addObject("sectors",resourceCatelogService.getSectorNameList()) ;
        modelAndView.addObject("chargeMethods",DicPublishSettingChargeMethod.getInstacne().getDicMap()) ;
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        modelAndView.addObject("searchModel", inputModel);
        modelAndView.addObject("flag", inputModel.getFlag());
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        modelAndView.addObject("imageContextPath", imageContextPath);
        return modelAndView;
    }

    /**
     * 详情页面
     * settingId
     * @param id
     * @return
     */
    @RequestMapping(value = "view.htm/{id}")
    @ResponseBody
    public ModelAndView view(HttpSession session,@PathVariable long id) {
        ModelAndView modelAndView = new ModelAndView("/open/microapp/detail");
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        String platformType = DicPlatformType.OPEN;
        MicroappViewModel microappModel = microappService.queryView(id,platformType);
        modelAndView.addObject("model", microappModel);
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        modelAndView.addObject("imageContextPath", imageContextPath);
        List<ResourceAuth> list =null;
        if(loginUser!=null) {
            list =  microappService.isAPPly(loginUser.getId(),microappModel.getPublishSettingId());

        }
        modelAndView.addObject("list",list);
        return modelAndView;
    }


    @RequestMapping(value = "apply.action")
    @ResponseBody
    @RequiresAuthentication
    public ResultState doApply(HttpSession session,MicroappApplyModel inputModel) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setApplier(loginUser.getId());//在申请人
        inputModel.setPlatformType(DicPlatformType.OPEN);
        //判断是否已经申请过
        Long resourceAuthId= myDataService.getResourceAuthId(inputModel.getPublishSettingId(),loginUser.getId(), DicPlatformType.OPEN);
        if(resourceAuthId !=null){
            ResultState resultState = new ResultState();
            resultState.setMsg("已经申请过了，请前往用户中心下载");
            return resultState;
        }
        return microappService.doApply(inputModel);
    }



    /**
     *查看演示
     * resource_microapp表id
     * @param id
     * @return
     */
//    @RequestMapping(value = "openDemo.action/{id}")
    @RequestMapping(value = "openDemo.action/{id}/{flag}", produces = "text/html; charset=UTF-8")
    @RequiresAuthentication
    @ResponseBody
    public String openDemo(@PathVariable long id,@PathVariable int flag) {
        ResourceMicroappWithBLOBs outputModel=microappService.demo(id);
        String html ="";
        if(flag==1) {
             html = HttpTookitUtils.doGet(outputModel.getUrl(),null,  CharEncoding.UTF8);
        }else {
             html = HttpTookitUtils.doGet(outputModel.getDemoUrl(),null,  CharEncoding.UTF8);
        }

//        String html = HttpTookitUtils.doGet("http://127.0.0.1:8080/hsdatashowapi/app/cockpit/jmxfzs.htm",null,  CharEncoding.UTF8);
//        String str="";
//        try {
//             str = new String(html.getBytes("utf-8"),"iso8859-1");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        return html;
    }





    /**
     *关注
     * setting表id
     * @param session
     * @param id
     * @return
     */
    @RequestMapping(value = "follow.action/{id}")
    @ResponseBody
    @RequiresAuthentication
    public ResultState follow(HttpSession session,@PathVariable long id) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResourceFollow model = new ResourceFollow();
        model.setFollowerId(loginUser.getId());//关注人id
        model.setPublishSettingId(id);//资源发布id
        model.setPlatformType(DicPlatformType.OPEN);
        ResultState   resultState = microappService.follow(model);
        return resultState;
    }
    /**
     *取消关注
     * 关注表id
     * @param
     * @param id
     * @return
     */
    @RequestMapping(value = "delfollow.action/{id}")
    @ResponseBody
    @RequiresAuthentication
    public ResultState delfollow(@PathVariable long id) {
        ResultState   resultState = microappService.delfollow(id);
        return resultState;
    }
    @RequestMapping(value = "offline.htm/{id}")
    public ModelAndView offline(@PathVariable long id) {
        ModelAndView modelAndView = new ModelAndView("/open/microapp/offline");
        modelAndView.addObject("publishSettingId",id );
        return modelAndView;
    }

    @RequestMapping(value = "offlineConference.action")
    @ResponseBody
    @RequiresAuthentication
    public ResultState offlineConference(HttpSession session, @Valid MicroappOfflineConferenceModel inputModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        return microappService.offlineConference(inputModel,loginUser.getId());
    }





}
