package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.common.GuidGenerator;
import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;
import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.*;
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.IResourceAPIRegisterService;
import com.lightinit.hsdataplatform.service.admin.IResourceMicroappPublishService;
import com.lightinit.hsdataplatform.service.admin.IResourceMicroappRegisterService;
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.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微应用发布
 */
@Controller
@RequestMapping(value="/admin/microapp_publish")
public class ResourceMicroappPublishController extends  BaseController{
    @Autowired
    private IResourceMicroappPublishService resourceMicroappPublishService;
    @Autowired
    private IResourceMicroappRegisterService resourceMicroappRegisterService;
    @Autowired
    private AdminRoleMapper adminRoleMapper;


    /**
     * 跳转发布列表
     * @return
     */
    @RequestMapping(value="index.htm")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("/admin/microapp_publish/index");
        modelAndView.addObject("dicResourceState", DicResourceMicroappPublishState.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_publish/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 = resourceMicroappPublishService.querypublishList(inputModel);
        pager.setTotal(resourceMicroappPublishService.querypublishCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }


    /**
     * 跳转选择发布列表
     * @return
     */
    @RequestMapping(value="publish_index.htm")
    public ModelAndView publishIndex() {
        ModelAndView modelAndView = new ModelAndView("/admin/microapp_publish/publish_index");
        //modelAndView.addObject("dicResourceState", DicResourceMicroappPublishState.getInstacne().getDicMap());
        return modelAndView;
    }

    /**
     * 选择发布列表
     * @param inputModel
     * @param pageNo
     * @return
     */
    @RequestMapping(value="publishList.action")
    public ModelAndView publishList(HttpSession session,ResourceMicroappRegisterSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo) {
        ModelAndView modelAndView = new ModelAndView("/admin/microapp_publish/publishList");
        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 = resourceMicroappPublishService.queryList(inputModel);
        pager.setTotal(resourceMicroappPublishService.queryCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    @RequestMapping(value = "delete.action/{id}")
    @ResponseBody
    public ResultState delete(@PathVariable long id){
        ResultState<Long> resultState = resourceMicroappPublishService.delete(id);
        return resultState;
    }
    @RequestMapping(value="edit.htm/{id}")
    @ResponseBody
    public ModelAndView edit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("/admin/microapp_publish/edit");
        modelAndView.addObject("chargeMethod", DicPublishSettingChargeMethod.getInstacne().getDicMap());
        ResourceMicroappWithBLOBs microapp =resourceMicroappPublishService.selectMicroappId(id);
        modelAndView.addObject("microapp",microapp );
        modelAndView.addObject("screenshot", StringUtils.isNotEmpty(microapp.getScreenshot()) ? UploadFileUtils.getFileNameByPath(microapp.getScreenshot()) : null);
        modelAndView.addObject("resource", resourceMicroappPublishService.selectResourceId(id));

        PublishInfoWithBLOBs publishInfo = resourceMicroappPublishService.selectByResourceId(id);
        modelAndView.addObject("publishInfo",publishInfo );
        modelAndView.addObject("img", StringUtils.isNotEmpty(publishInfo.getResourceImg()) ? UploadFileUtils.getFileNameByPath(publishInfo.getResourceImg()) : null);
        modelAndView.addObject("publishSettingList",  resourceMicroappPublishService.selectByPublishInfoId(publishInfo.getId()));

        modelAndView.addObject("dic", resourceMicroappRegisterService.selectDic(id));
        return modelAndView;
    }

    @RequestMapping(value = "doAdit.action")
    @ResponseBody
    public ResultState doAdit( ResourceMicroappPublishDataModel inputModel,BindingResult bindingResult, MultipartFile imgResource){
        // 保存文件
        String uniqueDir;
        if (StringUtils.isNotEmpty(inputModel.getResourceImg())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, inputModel.getResourceImg(), 2);
        }else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.MICROAPP_PUBLISH_ROOT_DIR, uniqueDir,  SysContants.UploadFilePath.MICROAPP_PUBLISH_RESOURCE_IMG_DIR);
        if (imgResource != null && !imgResource.isEmpty()){
            if (UploadFileUtils.writeUploadFile(imgResource, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setResourceImg(dataFileDir + imgResource.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }
        ResultState<Long> resultState = resourceMicroappPublishService.edit(inputModel);
        return resultState;
    }

    @RequestMapping(value="publish.htm/{id}")
    public ModelAndView publish(@PathVariable long id) {
        ModelAndView modelAndView = new ModelAndView("admin/microapp_publish/publish");
        ResourceMicroappWithBLOBs microapp =resourceMicroappPublishService.selectMicroappId(id);
        modelAndView.addObject("microapp",microapp );
        modelAndView.addObject("screenshot", StringUtils.isNotEmpty(microapp.getScreenshot()) ? UploadFileUtils.getFileNameByPath(microapp.getScreenshot()) : null);
       Resource resource =  (Resource) resourceMicroappPublishService.selectResourceId(id);
        modelAndView.addObject("resource",resource );
        modelAndView.addObject("dic", resourceMicroappRegisterService.selectDic(id));
        modelAndView.addObject("chargeMethod", DicPublishSettingChargeMethod.getInstacne().getDicMap());

        //获取应用版本
//        Map<String,Object> applicationVersion = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.APPLICATIONVERSION,null,null)) ;
//        modelAndView.addObject("applicationVersion",applicationVersion);
        return modelAndView;
    }

    @RequestMapping(value = "doPublish.action")
    @ResponseBody
    public ResultState doPublish(HttpSession session, ResourceMicroappPublishDataModel inputModel, MultipartFile imgResource){
        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.MICROAPP_PUBLISH_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.MICROAPP_PUBLISH_RESOURCE_IMG_DIR);
        //String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.MICROAPP_PUBLISH_ROOT_DIR, uniqueDir,"");
        if (imgResource != null && !imgResource.isEmpty()){
            if (UploadFileUtils.writeUploadFile(imgResource, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setResourceImg(dataFileDir + imgResource.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "页面截图保存失败");
            }
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setCreatedBy(loginUser.getId());
        ResultState<Long> resultState = resourceMicroappPublishService.doPublish(inputModel);
        return resultState;
    }

    /**\
     * 审核页面
     * @return
     */
    @RequestMapping(value="aduitIndex.htm")
    public ModelAndView aduitIndex() {
        ModelAndView modelAndView = new ModelAndView("/admin/microapp_aduit/index");
        modelAndView.addObject("dicResourceState", DicResourceMicroappPublishState.getInstacne().getDicMap());
        return modelAndView;
    }
    /**
     * 审核列表
     */
    @RequestMapping(value="auditList.action")
    public ModelAndView aduitList(HttpSession session,ResourceMicroappRegisterSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo) {
        ModelAndView modelAndView = new ModelAndView("/admin/microapp_aduit/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 = resourceMicroappPublishService.querypublishAduitList(inputModel);
        pager.setTotal(resourceMicroappPublishService.querypublishAduitCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    /**
     * 跳转审核页面
     */
    @RequestMapping(value = "aduit.htm/{id}")
    @ResponseBody
    public ModelAndView aduit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/microapp_aduit/aduit");
        modelAndView.addObject("microapp", resourceMicroappPublishService.selectMicroappId(id));
        modelAndView.addObject("resource", resourceMicroappPublishService.selectResourceId(id));

        PublishInfoWithBLOBs publishInfo = resourceMicroappPublishService.selectByResourceId(id);
        modelAndView.addObject("publishInfo",publishInfo );
        modelAndView.addObject("publishSettingList",  resourceMicroappPublishService.selectByPublishInfoId(publishInfo.getId()));

        modelAndView.addObject("dic", resourceMicroappRegisterService.selectDic(id));
        return modelAndView;
    }

    /**
     * 跳转详情页
     * @param id
     * @return
     */
    @RequestMapping(value = "detail.htm/{id}")
    @ResponseBody
    public ModelAndView detail(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/microapp_publish/detail");
        modelAndView.addObject("chargeMethod", DicPublishSettingChargeMethod.getInstacne().getDicMap());
        ResourceMicroappWithBLOBs microapp =resourceMicroappPublishService.selectMicroappId(id);
        modelAndView.addObject("microapp",microapp );
        modelAndView.addObject("screenshot", StringUtils.isNotEmpty(microapp.getScreenshot()) ? UploadFileUtils.getFileNameByPath(microapp.getScreenshot()) : null);
        modelAndView.addObject("resource", resourceMicroappPublishService.selectResourceId(id));

        PublishInfoWithBLOBs publishInfo = resourceMicroappPublishService.selectByResourceId(id);
        modelAndView.addObject("publishInfo",publishInfo );
        modelAndView.addObject("img", StringUtils.isNotEmpty(publishInfo.getResourceImg()) ? UploadFileUtils.getFileNameByPath(publishInfo.getResourceImg()) : null);
        modelAndView.addObject("publishSettingList",  resourceMicroappPublishService.selectByPublishInfoId(publishInfo.getId()));

        modelAndView.addObject("dic", resourceMicroappRegisterService.selectDic(id));
        return modelAndView;
    }


    @RequestMapping(value = "doAduit.action")
    @ResponseBody
    public ResultState doAduit(HttpSession session , ResourceMicroappPublishDataModel inputModel) {
        LoginUser loginUser = (LoginUser)session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        if(inputModel.getAduitState()==1) {
            inputModel.setPublishState(DicResourceMicroappPublishState.PUBLISH);//已发布
            inputModel.setAuditResult(DicResourceMicroappAuditResult.APPROVED);//审核通过
        }
        if(inputModel.getAduitState()==2) {
            inputModel.setPublishState(DicResourceMicroappState.REJECTED);//审核不通过
            inputModel.setAuditResult(DicResourceMicroappAuditResult.PENDING);//审核不通过
        }
        inputModel.setAuditedBy(loginUser.getId());
        inputModel.setAuditedAt(new Date());
        return  resourceMicroappPublishService.doAduit(inputModel);
    }
    @RequestMapping(value = "downframe.action/{id}")
    @ResponseBody
    public ResultState downframe(HttpSession session, @PathVariable long id) {
        LoginUser loginUser = (LoginUser)session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        PublishInfo publishInfo = resourceMicroappPublishService.selectByResourceId(id);
        publishInfo.setPublishState(DicDataPublishState.OFFLINE);
        return  resourceMicroappPublishService.downframe(publishInfo);

    }

    //======================================================================
    @RequestMapping(value = "shoreAduit.htm/{id}")
    @ResponseBody
    public ModelAndView shoreAduit (@PathVariable long id) throws Exception {
        ModelAndView modelAndView = new ModelAndView("admin/microapp_aduit/shoreAduit");
        modelAndView.addObject("microapp", resourceMicroappPublishService.selectMicroappId(id));
        modelAndView.addObject("resource", resourceMicroappPublishService.selectResourceId(id));

        PublishInfoWithBLOBs publishInfo = resourceMicroappPublishService.selectByResourceId(id);
        modelAndView.addObject("publishInfo",publishInfo );
        modelAndView.addObject("publishSettingList",  resourceMicroappPublishService.selectByPublishInfoId(publishInfo.getId()));

        modelAndView.addObject("dic", resourceMicroappRegisterService.selectDic(id));
        //获取租户
        Map<String,Object> tenants = HttpUtil.strToMap(HttpUtil.httpGet(DicPaasApi.TENANT,null,null)) ;
        modelAndView.addObject("tenant", tenants) ;
        return modelAndView;
    }


    @RequestMapping(value = "shoreAduit.action")
    @ResponseBody
    public ResultState shoreAduit(HttpSession session , ResourceMicroappPublishDataModel inputModel) {
        LoginUser loginUser = (LoginUser)session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        if(inputModel.getAduitState()==1) {
            inputModel.setPublishState(DicResourceMicroappPublishState.PUBLISH);//已发布
            inputModel.setAuditResult(DicResourceMicroappAuditResult.APPROVED);//审核通过
        }
        if(inputModel.getAduitState()==2) {
            inputModel.setPublishState(DicResourceMicroappState.REJECTED);//审核不通过
            inputModel.setAuditResult(DicResourceMicroappAuditResult.PENDING);//审核不通过
        }
        inputModel.setAuditedBy(loginUser.getId());
        inputModel.setAuditedAt(new Date());
        return  resourceMicroappPublishService.shoreAduit(inputModel);
    }
}
