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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.latentdanger.business.dto.DangerExecuteSubmitDto;
import com.yeejoin.amos.latentdanger.business.dto.ExecuteSubmitDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerDto;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerExecuteParam;
import com.yeejoin.amos.latentdanger.business.param.LatentDangerListParam;
import com.yeejoin.amos.latentdanger.business.param.PageParam;
import com.yeejoin.amos.latentdanger.business.service.intfc.ILatentDangerService;
import com.yeejoin.amos.latentdanger.business.util.CommonResponse;
import com.yeejoin.amos.latentdanger.business.util.CommonResponseUtil;
import com.yeejoin.amos.latentdanger.business.util.FileHelper;
import com.yeejoin.amos.latentdanger.business.vo.DangerTimeAxisVo;
import com.yeejoin.amos.latentdanger.business.vo.LatentDangerDetailVo;
import com.yeejoin.amos.latentdanger.core.common.response.DangerListResponse;
import com.yeejoin.amos.latentdanger.dao.entity.LatentDanger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
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 org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

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

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

    @Autowired
    private ILatentDangerService iLatentDangerService;

    @Value("${danger.biz.type}")
    private static final String bizType = "patrol";

    @ApiOperation(value = "创建无码无计划隐患", notes = "创建无码无计划隐患")
    @PostMapping(value = "/normal/save")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public CommonResponse saveNormal(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerDto latentDangerParam) {
        try {
            AgencyUserModel user = getUserInfo();

            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 ResponseModel<List<LatentDanger>> savePatrol(@ApiParam(value = "隐患对象", required = true) @RequestBody List<LatentDangerDto> latentDangerDtoList) throws Exception {
        AgencyUserModel user = getUserInfo();
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String deptId = getDepartmentId(reginParams);
        String companyId = getCompanyId(reginParams);
        String departmentName = getDepartmentName(reginParams);
        RoleBo role = reginParams.getRole();
        return ResponseHelper.buildResponse(iLatentDangerService.savePatrol(latentDangerDtoList, user.getUserId(),
                user.getRealName(), deptId, departmentName, companyId, loginOrgCode, role));
    }

    @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("登录过期，请重新登录");
            }
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            return iLatentDangerService.list(getToken(), getProduct(), getAppKey(), latentDangerListParam, user,
                    loginOrgCode, null);
        } 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 ResponseModel<LatentDangerDetailVo> detail(@ApiParam(value = "隐患Id", required = true) @RequestParam Long dangerId,
                                                      @ApiParam(value = "是否完成") @RequestParam(required = false) boolean isFinish) throws Exception {
        AgencyUserModel user = getUserInfo();
        return iLatentDangerService.detail(dangerId, user.getUserId(), isFinish);
    }

    @ApiOperation(value = "隐患执行记录", notes = "隐患执行记录")
    @GetMapping(value = "/listFlowRecord")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel listFlowRecord(@ApiParam(value = "隐患id", required = true) @RequestParam Long id) throws Exception {
            return ResponseHelper.buildResponse(iLatentDangerService.listFlowRecord(getToken(), getProduct(),
                    getAppKey(), id));
    }

    @ApiOperation(value = "流程执行", notes = "流程执行")
    @PostMapping(value = "/excute")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel execute(@ApiParam(value = "隐患对象", required = true) @RequestBody LatentDangerExecuteParam latentDangerExecuteParam) throws Exception {
            AgencyUserModel user = getUserInfo();
            ReginParams reginParams = getSelectedOrgInfo();
            String deptId = getDepartmentId(reginParams);
            String departmentName = getDepartmentName(reginParams);
            String userRealName = user.getRealName();
            String userId = user.getUserId();
            DangerExecuteSubmitDto executeSubmitDto = iLatentDangerService.execute(latentDangerExecuteParam, userId,
                    userRealName, deptId, departmentName, reginParams);
            if (!executeSubmitDto.getIsOk()) {
                throw new Exception(executeSubmitDto.getMsg());
            }
//            iLatentDangerService.freshRiskJudgmentLangerCount(latentDangerExecuteParam);//更新统计
            // 执行通过，发送执行结果消息
//            if (executeSubmitDto.getIsOk()) {
//                if (!StringUtils.isEmpty(executeSubmitDto.getPointOriginalId())) {
//                    iLatentDangerService.sendLatentDangerExecuteResult(executeSubmitDto);
//                }
//                return CommonResponseUtil.success();
//            } else {
//                return CommonResponseUtil.failure(executeSubmitDto.getMsg());
//            }
            return ResponseHelper.buildResponse("success");
    }

    @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("登录过期，请重新登录");
            }
            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 executeCallBack(@ApiParam(value = "隐患按错计划流程执行回调对象") @RequestBody JSONObject json) {
        try {
            AgencyUserModel user = getUserInfo();
            if (ObjectUtils.isEmpty(user)) {
                return CommonResponseUtil.failure("登录过期，请重新登录");
            }
            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.executeCallBack(instanceId, actionType, remark,
                    getToken(), user.getUserId(), user.getRealName(), deptId, departmentName);
            if (executeSubmitDto.getIsOk()) {
                if (!StringUtils.isEmpty(executeSubmitDto.getPointOriginalId())) {
                    iLatentDangerService.sendLatentDangerExecuteResult(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 ResponseModel getDangerLevel() {
        return ResponseHelper.buildResponse((iLatentDangerService.getDangerLevel()));
    }

    @ApiOperation(value = "获取隐患整改方式", notes = "获取隐患整改方式")
    @GetMapping(value = "/dangerGovernance")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getDangerGovernance() {
        return ResponseHelper.buildResponse((iLatentDangerService.getDangerGovernance()));
    }

    @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 ResponseModel listDanger(@ApiParam(value = "查询条件", required = true) @RequestBody PageParam pageParam) throws Exception {
        IPage<LatentDanger> result = iLatentDangerService.pageListDanger(pageParam);
        return ResponseHelper.buildResponse(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("登录过期，请重新登录");
        }
        pageParam.setSize(Integer.MAX_VALUE);
        List<DangerListResponse> list = iLatentDangerService.export(pageParam);
        String fileName = "隐患清单" + System.currentTimeMillis();
        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("登录过期，请重新登录");
        }
        try {
            List<DangerTimeAxisVo> result = iLatentDangerService.queryExecuteLog(dateTime);
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    @ApiOperation(value = "所有隐患列表", notes = "所有隐患列表")
    @PostMapping(value = "/list/all")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel<List<LatentDanger>> listAllDanger(@RequestBody LatentDangerListParam searchParam) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        searchParam.setOrgCode(loginOrgCode);
        return ResponseHelper.buildResponse(iLatentDangerService.listAllDanger(searchParam));
    }

    @ApiOperation(value = "隐患删除", notes = "隐患删除")
    @DeleteMapping(value = "/delete")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel<Boolean> delete(@RequestParam String ids) throws Exception {
        return ResponseHelper.buildResponse(iLatentDangerService.delete(ids));
    }

    @ApiOperation(value = "隐患状态列表", notes = "隐患状态列表")
    @GetMapping(value = "/state")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getDangerState() {
        return ResponseHelper.buildResponse(iLatentDangerService.getDangerState());
    }

    @ApiOperation(value = "隐患审核/复审", notes = "隐患审核/复审")
    @PostMapping(value = "/supervision/audit")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel dangerAudit(@RequestBody LatentDangerDto latentDangerDto, @RequestParam Integer executeType) throws Exception {
        AgencyUserModel user = getUserInfo();
        ReginParams reginParams = getSelectedOrgInfo();
        String deptId = getDepartmentId(reginParams);
        String departmentName = getDepartmentName(reginParams);
        String userRealName = user.getRealName();
        String userId = user.getUserId();
        ExecuteSubmitDto executeSubmitDto = iLatentDangerService.dangerAudit(latentDangerDto, executeType, userId,
                userRealName, deptId, departmentName, reginParams);
        if (!executeSubmitDto.getIsOk()) {
            throw new Exception(executeSubmitDto.getMsg());
        }
        return ResponseHelper.buildResponse(executeSubmitDto);
    }

    /**
     * 隐患审核分页列表
     */
    @ApiOperation(value = "隐患审核分页列表", notes = "隐患审核分页列表")
    @PostMapping(value = "/supervision/page/reviewList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel reviewListDanger(@ApiParam(value = "查询条件", required = true) @RequestBody PageParam pageParam) throws Exception {
        IPage<LatentDanger> result = iLatentDangerService.reviewListDanger(pageParam);
        return ResponseHelper.buildResponse(result);
    }

    @ApiOperation(value = "获取所有隐患等级", notes = "获取所有隐患等级")
    @GetMapping(value = "/all/dangerLevel")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getAllDangerLevel() {
        return ResponseHelper.buildResponse((iLatentDangerService.getAllDangerLevel()));
    }

    @ApiOperation(value = "获取所有隐患整改方式", notes = "获取所有隐患整改方式")
    @GetMapping(value = "/all/dangerGovernance")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getAllDangerGovernance() {
        return ResponseHelper.buildResponse((iLatentDangerService.getAllDangerGovernance()));
    }

    @ApiOperation(value = "获取所有隐患治理进度", notes = "获取所有隐患治理进度")
    @GetMapping(value = "/all/dangerState")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getAllDangerState() {
        return ResponseHelper.buildResponse((iLatentDangerService.getAllDangerState()));
    }

    @ApiOperation(value = "所有未完成隐患数量", notes = "所有未完成隐患数量")
    @GetMapping(value = "/app/unFinished")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getUnFinishedDangerCount() {
        return ResponseHelper.buildResponse((iLatentDangerService.getUnFinishedDangerCount()));
    }

    @ApiOperation(value = "获取隐患复查信息", notes = "获取隐患复查信息")
    @GetMapping(value = "/supervision/reviewInfo")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getSupervisionReviewInfo(@RequestParam String orgCode, @RequestParam String t1,
                                                   @RequestParam String t2) {
        return ResponseHelper.buildResponse(iLatentDangerService.getSupervisionReviewInfo(orgCode,
                DateUtils.longStr2Date(t1), DateUtils.longStr2Date(t2)));
    }
}
