package com.yeejoin.amos.patrol.business.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
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 org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.patrol.business.dto.DangerExecuteSubmitDto;
import com.yeejoin.amos.patrol.business.param.LatentDangerExcuteParam;
import com.yeejoin.amos.patrol.business.param.LatentDangerListParam;
import com.yeejoin.amos.patrol.business.param.LatentDangerNormalParam;
import com.yeejoin.amos.patrol.business.param.LatentDangerPatrolParam;
import com.yeejoin.amos.patrol.business.param.PageParam;
import com.yeejoin.amos.patrol.business.service.intfc.ILatentDangerService;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.business.util.FileHelper;
import com.yeejoin.amos.patrol.business.vo.DangerTimeAxisVo;
import com.yeejoin.amos.patrol.common.enums.DictTypeEnum;
import com.yeejoin.amos.patrol.core.common.response.DangerListResponse;

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

@RestController
@RequestMapping(value = "/api/latent/danger")
@Api(tags = "隐患接口api")
public class LatentDangerController extends AbstractBaseController {

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

    @Autowired
    private ILatentDangerService iLatentDangerService;

    @ApiOperation(value = "创建无码无计划隐患", notes = "创建无码无计划隐患")
    @PostMapping(value = "/normal/save")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse saveNormal(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerNormalParam latentDangerParam) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            String dangerLevelStr = String.valueOf(latentDangerParam.getDangerLevel());
            if (iLatentDangerService.getDangerLevelJsonObject(dangerLevelStr, getToken(), getProduct(), getAppKey(), DictTypeEnum.DANGERLEVEL.getCode()) == null) {
                return CommonResponseUtil.failure("隐患等级有误");
            }

            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            String deptId = getDepartmentId(reginParams);
            String companyId = getCompanyId(reginParams);
            String departmentName = getDepartmentName(reginParams);
            RoleBo role = reginParams.getRole();
            return iLatentDangerService.saveNormal(latentDangerParam, user.getUserId(),
                    user.getRealName(), deptId, departmentName, companyId, loginOrgCode, role);
        } catch (Exception e) {
            logger.error("创建普通隐患异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    @ApiOperation(value = "创建巡检隐患", notes = "创建巡检隐患")
    @PostMapping(value = "/patrol/save")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse savePatrol(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerPatrolParam latentDangerPatrolParam) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            String deptId = getDepartmentId(reginParams);
            String companyId = getCompanyId(reginParams);
            String departmentName = getDepartmentName(reginParams);
            RoleBo role = reginParams.getRole();
            return iLatentDangerService.savePatrol(latentDangerPatrolParam, user.getUserId(),
                    user.getRealName(), deptId, departmentName, companyId, loginOrgCode, role);
        } catch (Exception e) {
            logger.error("创建巡检隐患异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    @ApiOperation(value = "隐患列表", notes = "隐患列表")
    @PostMapping(value = "/list")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse list(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerListParam latentDangerListParam) {
        Date startDate = new Date();
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            String deptId = null;
            return iLatentDangerService.list(getToken(), getProduct(), getAppKey(), latentDangerListParam, user, loginOrgCode, deptId);
        } catch (Exception e) {
            logger.error("隐患列表异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }finally {
            Date endDate = new Date();
            logger.info("-------------------------隐患列表时间" +(endDate.getTime()-startDate.getTime()));
        }
    }

    @ApiOperation(value = "隐患详情", notes = "隐患详情")
    @GetMapping(value = "/detail")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse detail(@ApiParam(value = "任务Id", required = true) @RequestParam String id,
                                 @ApiParam(value = "是否完成", required = true) @RequestParam boolean isFinish) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            return iLatentDangerService.detail(id, user.getUserId(),isFinish);
        } catch (Exception e) {
            logger.error("隐患详情异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    @ApiOperation(value = "隐患执行记录", notes = "隐患执行记录")
    @GetMapping(value = "/listFlowRecord")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse listFlowRecord(@ApiParam(value = "隐患编号", required = true) @RequestParam Long id) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            return iLatentDangerService.listFlowRecord(getToken(), getProduct(), getAppKey(), id);
        } catch (Exception e) {
            logger.error("隐患执行记录异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    @ApiOperation(value = "流程执行", notes = "流程执行")
    @PostMapping(value = "/excute")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse excute(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerExcuteParam latentDangerExcuteParam) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            ReginParams reginParams = getSelectedOrgInfo();
            String deptId = getDepartmentId(reginParams);
            String departmentName = getDepartmentName(reginParams);
            String userRealName = user.getRealName();
            String userId = user.getUserId();
            RoleBo role = reginParams.getRole();
            DangerExecuteSubmitDto executeSubmitDto = iLatentDangerService.execute(latentDangerExcuteParam, userId,
                    userRealName, deptId, departmentName, role);
//            iLatentDangerService.freshRiskJudgmentLangerCount(latentDangerExcuteParam);//更新统计
            if (executeSubmitDto.getIsOk()) {
                if (!StringUtils.isEmpty(executeSubmitDto.getPointOriginalId())) {
                    iLatentDangerService.sendLatentDangerExcuteResult(executeSubmitDto);
                }
                return CommonResponseUtil.success();
            } else {
                return CommonResponseUtil.failure(executeSubmitDto.getMsg());
            }
        } catch (Exception e) {
            logger.error("流程执行异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    @ApiOperation(value = "根据流程实例编号获取隐患信息", notes = "根据流程实例编号获取隐患信息")
    @GetMapping(value = "/getByInstanceId")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse getByInstanceId(@ApiParam(value = "流程实例编号", required = true) @RequestParam String instanceId) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            return iLatentDangerService.getByInstanceId(instanceId);
        } catch (Exception e) {
            logger.error("根据流程实例编号获取隐患信息异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    @ApiOperation(value = "隐患按错计划流程执行回调", notes = "隐患按错计划流程执行回调")
    @PostMapping(value = "/plan/flow/excuteCallBack")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse excuteCallBack(@ApiParam(value = "隐患按错计划流程执行回调对象") @RequestBody JSONObject json) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("用户session过期");
            }
            String instanceId = json.getString("instanceId");
            Integer actionType = json.getInteger("actionType");
            String remark = json.getString("remark");
            ReginParams reginParams = getSelectedOrgInfo();
            String deptId = getDepartmentId(reginParams);
            String departmentName = getDepartmentName(reginParams);
            DangerExecuteSubmitDto executeSubmitDto = iLatentDangerService.excuteCallBack(instanceId, actionType, remark,
                    getToken(), user.getUserId(), user.getRealName(), deptId, departmentName);
            if (executeSubmitDto.getIsOk()) {
                if (!StringUtils.isEmpty(executeSubmitDto.getPointOriginalId())) {
                    iLatentDangerService.sendLatentDangerExcuteResult(executeSubmitDto);
                }
                return CommonResponseUtil.success();
            } else {
                return CommonResponseUtil.failure(executeSubmitDto.getMsg());
            }
        } catch (Exception e) {
            logger.error("隐患按错计划流程执行回调异常", e.getMessage());
            return CommonResponseUtil.failure("系统繁忙，请稍后再试");
        }
    }

    @ApiOperation(value = "获取隐患等级", notes = "获取隐患等级")
    @GetMapping(value = "/dangerLevel")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse getDangerLevel() {
        return CommonResponseUtil.success(iLatentDangerService.getDangerLevel(getToken(), getProduct(), getAppKey(), DictTypeEnum.DANGERLEVEL.getCode()));
    }

    @ApiOperation(value = "获取隐患评审信息", notes = "获取隐患评审信息")
    @GetMapping(value = "/review/info")
    public CommonResponse getDangerReviewInfo(@ApiParam(value = "隐患id", required = true) @RequestParam Long dangerId) {
        return CommonResponseUtil.success(iLatentDangerService.getReviewInfo(dangerId));
    }

    /**
     * 隐患清单
     */
    @ApiOperation(value = "隐患清单", notes = "隐患清单")
    @PostMapping(value = "/page/list")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse listDanger(@ApiParam(value = "查询条件", required = true) @RequestBody PageParam pageParam) {
        AgencyUserModel user = getUserInfo();
        if (ObjectUtils.isEmpty(user)) {
            return CommonResponseUtil.failure("用户session过期");
        }
        Page<DangerListResponse> result = iLatentDangerService.listDanger(pageParam);
        return CommonResponseUtil.success(result);
    }

    /**
     * 导出隐患清单
     */
    @ApiOperation(value = "导出隐患清单", notes = "导出隐患清单")
    @PostMapping(value = "/export")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public void exportDangerList(@ApiParam(value = "查询条件") @RequestBody PageParam pageParam,
                                 HttpServletResponse response) {
        AgencyUserModel user = getUserInfo();
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户session过期");
        }
        pageParam.setPageSize(Integer.MAX_VALUE);
        List<DangerListResponse> list = iLatentDangerService.export(pageParam);
        String fileName = "隐患清单" + new Date().getTime();
        FileHelper.exportExcel(list, "隐患清单", "隐患清单", DangerListResponse.class, fileName + ".xls", response);
    }

    /**
      * <pre>
      * @Description: 查询隐患日志
      * </pre>
      *
      * @MethodName:
      * @Param: [userId, date]
      * @Return: CommonResponse
      * @Throws
      * @Author keyong
      * @Date 2021/3/11 11:42
      */
    @ApiOperation(value = "隐患日志", notes = "查询隐患节点信息")
    @GetMapping(value = "/listDangerTimeAxis")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse listTimeAxis(@ApiParam(value = "时间") @RequestParam(required = false) Integer dateTime) {
        AgencyUserModel user = getUserInfo();
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户session过期");
        }
        try {
            List<DangerTimeAxisVo> result = iLatentDangerService.queryExecuteLog(dateTime);
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            return CommonResponseUtil.failure(e.getMessage());
        }
    }
}
