package com.lightinit.hsdataplatform.controller.admin;

import com.google.gson.Gson;
import com.lightinit.hsdataplatform.common.*;
import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.mapper.AdminRoleMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.ICommonService;
import com.lightinit.hsdataplatform.service.admin.IResourceMicroappRegisterService;
import com.qcloud.Utilities.Json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * 微应用注册
 */
@Controller
@RequestMapping(value="/admin/microapp_register")
public class ResourceMicroappRegisterController extends BaseController{
    @Autowired
    private IResourceMicroappRegisterService resourceMicroappRegisterService;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @RequestMapping(value="index.htm")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/index");
        modelAndView.addObject("dicResourceState", DicResourceMicroappState.getInstacne().getDicMap());
    return modelAndView;
    }

    @RequestMapping(value = "list.action")
    public ModelAndView list(HttpSession session,ResourceMicroappRegisterSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo) {
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/list");
        BaseExample.Page pager = new BaseExample.Page(pageNo, 10);
        inputModel.setPage(pager);
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        int isFlag = adminRoleMapper.isAdminFalg(loginUser.getId()) ;
        if (!(isFlag>0)){
            inputModel.setOrgId(loginUser.getOrgId());
        }
        List<ResourceMicroappRegisterListModel> outputModel = resourceMicroappRegisterService.queryList(inputModel);
        pager.setTotal(resourceMicroappRegisterService.queryCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    @RequestMapping(value = "add.htm")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/add");
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        ResourceMicroappRegisterController aa = new ResourceMicroappRegisterController();

        /*String message=HttpUtil.httpGet("http://121.17.30.198:8097/microservice-gateway/msgs-server/v1/imageTags",null,null);
        Map<String,Object> map = new HashMap<String, Object>();
        map = HttpUtil.strToMap(message);*/
        //取得开发商地址
//        Map<String,Object> developes = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.DEVELOPERS,null,null)) ;
        //取得镜像地址
//        Map<String,Object> imagetags = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.IMAGETAGS,null,null)) ;
        //取得分类地址
//        Map<String,Object> appkinds = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.APPKINDS,null,null)) ;
//        modelAndView.addObject("developes",developes) ;
//        modelAndView.addObject("appkinds",appkinds) ;
//        modelAndView.addObject("ImageTags", imagetags);
        return modelAndView;
    }

    @RequestMapping(value = "add.action")
    @ResponseBody
    public ResultState doAdd( HttpSession session, @Valid ResourceDataMicroappDataModel inputModel, BindingResult bindingResult,MultipartFile imgFile){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }

        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.MICROAPP_REGISTER_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.MICROAPP_REGISTER_SCREENSHOT_DIR);
        if (imgFile != null && !imgFile.isEmpty()){
            if (UploadFileUtils.writeUploadFile(imgFile, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setScreenshot(dataFileDir + imgFile.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "页面截图保存失败");
            }
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setCreatedBy(loginUser.getId());


        ResultState<Long> resultState = resourceMicroappRegisterService.add(inputModel,loginUser.getUsername());
        return resultState;
    }


    public static void main(String[] args) throws Exception{
      String ss =   TokenUntils.getToken();
       /* ResourceMicroappRegisterController aa = new ResourceMicroappRegisterController();
        System.out.print(aa.getImageTags());*/
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");
        HashMap<String, String> json = new HashMap<>();
        json.put("summary","yyh");
        String s = HttpUtil.httpPost("http://121.17.30.198:8097/microservice-gateway/msgs-server/v1/nmspApp", headers, json);
        System.out.println(s);
    }


    @RequestMapping(value = "delete.action/{id}")
    @ResponseBody
    public ResultState delete(@PathVariable long id){
        ResultState<Long> resultState = resourceMicroappRegisterService.delete(id);
        return resultState;
    }

    @RequestMapping(value = "edit.htm/{id}")
    @ResponseBody
    public ModelAndView edit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/edit");
        ResourceDataMicroappDataModel busiModel= (ResourceDataMicroappDataModel) resourceMicroappRegisterService.queryOne(id);
        modelAndView.addObject("busiModel",busiModel );
        modelAndView.addObject("screenshot", StringUtils.isNotEmpty(busiModel.getScreenshot()) ? UploadFileUtils.getFileNameByPath(busiModel.getScreenshot()) : null);
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "update.action")
    @ResponseBody
    public ResultState doEdit(HttpSession session, @Valid ResourceDataMicroappDataModel inputModel,BindingResult bindingResult,MultipartFile imgFile){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        // 保存文件
        String uniqueDir;
        if (StringUtils.isNotEmpty(inputModel.getScreenshot())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, inputModel.getScreenshot(), 2);
        }else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.MICROAPP_REGISTER_ROOT_DIR, uniqueDir,  SysContants.UploadFilePath.MICROAPP_REGISTER_SCREENSHOT_DIR);
        if (imgFile != null && !imgFile.isEmpty()){
            if (UploadFileUtils.writeUploadFile(imgFile, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setScreenshot(dataFileDir + imgFile.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setCreatedBy(loginUser.getId());
        ResultState resultState = resourceMicroappRegisterService.edit(inputModel);
        return resultState;
    }

    @RequestMapping(value = "toDetail.htm/{id}")
    public ModelAndView toDetail(@PathVariable long id,Long catelogType,Long catelogSector,Long catelogTheme,Long catelogCustom){
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/detail");
        ResourceDataMicroappDataModel busiModel= (ResourceDataMicroappDataModel) resourceMicroappRegisterService.detail(id);
        modelAndView.addObject("microapp", resourceMicroappRegisterService.selectDic(id));
        modelAndView.addObject("busiModel",busiModel );
        modelAndView.addObject("screenshot", StringUtils.isNotEmpty(busiModel.getScreenshot()) ? UploadFileUtils.getFileNameByPath(busiModel.getScreenshot()) : null);
        return modelAndView;
    }

    @RequestMapping(value = "aduit.htm/{id}")
    @ResponseBody
    public ModelAndView aduit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/aduit");
        modelAndView.addObject("busiModel", resourceMicroappRegisterService.detail(id));
        modelAndView.addObject("microapp", resourceMicroappRegisterService.selectDic(id));
        return modelAndView;
    }

    @RequestMapping(value = "doAduit.action")
    @ResponseBody
    public ResultState doAduit(HttpSession session ,ResourceDataMicroappDataModel inputModel ){
        LoginUser loginUser = (LoginUser)session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);

        if(inputModel.getAuditStatus()==1) {
            inputModel.setResourceState(DicResourceMicroappState.APPROVED);//通过
            inputModel.setAuditResult(DicResourceMicroappAuditResult.APPROVED);//已审核


        }
        if(inputModel.getAuditStatus()==2) {
            inputModel.setResourceState(DicResourceMicroappState.REJECTED);//未通过
            inputModel.setAuditResult(DicResourceMicroappAuditResult.PENDING);//已审核
        }
        inputModel.setAuditedBy(loginUser.getId());
        inputModel.setAuditedAt(new Date());
        return  resourceMicroappRegisterService.edit(inputModel);
    }
//    @RequestMapping(value = "doSubmit.action")
//    @ResponseBody
//    public ResultState submit(HttpSession session, ResourceDataMicroappDataModel inputModel){
//        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
//        inputModel.setCreatedBy(loginUser.getId());
//        ResultState<Long> resultState =null;
//        Object obj =  resourceMicroappRegisterService.queryOne(inputModel.getId());
//        if(obj!=null){
//            inputModel.setResourceState(DicResourceMicroappState.PENDING);
//            resultState = resourceMicroappRegisterService.edit(inputModel);
//        }else {
//            resultState =resourceMicroappRegisterService.submit(inputModel);
//        }
//        return resultState;
//    }




    //=================================================================================
    @RequestMapping(value = "shoreAdd.htm")
    public ModelAndView shoreAdd()throws Exception {
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/shoreAdd");
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        String access_toke = TokenUntils.getToken() ;
        //取得开发商地址
        Map<String,Object> developes = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.DEVELOPERS,null,null)) ;
        //取得镜像地址
        Map<String,Object> imagetags = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.IMAGETAGS,null,null)) ;
        //取得分类地址
        Map<String,Object> appkinds = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.APPKINDS,null,null)) ;
        modelAndView.addObject("developes",developes) ;
        modelAndView.addObject("imagetags",imagetags) ;
        modelAndView.addObject("appkinds",appkinds) ;
        return modelAndView;
    }


    @RequestMapping(value = "shoreAdd.action")
    @ResponseBody
    public ResultState shoreAdd( HttpSession session, @Valid ResourceDataMicroappDataModel inputModel, BindingResult bindingResult,MultipartFile imgFile){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }

        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.MICROAPP_REGISTER_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.MICROAPP_REGISTER_SCREENSHOT_DIR);
        if (imgFile != null && !imgFile.isEmpty()){
            if (UploadFileUtils.writeUploadFile(imgFile, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setScreenshot(dataFileDir + imgFile.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "页面截图保存失败");
            }
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setCreatedBy(loginUser.getId());


        ResultState<Long> resultState = resourceMicroappRegisterService.shoreAdd(inputModel,loginUser.getUsername());
        return resultState;
    }



    @RequestMapping(value = "auditService.htm/{id}")
    @ResponseBody
    public ModelAndView auditService(@PathVariable long id) throws Exception {
        ModelAndView modelAndView = new ModelAndView("admin/microapp_register/addService");
        modelAndView.addObject("busiModel", resourceMicroappRegisterService.detail(id));
        modelAndView.addObject("microapp", resourceMicroappRegisterService.selectDic(id));
        //获取租户
        Map<String,Object> lessList = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.TENANT,null,null)) ;
        modelAndView.addObject("lessList",lessList) ;
        return modelAndView;
    }

    @RequestMapping(value = "AddService.action")
    @ResponseBody
    public ResultState AddService(HttpSession session ,ResourceDataMicroappDataModel inputModel ){
        LoginUser loginUser = (LoginUser)session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);

        if(inputModel.getAuditStatus()==1) {
            inputModel.setResourceState(DicResourceMicroappState.APPROVED);//通过
            inputModel.setAuditResult(DicResourceMicroappAuditResult.APPROVED);//已审核
        }
        if(inputModel.getAuditStatus()==2) {
            inputModel.setResourceState(DicResourceMicroappState.REJECTED);//未通过
            inputModel.setAuditResult(DicResourceMicroappAuditResult.PENDING);//已审核
        }
        inputModel.setAuditedBy(loginUser.getId());
        inputModel.setAuditedAt(new Date());
        return  resourceMicroappRegisterService.AddService(inputModel);
    }
}
