package cn.myapps.runtime.widget.controller;

import cn.myapps.authtime.user.model.UserDefined;
import cn.myapps.authtime.user.service.UserDefinedProcess;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.auth.IUser;
import cn.myapps.common.controller.Resource;
import cn.myapps.common.data.DataPackage;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.model.application.Application;
import cn.myapps.common.model.checkin.CheckinVO;
import cn.myapps.common.model.widget.PageWidget;
import cn.myapps.designtime.application.service.ApplicationDesignTimeService;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.widget.service.PageWidgetDesignTimeService;
import cn.myapps.runtime.checkin.CheckinProcess;
import cn.myapps.runtime.common.controller.AbstractRuntimeController;
import cn.myapps.runtime.common.service.RunTimeServiceManager;
import cn.myapps.runtime.dynaform.document.ejb.WorkVO;
import cn.myapps.runtime.dynaform.work.ejb.WorkProcess;
import cn.myapps.runtime.dynaform.work.ejb.WorkProcessBean;
import cn.myapps.runtime.widget.service.PageWidgetRunTimeService;
import cn.myapps.runtime.workflow.storage.runtime.ejb.Circulator;
import cn.myapps.runtime.workflow.storage.runtime.ejb.CirculatorProcess;
import cn.myapps.runtime.workflow.storage.runtime.ejb.CirculatorProcessBean;
import cn.myapps.runtime.workflow.storage.runtime.intervention.ejb.FlowInterventionVO;
import cn.myapps.util.ProcessFactory;
import cn.myapps.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.PathNotFoundException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by Seven on 2017/11/2.
 */
@Api(tags = "widgets执行模块")
@Component
@RequestMapping(path = "/api/runtime", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class PageWidgetController extends AbstractRuntimeController  {

//    private static final Logger LOG = LoggerFactory.getLogger(PageWidgetController.class);

    @Autowired
    PageWidgetRunTimeService pageWidgetRunTimeService;

    /**
     * 获取指定Widget内容
     * @param widgetId 小工具id
     * @return
     * @throws Exception
     */
    @GetMapping("/widgets/{widgetId}")
    @ApiOperation(value = "获取指定Widget内容", notes = "获取指定Widget内容")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "widgetId",value = "小工具id",required = true,paramType = "path",dataType = "string")
	})
    public Resource doDisplayWidget(@PathVariable String widgetId) throws Exception{
        Object result = pageWidgetRunTimeService.displayWidget(getParams(),widgetId, getUser());
        return success("ok", result);
    }

    /**
     * 获取指定用户首页Widget配置
     * @return
     * @throws Exception
     */
    @GetMapping("/homepage/config")
    @ApiOperation(value = "获取指定用户首页Widget配置", notes = "获取指定用户首页Widget配置")
    public Resource doGetUserPageWidgetSetting() throws Exception{
		boolean isMobile = getParams().getParameterAsBoolean("isMobile");
		JSONObject userPageWidgetSetting = pageWidgetRunTimeService.getUserPageWidgetSetting(getUser(), isMobile);
        return success("ok", userPageWidgetSetting);
    }


	/**
	 * 获取手机端(微信)首页配置
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/{applicationId}/homepage/phoneConfig")
	@ApiOperation(value = "获取手机端(微信)首页Widget配置", notes = "获取手机端(微信)首页Widget配置")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "应用id",required = true,paramType = "path",dataType = "string")
	})
	public Resource doGetPhoneConfig(@PathVariable String applicationId) throws Exception {
		ApplicationDesignTimeService applicationService = DesignTimeServiceManager.applicationDesignTimeService();
		Application application = applicationService.findById(applicationId);
		//获取软件widget系统设置
		String systemWidgetSettingString = application.getSystemWidgetSetting();

        JSONObject systemWidgetSetting = new JSONObject();
		if(StringUtils.isNotEmpty(systemWidgetSettingString)) {
		    //若不为空则解析获取结果
            systemWidgetSetting = JSONObject.parseObject(systemWidgetSettingString);
        }else {
            //若为空则返回默认结果
		    systemWidgetSetting.put("Banner",true);
            systemWidgetSetting.put("menuIcon",true);
            systemWidgetSetting.put("system_workflow",true);
        }

		return success("ok",systemWidgetSetting);
	}


    /**
     * 保存用户首页Widget配置
     * @param content 请求包体
     * @return
     * @throws Exception
     */
    @PostMapping("/homepage/config")
    @ApiOperation(value = "保存用户首页Widget配置", notes = "保存用户首页Widget配置")
    @ApiImplicitParams({
		@ApiImplicitParam(name = "content",value = "请求包体",required = true,paramType = "body",dataType = "string")
	})
    public Resource doSaveUserPageWidgetSetting(@RequestBody(required=false) String content) throws Exception{

        String templateElement = null;
        try {
			if(StringUtil.isBlank(content)){
				templateElement = "";
			} else {
				JSONObject templateJSON = JSONObject.parseObject(content);
				templateElement = templateJSON.toJSONString();

				ApplicationDesignTimeService appService = DesignTimeServiceManager.applicationDesignTimeService();
				Collection<Application> apps = appService.getListByWebUser(getUser());
				//获取widget
				PageWidgetDesignTimeService process = DesignTimeServiceManager.pageWidgetDesignTimeService();
				for (Application application : apps) {
					Collection<PageWidget> pageWidgets = process.doQueryWidgetsByApplicationId(application.getId());
					for(PageWidget pageWidget : pageWidgets){
						if(pageWidget.isPublished() && !pageWidget.isSetup()){
							pageWidget.setSetup(true);
							process.update(pageWidget);
						}
					}
				}
			}
        } catch (Exception e) {
            e.printStackTrace();
            throw new PathNotFoundException();
        }

        IUser user = getUser();
        UserDefinedProcess process = (UserDefinedProcess) ProcessFactory.createProcess(UserDefinedProcess.class);
        UserDefined vo =  process.doFindMyCustomUserDefined(user);
        if (vo != null) {
            vo.setTemplateElement(templateElement);
            process.doUpdate(vo);
        } else {
            UserDefined po = new UserDefined();
            po.setCreator(user.getName());
            po.setUserId(user.getId());
            po.setTemplateElement(templateElement);
            process.doCreate(po);
        }
        return success("ok", null);
    }
    
	/**
	 * 前台widget显示-我的待办(包含多个软件)
	 * @param pageNo 现在的页数
	 * @param linesPerPage 每页的条数
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/widget/myPending")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "前台widget显示-我的待办(包含多个软件)", notes = "前台widget显示-我的待办(包含多个软件)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageNo",value = "现在的页数",required = false,paramType = "query",dataType = "string",defaultValue="1"),
		@ApiImplicitParam(name = "linesPerPage",value = "每页的条数",required = false,paramType = "query",dataType = "string",defaultValue="5")
	})
	public Resource queryPendingByUser(@RequestParam(required=false,defaultValue="1") int pageNo,@RequestParam(required=false,defaultValue="5") int linesPerPage) throws Exception{
		//得到用户
		WebUser user=getUser();
		List<String> applicationIds = user.getApplicationIds();
		DataPackage<WorkVO> workDataPage= new DataPackage<WorkVO>();
		List<WorkVO> listWork = new ArrayList<WorkVO>();
		int allSum=0;
		boolean isFlowAgent=true;
		if(applicationIds != null){
			for (String applicationId : applicationIds) {
				WorkProcess wp = new WorkProcessBean(applicationId);
				DataPackage<WorkVO> tmp_works = wp.getPendingList("", "", "", isFlowAgent, applicationId, user.getDomainid(),"", pageNo, linesPerPage, user);
                listWork.addAll(tmp_works.getDatas());
                //添加该用户软件下的待办数量
                allSum+=tmp_works.getRowCount();
			}
		}
		if(allSum!=0){
			//为包赋值
			workDataPage.setRowCount(allSum);
			workDataPage.setLinesPerPage(linesPerPage);
			workDataPage.setPageNo(pageNo);
			
			//分页后的数据
			int beginIndex=(pageNo-1)*linesPerPage;
			int endIndex=pageNo*linesPerPage;
			//如果开始标志大于listWork的数量
			if(beginIndex>=listWork.size()){
				workDataPage.setDatas(null);
				workDataPage.setRowCount(0);
			}else if(endIndex>=listWork.size()){ //如果结束标志大于等于listWork的数量
				endIndex=listWork.size();
			}
			
			workDataPage.setDatas(listWork.subList(beginIndex, endIndex));
			
		}
	    
		return success("ok",workDataPage);
		
	}
	
	
	/**
	 * 前台widget显示-我的经办(包含多个软件)
	 * @param pageNo 页数
	 * @param linesPerPage 每页
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/widget/myProcessing")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "前台widget显示-我的经办(包含多个软件)", notes = "前台widget显示-我的经办(包含多个软件)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageNo",value = "现在的页数",required = false,paramType = "query",dataType = "int",defaultValue="1"),
		@ApiImplicitParam(name = "linesPerPage",value = "每页的条数",required = false,paramType = "query",dataType = "int",defaultValue="5")
	})
	public Resource queryProcessingByUser(@RequestParam(required=false,defaultValue="1") int pageNo,@RequestParam(required=false,defaultValue="5") int linesPerPage) throws Exception{
		//得到用户
		WebUser user=getUser();
		
		List<String> applicationIds = user.getApplicationIds();
		DataPackage<WorkVO> workDataPage= new DataPackage<WorkVO>();
		List<WorkVO> listWork = new ArrayList<WorkVO>();
		int allSum=0;
		if(applicationIds != null){
			for (String applicationId : applicationIds) {
				
				WorkProcess wp = new WorkProcessBean(applicationId);
				DataPackage<WorkVO> tmp_works = wp.getProcessedRunningList("", "", "", applicationId,user.getDomainid(), false, FlowInterventionVO.STATUS_PENDING,"", pageNo, linesPerPage,user);
                listWork.addAll(tmp_works.getDatas());
                //添加个软件已办的条数：
                allSum+=tmp_works.getRowCount();
			}
		}
		if(allSum!=0){
			//为包赋值
			workDataPage.setRowCount(allSum);
			workDataPage.setLinesPerPage(linesPerPage);
			workDataPage.setPageNo(pageNo);
			
			//分页后的数据
			int beginIndex=(pageNo-1)*linesPerPage;
			int endIndex=pageNo*linesPerPage;
			//如果开始标志大于listWork的数量
			if(beginIndex>=listWork.size()){
				workDataPage.setDatas(null);
				workDataPage.setRowCount(0);
			}else if(endIndex>=listWork.size()){ //如果结束标志大于等于listWork的数量
				endIndex=listWork.size();
			}
			
			workDataPage.setDatas(listWork.subList(beginIndex, endIndex));
		}
		return success("ok",workDataPage);
	}
	
	/**
	 * 前台widget显示-我的抄办(包含多个软件)
	 * @param pageNo 页数
	 * @param linesPerPage 每页显示的条数
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/widget/myCopy")
	@ApiOperation(value = "前台widget显示-我的抄办(包含多个软件)", notes = "前台widget显示-我的抄办(包含多个软件)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageNo",value = "现在的页数",required = false,paramType = "query",dataType = "int",defaultValue="1"),
		@ApiImplicitParam(name = "linesPerPage",value = "每页的条数",required = false,paramType = "query",dataType = "int",defaultValue="5")
	})
	public Resource listCirculatorByUser(@RequestParam(required=false,defaultValue="1") int pageNo,@RequestParam(required=false,defaultValue="5") int linesPerPage) throws Exception{
		//得到用户
		WebUser user=getUser();
		List<String> applicationIds = user.getApplicationIds();
		DataPackage<Circulator> workDataPage= new DataPackage<Circulator>();
		List<Circulator> listCirculators = new ArrayList<Circulator>();
		long allSum=0;
		ParamsTable params=getParams();
		boolean isRead = params.getParameterAsBoolean("isread");
		if(isRead){
			params.setParameter("_isRead", 1);
		}else {
			params.setParameter("_isRead", 0);
		}
		if(applicationIds != null){
			for (String applicationId : applicationIds) {
				CirculatorProcess cprocess = new CirculatorProcessBean(applicationId);
				DataPackage<Circulator> result = cprocess.getWorksByUser(params, getUser());
				allSum+=cprocess.countByCopy(params, user);
				listCirculators.addAll(result.getDatas());
			}
		}
		if(allSum!=0){
			MyCompartor2 mc=new MyCompartor2();
			Collections.sort(listCirculators,mc);
			//为包赋值
			workDataPage.setRowCount(new Long(allSum).intValue());
			workDataPage.setLinesPerPage(linesPerPage);
			workDataPage.setPageNo(pageNo);
			
			//分页后的数据
			int beginIndex=(pageNo-1)*linesPerPage;
			int endIndex=pageNo*linesPerPage;
			//如果开始标志大于listWork的数量
			if(beginIndex>=listCirculators.size()){
				workDataPage.setDatas(null);
				workDataPage.setRowCount(0);
			}else if(endIndex>=listCirculators.size()){ //如果结束标志大于等于listWork的数量
				endIndex=listCirculators.size();
			}
			
			workDataPage.setDatas(listCirculators.subList(beginIndex, endIndex));
		}
		return success("ok",workDataPage);
	}

	/**
	 * 签到
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/{applicationId}/widgets/{widgetId}/checkin")
	@ApiOperation(value = "签到", notes = "签到")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
            @ApiImplicitParam(name = "widgetId",value = "widetId",required = true,paramType = "path",dataType = "string")
    })
	public Resource createCheckin(@PathVariable String applicationId, @PathVariable String widgetId) throws Exception{
		CheckinProcess service = RunTimeServiceManager.checkinProcess(applicationId);
		WebUser user = getUser();
		CheckinVO checkin = new CheckinVO();
		checkin.setUserId(user.getId());
		checkin.setUserName(user.getName());
		checkin.setCheckinTime(new Date());
		checkin.setDomainid(user.getDomainid());
		checkin.setApplicationid(applicationId);
		checkin.setWidgetId(widgetId);
		service.doCreate(checkin);
		return success("ok", checkin);
	}

	/**
	 * 是否签到
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/{applicationId}/widgets/{widgetId}/checkin")
	@ApiOperation(value = "是否签到", notes = "是否签到")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
            @ApiImplicitParam(name = "widgetId",value = "widetId",required = true,paramType = "path",dataType = "string")
    })
	public Resource isCheckin(@PathVariable String applicationId, @PathVariable String widgetId) throws Exception{
		CheckinProcess service = RunTimeServiceManager.checkinProcess(applicationId);
		boolean result = service.isCheckin(widgetId, getUser().getId());
		return success("ok", result);
	}

	/**
	 * 签到统计
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/{applicationId}/widgets/{widgetId}/checkins")
	@ApiOperation(value = "签到统计", notes = "签到统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
            @ApiImplicitParam(name = "widgetId",value = "widetId",required = true,paramType = "path",dataType = "string"),
            @ApiImplicitParam(name = "countType",value = "统计类型",required = false,paramType = "query",dataType = "string",defaultValue = "none")
    })
	public Resource getCheckins(@PathVariable String applicationId, @PathVariable String widgetId, @RequestParam(required = false, defaultValue = "none") String countType) throws Exception{
		CheckinProcess service = RunTimeServiceManager.checkinProcess(applicationId);
		long result = service.countCheckinByType(widgetId, countType, getUser().getId());
		return success("ok", result);
	}
	
	private class MyCompartor2 implements Comparator{

		@Override
		public int compare(Object o1, Object o2) {
			Circulator c1=(Circulator) o1;
			Circulator c2=(Circulator) o2;
			return c2.getCcTime().compareTo(c1.getCcTime());
		}
	}
}
