package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.common.GuidGenerator;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;
import com.lightinit.hsdataplatform.dictionary.DicPublishApiState;
import com.lightinit.hsdataplatform.dictionary.DicResourceOpenType;
import com.lightinit.hsdataplatform.dictionary.DicResourceShareType;
import com.lightinit.hsdataplatform.dictionary.DicResourceState;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.entity.PublishInfoWithBLOBs;
import com.lightinit.hsdataplatform.entity.ResourceApiInterfaceWithBLOBs;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IApiPublishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
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 java.io.File;
import java.util.List;

import static com.lightinit.hsdataplatform.controller.admin.BaseController.buildInvalidResultState;

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

    @Autowired
    private IApiPublishService apiPublishService ;

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

    @RequestMapping(value = "list.action")
    public ModelAndView list(APIPublishSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo,
                             HttpSession session) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ModelAndView modelAndView = new ModelAndView("admin/api_publish/list");
        BaseExample.Page pager = new BaseExample.Page(pageNo, 10);
        inputModel.setPage(pager);
        int isFlag = apiPublishService.isAdminFalg(loginUser.getId()) ;
        if (!(isFlag>0)){
            inputModel.setOrgId(loginUser.getOrgId());
        }
        List<APIPublishListModel> outputModel = apiPublishService.queryList(inputModel);
        pager.setTotal(apiPublishService.queryCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        modelAndView.addObject("dicPublishApiState_DRAFT", DicPublishApiState.DRAFT) ;
        modelAndView.addObject("dicPublishApiState_PUBLISH", DicPublishApiState.PUBLISH) ;
        modelAndView.addObject("dicPublishApiState_UN_PUBLISH", DicPublishApiState.UN_PUBLISH) ;
        modelAndView.addObject("dicPublishApiState_UNPASS", DicPublishApiState.UNPASS) ;
        return modelAndView;
    }

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

    @RequestMapping(value = "publish_list.action")
    public ModelAndView publish_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/api_publish/publish_list");
        BaseExample.Page pager = new BaseExample.Page(pageNo, 10);
        inputModel.setPage(pager);
        int isFlag = apiPublishService.isAdminFalg(loginUser.getId()) ;
        if (!(isFlag>0)){
            inputModel.setOrgId(loginUser.getOrgId());
        }
        List<ResourceAPIRegisterListModel> outputModel = apiPublishService.queryPublishList(inputModel);
        pager.setTotal(apiPublishService.queryPublishCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

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

    @RequestMapping(value = "apiPublish_setting.htm")
    public ModelAndView apiPublic_setting(Long api_badge){
        ModelAndView modelAndView = new ModelAndView("admin/api_publish/apiPublish_setting");
        return modelAndView;
    }

    @RequestMapping(value = "edit_setting.htm")
    public ModelAndView edit_setting(APIPublishSettingModel apiPublishSettingModel){
        ModelAndView modelAndView = new ModelAndView("admin/api_publish/apiPublish_setting");
        modelAndView.addObject("publishSetting",apiPublishSettingModel) ;
        return modelAndView;
    }

    @RequestMapping(value = "publishAPI_add.action")
    @ResponseBody
    public ResultState publishAPI_add(
             APIPublishInfoAndSettingModel apiPublishInfoAndSettingModel, String shareType, String openType) {
        // 保存图片
        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.API_PUBLISH_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.API_PUBLISH_RESOURCE_IMG_DIR);
        if (apiPublishInfoAndSettingModel.getFileImg() != null && !apiPublishInfoAndSettingModel.getFileImg().isEmpty()){
            if (UploadFileUtils.writeUploadFile(apiPublishInfoAndSettingModel.getFileImg(), dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                apiPublishInfoAndSettingModel.setResourceImg(dataFileDir + apiPublishInfoAndSettingModel.getFileImg().getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "资源图片保存失败");
            }
        }
        if (shareType.equals(DicResourceShareType.CONDITIONAL)){
            if (StringUtils.isEmpty(apiPublishInfoAndSettingModel.getShareCondition())){
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "共享条件有条件共享时必须填写");
            }
        }
        if (openType.equals(DicResourceOpenType.NEED_TO_APPLY)){
            if (StringUtils.isEmpty(apiPublishInfoAndSettingModel.getOpenCondition())){
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "开放类型为依申开放时必须填写");
            }
        }
        ResultState<Long> resultState = apiPublishService.publishAPI_add(apiPublishInfoAndSettingModel) ;
        return resultState ;
    }

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

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

    @RequestMapping(value = "editPublish.htm/{id}/{publishInfoId}")
    public ModelAndView editPublish(@PathVariable("id") long id,@PathVariable("publishInfoId") long publishInfoId){
        ModelAndView modelAndView = new ModelAndView("admin/api_publish/editPublish");
        modelAndView.addObject("resource", apiPublishService.queryOneViewResource(id)) ;
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceWithBLOBsList = apiPublishService.queryOneResourceAPIInterface(id) ;
        modelAndView.addObject("resourceApiInterface", resourceApiInterfaceWithBLOBsList) ;
        PublishInfoWithBLOBs publishInfoWithBLOBs = apiPublishService.queryOnePublishInfoById(publishInfoId) ;
        if (publishInfoWithBLOBs!=null){
            modelAndView.addObject("resourceImgName", org.apache.commons.lang.StringUtils.isNotEmpty(publishInfoWithBLOBs.getResourceImg()) ? UploadFileUtils.getFileNameByPath(publishInfoWithBLOBs.getResourceImg()) : null);
        }
        modelAndView.addObject("publishInfo",publishInfoWithBLOBs ) ;
        modelAndView.addObject("publishSettingList", apiPublishService.queryListPublishSettingByInfoId(publishInfoId)) ;
        return modelAndView;
    }

    @RequestMapping(value = "publishInfoView.htm/{id}/{publishInfoId}")
    public ModelAndView publishInfoView(@PathVariable("id") long id,@PathVariable("publishInfoId") long publishInfoId){
        ModelAndView modelAndView = new ModelAndView("admin/api_publish/publishInfo_view");
        modelAndView.addObject("resource", apiPublishService.queryOneViewResource(id)) ;
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceWithBLOBsList = apiPublishService.queryOneResourceAPIInterface(id) ;
        modelAndView.addObject("resourceApiInterface", resourceApiInterfaceWithBLOBsList) ;
        modelAndView.addObject("publishInfo", apiPublishService.queryOnePublishInfoById(publishInfoId)) ;
        modelAndView.addObject("publishSettingList", apiPublishService.queryListPublishSettingByInfoId(publishInfoId)) ;
        return modelAndView;
    }

    @RequestMapping(value = "publishSettingView.htm/{id}")
    public ModelAndView publishSettingView(@PathVariable("id") long id){
        ModelAndView modelAndView = new ModelAndView("admin/api_publish/publishSettingView");
        modelAndView.addObject("publishSetting", apiPublishService.queryOnePublishSettingById(id)) ;
        return modelAndView;
    }

    @RequestMapping(value = "editPublishSetting.htm/{id}")
    public ModelAndView editPublishSetting(@PathVariable("id") long id){
        ModelAndView modelAndView = new ModelAndView("admin/api_publish/editPublishSetting");
        modelAndView.addObject("publishSetting", apiPublishService.queryOnePublishSettingById(id)) ;
        return modelAndView;
    }

    @RequestMapping(value = "publishAPI_edit.action")
    @ResponseBody
    public ResultState publishAPI_edit(APIPublishInfoAndSettingEditModel infoAndSettingEditModel, String shareType, String openType,MultipartFile fileImg) {
        // 保存图片
        String uniqueDir ;
        if (org.apache.commons.lang.StringUtils.isNotEmpty(infoAndSettingEditModel.getImgFile())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, infoAndSettingEditModel.getImgFile(), 2);
        } else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.API_PUBLISH_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.API_PUBLISH_RESOURCE_IMG_DIR);
        if (fileImg != null && !fileImg.isEmpty()){
            if (UploadFileUtils.writeUploadFile(fileImg, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                infoAndSettingEditModel.setResourceImg(dataFileDir + fileImg.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "资源图片保存失败");
            }
        }
        if (shareType.equals(DicResourceShareType.CONDITIONAL)){
            if (StringUtils.isEmpty(infoAndSettingEditModel.getShareCondition())){
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "共享条件有条件共享时必须填写");
            }
        }
        if (openType.equals(DicResourceOpenType.NEED_TO_APPLY)){
            if (StringUtils.isEmpty(infoAndSettingEditModel.getOpenCondition())){
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "开放类型为依申开放时必须填写");
            }
        }
        ResultState<Long> resultState = apiPublishService.publishAPI_edit(infoAndSettingEditModel) ;
        return resultState ;
    }
}
