package com.yeejoin.amos.patrol.business.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.patrol.business.param.SynInputItemParam;
import com.yeejoin.amos.patrol.business.param.SynPlanParam;
import com.yeejoin.amos.patrol.business.param.SynPointParam;
import com.yeejoin.amos.patrol.business.param.SynRouteParam;
import com.yeejoin.amos.patrol.business.service.intfc.ISynDataService;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.business.util.Toke;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


@RestController
@RequestMapping(value = "/api/syn")
@Api(tags = "巡检同步接口api")
public class SynDataController extends AbstractBaseController {

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

    private static final String saveOperationType = "save";

    private static final String updateOperationType = "update";

    private static final String deleteOperationType = "delete";

    @Autowired
    private ISynDataService iSynDataService;

    /**
     * 同步巡检项
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "同步巡检项", notes = "同步巡检项")
    @PostMapping(value = "/inputItem/{operationType}")
    public CommonResponse inputItem(@ApiParam(value = "操作类型（save/update/delete）", required = true) @PathVariable String operationType,
                                    @ApiParam(value = "巡检项信息", required = true) @RequestBody SynInputItemParam synInputItemParam) {
        try {
        	ReginParams reginParams = getSelectedOrgInfo();
            String orgCode = getOrgCode(reginParams);
            String userId = getUserId();
            if (ObjectUtils.isEmpty(reginParams)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            if (operationType.equals(saveOperationType)) {
                return iSynDataService.saveInputItem(synInputItemParam,userId, orgCode);
            }
            if (operationType.equals(updateOperationType)) {
                return iSynDataService.updateInputItem(synInputItemParam);
            }
            if (operationType.equals(deleteOperationType)) {
                return iSynDataService.deleteInputItem(synInputItemParam);
            }
            return CommonResponseUtil.failure("操作类型有误");
        } catch (Exception e) {
            logger.error("同步巡检项异常", e);
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    /**
     * 同步巡检点
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "同步巡检点", notes = "同步巡检点")
    @PostMapping(value = "/point/{operationType}")
    public CommonResponse point(@ApiParam(value = "操作类型（save/update/delete）", required = true) @PathVariable String operationType,
                                @ApiParam(value = "巡检点信息", required = true) @RequestBody SynPointParam synPointParam) {
        try {
            if (operationType.equals(saveOperationType)) {
            	ReginParams reginParams = getSelectedOrgInfo();
                String orgCode = getOrgCode(reginParams);
                String userId = getUserId();
                if (ObjectUtils.isEmpty(reginParams)) {
                    return CommonResponseUtil.failure("用户session过期");
                }
                return iSynDataService.saveSinglePoint(synPointParam, userId, orgCode);
            }
            if (operationType.equals(updateOperationType)) {
                return iSynDataService.updateSinglePoint(synPointParam);
            }
            if (operationType.equals(deleteOperationType)) {
                return iSynDataService.deleteSinglePoint(synPointParam);
            }
            return CommonResponseUtil.failure("操作类型有误");
        } catch (Exception e) {
            logger.error("同步巡检点异常", e);
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    /**
     * 同步巡检点和巡检项关系
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "同步巡检点和巡检项关系", notes = "同步巡检点和巡检项关系")
    @PostMapping(value = "/pointItem/relation/{operationType}")
    public CommonResponse relation(@ApiParam(value = "操作类型（save/update/delete）", required = true) @PathVariable String operationType,
                                   @ApiParam(value = "巡检点信息", required = true) @RequestBody SynPointParam synPointParam) {
        try {
           /* User user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }*/
        	 String userId = getUserId();
            if (operationType.equals(saveOperationType)) {
                return iSynDataService.synPointItemRelation(synPointParam, true, userId);
            }
            if (operationType.equals(updateOperationType)) {
                return iSynDataService.synPointItemRelation(synPointParam, false, userId);
            }
            return CommonResponseUtil.failure("操作类型有误");
        } catch (Exception e) {
            logger.error("同步巡检点和巡检项关系异常", e);
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    /**
     * 同步巡检路线
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "同步巡检路线", notes = "同步巡检路线")
    @PostMapping(value = "/route/{operationType}")
    public CommonResponse route(@ApiParam(value = "操作类型（save/update/delete）", required = true) @PathVariable String operationType,
                                @ApiParam(value = "巡检路线信息") @RequestBody SynRouteParam synRouteParam) {
        try {
        	 ReginParams reginParams = getSelectedOrgInfo();
             String orgCode = getOrgCode(reginParams);
             String userId = getUserId();
            if (ObjectUtils.isEmpty(reginParams)) {
                return CommonResponseUtil.failure("用户session过期");
            }
           // String orgCode = getLoginUserParam().getOrgCode();
            if (operationType.equals(saveOperationType)) {
                return iSynDataService.saveRoute(synRouteParam, userId, orgCode);
            }
            if (operationType.equals(updateOperationType)) {
                return iSynDataService.updateRoute(synRouteParam, userId, orgCode);
            }
            return CommonResponseUtil.failure("操作类型有误");
        } catch (Exception e) {
            logger.error("同步巡检路线异常", e);
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    /**
     * 同步巡检计划
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "同步巡检计划", notes = "同步巡检计划")
    @PostMapping(value = "/plan/{operationType}")
    public CommonResponse plan(@ApiParam(value = "操作类型（save/update/delete）", required = true) @PathVariable String operationType,
                               @ApiParam(value = "巡检计划信息") @RequestBody SynPlanParam synPlanParam) {
        try {
        	 ReginParams reginParams = getSelectedOrgInfo();
             String orgCode = getOrgCode(reginParams);
             String userId = getUserId();
            Toke toke = new Toke();
            toke.setAppKey(getAppKey());
            toke.setProduct(getProduct());
            toke.setToke(getToken());
            if (ObjectUtils.isEmpty(reginParams)) {
                return CommonResponseUtil.failure("用户session过期");
            }
           // String orgCode = getLoginUserParam().getOrgCode();
            if (operationType.equals(saveOperationType)) {
                return iSynDataService.savePlan(synPlanParam, userId, orgCode,toke);
            }
            if (operationType.equals(updateOperationType)) {
                return iSynDataService.updatePlan(synPlanParam, userId, orgCode);
            }
            return CommonResponseUtil.failure("操作类型有误");
        } catch (Exception e) {
            logger.error("同步巡检计划异常", e);
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    /**
     * 停用巡检计划
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "停用巡检计划", notes = "停用巡检计划")
    @PostMapping(value = "/stopPlan")
    public CommonResponse stopPlan(@ApiParam(value = "巡检计划信息", required = true) @RequestParam String originalId) {
        try {
       	 ReginParams reginParams = getSelectedOrgInfo();
            if (ObjectUtils.isEmpty(reginParams)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            iSynDataService.stopPlan(originalId);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            logger.error("停用巡检计划异常", e);
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    /**
     * 获取巡检计划已完成次数
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取巡检计划已完成次数", notes = "获取巡检计划已完成次数")
    @GetMapping(value = "/plan/getFinishTimes")
    public CommonResponse getPlanFinishTimes(@ApiParam(value = "巡检计划原始编号（多个逗号隔开）", required = true) @RequestParam String originalIds) {
        try {
        	 ReginParams reginParams = getSelectedOrgInfo();
            if (ObjectUtils.isEmpty(reginParams)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            return iSynDataService.getPlanFinishTimes(originalIds);
        } catch (Exception e) {
            logger.error("获取巡检计划已完成次数异常", e);
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }
}
