package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.entity.ResourceApiInterfaceInput;
import com.lightinit.hsdataplatform.entity.ResourceApiInterfaceOutput;
import com.lightinit.hsdataplatform.entity.ResourceApiInterfaceWithBLOBs;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IPaasService;
import com.lightinit.hsdataplatform.service.admin.IResourceAPIRegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 资源注册->api注册
 */
@Controller
@RequestMapping("/admin/data_register_api")
public class DataRegisterAPIController extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(DataRegisterAPIController.class);

    @Autowired
    private IResourceAPIRegisterService resourceAPIRegisterService ;

    @Autowired
    private IPaasService paasService ;

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

    @RequestMapping(value = "list.action")
    public ModelAndView list(ResourceAPIRegisterSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo,HttpSession session) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/list");
        int isFlag = resourceAPIRegisterService.isAdminFalg(loginUser.getId()) ;
        if (!(isFlag>0)){
            inputModel.setOrgId(loginUser.getOrgId());
        }
        BaseExample.Page pager = new BaseExample.Page(pageNo, 10);
        inputModel.setPage(pager);
        List<ResourceAPIRegisterListModel> outputModel = resourceAPIRegisterService.queryList(inputModel);
        pager.setTotal(resourceAPIRegisterService.queryCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        modelAndView.addObject("dicResourceState_DRAFT", DicResourceState.DRAFT) ;
        modelAndView.addObject("dicResourceState_PENDING", DicResourceState.PENDING) ;
        modelAndView.addObject("dicResourceState_AUDITED", DicResourceState.APPROVED) ;
        modelAndView.addObject("dicResourceState_UNPASS", DicResourceState.REJECTED) ;
        return modelAndView;
    }

    @RequestMapping(value = "add.htm")
    public ModelAndView add() throws Exception {
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/add");
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        List<APIServiceTypeModel> apiServiceTypeModels = resourceAPIRegisterService.getApiServiceTypes(DicGroupName.FUWUTYPE) ;
        modelAndView.addObject("dicAPIServiceType", apiServiceTypeModels);
        return modelAndView;
    }

    @RequestMapping(value = "apiInterface_add.htm")
    public ModelAndView apiInterface_add(Long api_badge){
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/apiInterface_add");
        modelAndView.addObject("dicAPIInterFaceRequestMethod", DicAPIInterFaceRequestMethod.getInstacne().getDicMap());
        modelAndView.addObject("dicAPIInterFaceReturnFormat", DicAPIInterFaceReturnFormat.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "apiInterface_edit_add.htm")
    public ModelAndView apiInterface_edit_add(Long api_badge){
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/apiInterface_edit_add");
        modelAndView.addObject("dicAPIInterFaceRequestMethod", DicAPIInterFaceRequestMethod.getInstacne().getDicMap());
        modelAndView.addObject("dicAPIInterFaceReturnFormat", DicAPIInterFaceReturnFormat.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "apiInterface_add_finally.action")
    @ResponseBody
    public ResultState apiInterface_add_finally(@Valid ResourceAPIRegisterAddResourceModel addResourceModel, BindingResult bindingResult, HttpSession session){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(addResourceModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResultState<Long> resultState = resourceAPIRegisterService.apiInterface_add_finally(addResourceModel,loginUser.getId(),loginUser.getUsername()) ;
        return resultState ;
    }

    @RequestMapping(value = "edit.htm/{id}")
    public ModelAndView edit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/edit");
        modelAndView.addObject("resourceId",id) ;
        modelAndView.addObject("resource", resourceAPIRegisterService.queryOneResource(id)) ;
        modelAndView.addObject("resourceApi", resourceAPIRegisterService.queryOneResourceAPI(id)) ;
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceWithBLOBsList = resourceAPIRegisterService.queryOneResourceAPIInterface(id) ;
        modelAndView.addObject("resourceApiInterface", resourceApiInterfaceWithBLOBsList) ;
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        List<APIServiceTypeModel> apiServiceTypeModels = resourceAPIRegisterService.getApiServiceTypes(DicGroupName.FUWUTYPE) ;
        modelAndView.addObject("dicAPIServiceType", apiServiceTypeModels);
        return modelAndView;
    }

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

    @RequestMapping(value = "apiInterface_edit_add.action")
    @ResponseBody
    public ResultState apiInterface_edit_add(@Valid ResourceAPIRegisterEditResourceModel editResourceModel,
                                             BindingResult bindingResult,HttpSession session) {
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(editResourceModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResultState<Long> resultState = resourceAPIRegisterService.apiInterface_edit(editResourceModel,loginUser.getId());
        return resultState;
    }

    @RequestMapping(value = "view.htm/{id}")
    public ModelAndView view(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/view");
        modelAndView.addObject("resource", resourceAPIRegisterService.queryOneViewResource(id)) ;
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceWithBLOBsList = resourceAPIRegisterService.queryOneResourceAPIInterface(id) ;
        modelAndView.addObject("resourceApiInterface", resourceApiInterfaceWithBLOBsList) ;
        return modelAndView;
    }

    @RequestMapping(value = "apiInterface_view.htm/{id}")
    public ModelAndView apiInterface_view(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/apiInterface_view");
        modelAndView.addObject("resourceAPIInterface", resourceAPIRegisterService.queryOneViewResourceAPI(id)) ;
        List<ResourceApiInterfaceInput> resourceApiInterfaceInputList = resourceAPIRegisterService.queryOneViewResourceAPIInterfaceInput(id) ;
        modelAndView.addObject("resourceApiInterfaceInputList", resourceApiInterfaceInputList) ;
        List<ResourceApiInterfaceOutput> resourceApiInterfaceOutputList = resourceAPIRegisterService.queryOneViewResourceAPIInterfaceOutput(id) ;
        modelAndView.addObject("resourceApiInterfaceOutputList", resourceApiInterfaceOutputList) ;
        return modelAndView;
    }

    @RequestMapping(value = "audit.htm/{id}")
    public ModelAndView audit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/audit");
        modelAndView.addObject("resource", resourceAPIRegisterService.queryOneViewResource(id)) ;
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceWithBLOBsList = resourceAPIRegisterService.queryOneResourceAPIInterface(id) ;
        modelAndView.addObject("resourceApiInterface", resourceApiInterfaceWithBLOBsList) ;
        return modelAndView;
    }

    @RequestMapping(value = "audit.action")
    @ResponseBody
    public ResultState audit(ResourceAPIRegisterAuditModel resourceAPIRegisterAuditModel){
        ResultState<Long> resultState = resourceAPIRegisterService.audit(resourceAPIRegisterAuditModel) ;
        return resultState ;
    }

    @RequestMapping(value = "apiInterface_validate.action")
    @ResponseBody
    public ResultState apiInterface_validate(@Valid ResourceAPIRegisterAddAPIInterfaceModel addAPIInterfaceModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(addAPIInterfaceModel, bindingResult);
        }
        ResultState<Long> resultState = new ResultState<>() ;
        return resultState ;
    }

//=====================添加到应用商店=========================
@RequestMapping(value = "shoreAdd.htm")
public ModelAndView shoreAdd() throws Exception {
    ModelAndView modelAndView = new ModelAndView("admin/data_register_api/shoreAdd");
    modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
    modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
    List<APIServiceTypeModel> apiServiceTypeModels = resourceAPIRegisterService.getApiServiceTypes(DicGroupName.FUWUTYPE) ;
    //取得开发商地址
    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) ;
    modelAndView.addObject("dicAPIServiceType", apiServiceTypeModels);
    return modelAndView;
}

    @RequestMapping(value = "shoreAddFinally.action")
    @ResponseBody
    public ResultState shoreAddFinally(@Valid PaasShoreModel addResourceModel, BindingResult bindingResult, HttpSession session){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(addResourceModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResultState<Long> resultState = paasService.apiInterface_add_finally(addResourceModel,loginUser.getId(),loginUser.getUsername()) ;
        return resultState ;
    }

    @RequestMapping(value = "auditService.htm/{id}")
    public ModelAndView auditService(@PathVariable long id) throws Exception {
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/auditService");
        modelAndView.addObject("resource", resourceAPIRegisterService.queryOneViewResource(id)) ;
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceWithBLOBsList = resourceAPIRegisterService.queryOneResourceAPIInterface(id) ;
        modelAndView.addObject("resourceApiInterface", resourceApiInterfaceWithBLOBsList) ;
        //获取租户
        Map<String,Object> lessList = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.TENANT,null,null)) ;
        modelAndView.addObject("lessList",lessList) ;
        return modelAndView;
    }

    @RequestMapping(value = "auditAddService.action")
    @ResponseBody
    public ResultState auditAddService(@Valid AuditAddServiceModel auditAddServiceModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(auditAddServiceModel, bindingResult);
        }
        ResultState<Long> resultState = paasService.auditAddService(auditAddServiceModel) ;
        return resultState ;
    }

    //添加第三方服务
    @RequestMapping(value = "addRouteService.htm/{id}")
    public ModelAndView addRouteService(@PathVariable long id) throws Exception {
        ModelAndView modelAndView = new ModelAndView("admin/data_register_api/addRouteService");
        modelAndView.addObject("resource", resourceAPIRegisterService.queryOneViewResource(id)) ;
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceWithBLOBsList = resourceAPIRegisterService.queryOneResourceAPIInterface(id) ;
        modelAndView.addObject("resourceApiInterface", resourceApiInterfaceWithBLOBsList) ;
        //获取租户
        Map<String,Object> tenants = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.TENANT,null,null)) ;
        modelAndView.addObject("tenant", tenants) ;
        return modelAndView;
    }


    @RequestMapping(value = "addRouteService.action")
    @ResponseBody
    public ResultState addRouteServicePost(AddRouteServiceModel inputModel) {
        ResultState<Long> resultState = paasService.addRouteServicePost(inputModel) ;
        return resultState ;
    }
}
