package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.common.GuidGenerator;
import com.lightinit.hsdataplatform.common.PermissionUtilsPro;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;
import com.lightinit.hsdataplatform.dictionary.DicDataApiAndServiceState;
import com.lightinit.hsdataplatform.dictionary.DicResourceOpenType;
import com.lightinit.hsdataplatform.dictionary.DicResourceShareType;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IDataSupplyApiService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
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 javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.List;

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

@Controller
@RequestMapping("/admin/data_supply_api")
public class DataSupplyApiController {

    @Autowired
    private IDataSupplyApiService iDataSupplyApiService;
    @Autowired
    private PermissionUtilsPro permissionUtilsPro;

    @RequestMapping(value = "index.htm")
    public ModelAndView requirement_api(){
        ModelAndView modelAndView=new ModelAndView("admin/data_api/index");
        modelAndView.addObject("dicDataApiAndServiceState", DicDataApiAndServiceState.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping("list.action")
    public ModelAndView list(DataSupplyApiInputModel inputModel, @RequestParam(defaultValue = "1")Integer pageNo){
        ModelAndView modelAndView=new ModelAndView("admin/data_api/list");
        BaseExample.Page pager =new BaseExample.Page();
        pager.setPageNo(pageNo);
        List<Requirement> outputModel=iDataSupplyApiService.QueryRequirementList(inputModel,pager);
        pager.setTotal(iDataSupplyApiService.QueryRequirementListCount(inputModel));
        modelAndView.addObject("list",outputModel);
        modelAndView.addObject("pager",pager);
        return modelAndView;
    }
    @RequestMapping(value = "info/{id}")
    public ModelAndView info(@PathVariable long id){
        ModelAndView modelAndView=new ModelAndView("admin/data_api/info");
        DataSupplyApiInfoModel dataSupplyApiInfoModel=new DataSupplyApiInfoModel();
        Requirement requirement= iDataSupplyApiService.QueryRequirement(id);
        dataSupplyApiInfoModel.setRqm(requirement);
        RequirementApi requirementApi= iDataSupplyApiService.QueryRequirementApi(id);
        dataSupplyApiInfoModel.setApiinfo(requirementApi);
        ResourceCatelog resourceCatelog= iDataSupplyApiService.QueryCateType(requirementApi.getCategoryId());
        dataSupplyApiInfoModel.setCatelog(resourceCatelog);
        dataSupplyApiInfoModel.setAdmin(iDataSupplyApiService.QueryAdmin(requirement.getAuditedBy()==null?0:requirement.getAuditedBy()));
        modelAndView.addObject("info",dataSupplyApiInfoModel);
        return modelAndView;
    }
    @RequestMapping(value = "unshelve/{id}")
    public ModelAndView unshelve(@PathVariable long id){
        ModelAndView modelAndView=new ModelAndView("admin/data_api/unshelve");
        modelAndView.addObject("id",id);
        return modelAndView;
    }
    @RequestMapping(value="unshelveresult/{status}")
    public ModelAndView unshelveresult(@PathVariable String status){
        ModelAndView modelAndView=new ModelAndView("admin/data_api/unshelve_result");
        modelAndView.addObject("status",status);
        return modelAndView;
    }
    @RequestMapping(value = "unshelve.action")
    @ResponseBody
    public ResultState unshelveaction(RequirementUnShelveModel unShelveModel){
        ResultState<Long> resultState=new ResultState<Long>();
        if (unShelveModel==null){
            resultState.setStateCode(ResultStateCode.DATA_ITEM_NOT_EXIST);
            resultState.setMsg("数据不存在");
            return resultState;
        }
        if ( unShelveModel.getId()<=0   ){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据非法");
            return resultState;
        }
        Requirement requirement=iDataSupplyApiService.QueryRequirement(unShelveModel.getId());
        Admin admin=iDataSupplyApiService.QueryAdminByUserName(permissionUtilsPro.CurrentName());
        requirement.setAuditedBy(admin.getId());
        requirement.setAuditedAt(new Date());
        requirement.setAuditOpinion(unShelveModel.getUnshelvereasons());//下架原因（审核意见）
        requirement.setRqrmntState("已下架");
        if(iDataSupplyApiService.UpDateRequirement(requirement)>0){
            resultState.setStateCode(ResultStateCode.SUCCESS);
            resultState.setMsg("执行下架成功");
        }else{
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("执行下架失败");
        }
        return resultState;
    }

    @RequiresAuthentication
    @RequestMapping(value = "audit/{id}")
    public ModelAndView aduit(@PathVariable long id,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ModelAndView modelAndView=new ModelAndView("admin/data_api/aduit");
        DataSupplyApiInfoModel dataSupplyApiInfoModel=new DataSupplyApiInfoModel();
        Requirement requirement= iDataSupplyApiService.QueryRequirement(id);
        dataSupplyApiInfoModel.setRqm(requirement);
        RequirementApi requirementApi= iDataSupplyApiService.QueryRequirementApi(id);
        dataSupplyApiInfoModel.setApiinfo(requirementApi);
        ResourceCatelog resourceCatelog= iDataSupplyApiService.QueryCateType(requirementApi.getCategoryId());
        dataSupplyApiInfoModel.setCatelog(resourceCatelog);
        modelAndView.addObject("admin",loginUser.getUsername());
        modelAndView.addObject("auditedAt",new Date());
        modelAndView.addObject("info",dataSupplyApiInfoModel);
        return modelAndView;
    }
    @RequiresAuthentication
    @RequestMapping(value = "audit.action")
    @ResponseBody
    public ResultState auditinfo(RequirementAuditModel requirementAuditModel,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        Requirement requirement=iDataSupplyApiService.QueryRequirement(requirementAuditModel.getId());
        ResultState<Long> resultState=new ResultState<Long>();
        if(requirement==null){
            resultState.setStateCode(ResultStateCode.DATA_ITEM_NOT_EXIST);
            resultState.setMsg("数据不存在");
            return resultState;
        }
        if(requirementAuditModel.getId()<0){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("非法数据");
            return resultState;
        }
        if(requirementAuditModel.getAuditStatus()==1){
            requirement.setRqrmntState("进行中");
            requirement.setAuditResult("审核通过");
        }else if(requirementAuditModel.getAuditStatus()==2){
            requirement.setRqrmntState("审核不通过");
            requirement.setAuditResult("审核不通过");
        }
        requirement.setAuditOpinion(requirementAuditModel.getAuditOpinion());
        requirement.setAuditedAt(new Date());
        requirement.setPublishAt(new Date());
        //Admin admin=iDataSupplyApiService.QueryAdminByUserName(permissionUtilsPro.CurrentName());
        requirement.setAuditedBy(loginUser.getId());
        if(iDataSupplyApiService.UpDateRequirement(requirement)>0){
            resultState.setStateCode(ResultStateCode.SUCCESS);
            resultState.setMsg("审核完成！");
        }else{
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("审核失败！");
        }
        return resultState;
    }

    @RequestMapping(value = "publishApiAdd.htm")
    public ModelAndView publishApiAdd(){
        ModelAndView modelAndView=new ModelAndView("admin/data_api/publishApiAdd");
        return modelAndView;
    }

    @RequestMapping(value = "release.action")
    @ResponseBody
    public ResultState release(@Valid APIDdmandOpenReleaseModel  releaseModel, BindingResult bindingResult, HttpSession session,MultipartFile attachment){
        if(bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(releaseModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        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 (attachment != null && !attachment.isEmpty()){
            if (UploadFileUtils.writeUploadFile(attachment, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                releaseModel.setAttachmentAdd(dataFileDir + attachment.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "附件保存失败");
            }
        }
        return iDataSupplyApiService.release(releaseModel,loginUser.getId());
    }


}
