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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
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.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.maintenance.business.entity.mybatis.CheckChkExListBo;
import com.yeejoin.amos.maintenance.business.entity.mybatis.CheckDetailBo;
import com.yeejoin.amos.maintenance.business.entity.mybatis.CheckInputBo;
import com.yeejoin.amos.maintenance.business.entity.mybatis.CheckPtListBo;
import com.yeejoin.amos.maintenance.business.entity.mybatis.CheckTraListBo;
import com.yeejoin.amos.maintenance.business.entity.mybatis.CheckUserBo;
import com.yeejoin.amos.maintenance.business.entity.mybatis.PlanRoutePointBo;
import com.yeejoin.amos.maintenance.business.param.CheckInfoListPageParam;
import com.yeejoin.amos.maintenance.business.param.CheckPtListPageParam;
import com.yeejoin.amos.maintenance.business.service.intfc.ICheckService;
import com.yeejoin.amos.maintenance.business.service.intfc.IMeasuresService;
import com.yeejoin.amos.maintenance.business.service.intfc.IPlanTaskService;
import com.yeejoin.amos.maintenance.business.service.intfc.IPointService;
import com.yeejoin.amos.maintenance.business.util.CheckDetailInputPageParam;
import com.yeejoin.amos.maintenance.business.util.CheckPageParamUtil;
import com.yeejoin.amos.maintenance.business.util.CommonResponse;
import com.yeejoin.amos.maintenance.business.util.CommonResponseUtil;
import com.yeejoin.amos.maintenance.common.enums.CheckStatusEnum;
import com.yeejoin.amos.maintenance.common.enums.PointStatusEnum;
import com.yeejoin.amos.maintenance.core.common.request.CommonPageable;
import com.yeejoin.amos.maintenance.core.common.request.CommonRequest;
import com.yeejoin.amos.maintenance.core.common.response.CommonPage;
import com.yeejoin.amos.maintenance.core.common.response.QueryCriteriaRespone;
import com.yeejoin.amos.maintenance.dao.entity.Measure;
import com.yeejoin.amos.maintenance.feign.RemoteSecurityService;

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

@RestController
@RequestMapping(value = "/api/spc")
@Api(tags = "生产安全预控api")
public class SafetyPreCtrlController extends AbstractBaseController {
    @Autowired
    private IPointService pointService;

    @Autowired
    private ICheckService checkService;
    @Autowired
    private IPlanTaskService iPlanTaskService;
    @Autowired
    IMeasuresService measuresService;
    @Autowired
    private RemoteSecurityService remoteSecurityService;

    /*
     * 巡检点统计
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检点统计", notes = "巡检点统计")
    @RequestMapping(value = "/countPoint", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse sumCheckPtById() {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, roleTypeName);
        List<HashMap<String, Object>> List = pointService.getSumPtByRole(paramMap);
        return CommonResponseUtil.success(List);
    }

    /**
     * 月巡检情况统计
     *
     * @param dateMonth
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检情况统计", notes = "巡检情况统计")
    @RequestMapping(value = "/countMonth/{dateMonth}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse countMonthCheckById(@ApiParam(value = "年月日(yyyyMMdd)8位", required = false) @PathVariable String dateMonth) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, roleTypeName);
        List<HashMap<String, Object>> countList = checkService.getCountMonthChkByRole(paramMap, dateMonth);
        return CommonResponseUtil.success(countList);
    }

    /**
     * 巡检执行情况查询
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检执行情况查询", notes = "巡检执行情况查询")
    @RequestMapping(value = "/checkExecute/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse findChkExList(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
                                        @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, roleTypeName);
        CheckPtListPageParam params = CheckPageParamUtil.fillChkExParam(queryRequests, commonPageable, paramMap);
        Page<CheckChkExListBo> checkChkExListBo = iPlanTaskService.getChkExList(getToken(), getProduct(), getAppKey(), params);
        return CommonResponseUtil.success(checkChkExListBo);
    }

    /**
     * 获取巡检点列表查询接口
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取巡检点列表查询接口(<font color='blue'>release</font>)", notes = "获取巡检点列表查询接口")
    @RequestMapping(value = "/point/queryCriteria/init", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse getQueryCriteriaInit() {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        String departmentId = getDepartmentId(reginParams);
        String companyId = getCompanyId(reginParams);
        String dep = reginParams.getCompany().getSequenceNbr().toString();
        QueryCriteriaRespone respone = checkService.getQueryCriteriaInit(getToken(), getProduct(), getAppKey(), loginOrgCode, roleTypeName, departmentId, companyId);
        return CommonResponseUtil.success(respone);
    }

    /**
     * 巡检记录统计
     *
     * @param
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检记录统计", notes = "巡检记录统计")
    @RequestMapping(value = "/check-info/count", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse countCheckInfoDate(@ApiParam(value = "查询条件", required = false) @RequestBody HashMap<String, Object> map) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        HashMap<String, Object> paramsMap = buildMybatisDaoCriterias(loginOrgCode, roleTypeName);
        paramsMap.put("checkMonth", map.get("date").toString().subSequence(0, 6));
        paramsMap.put("pointId", map.get("pointId"));
        List<HashMap<String, String>> checkInfoList = checkService.getCalCountChkInfo(paramsMap);
        return CommonResponseUtil.success(checkInfoList);
    }

    /**
     * 巡检人员查询
     *
     * @param PointID
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据巡检点id查询巡检人员", notes = "根据巡检点id查询巡检人员")
    @RequestMapping(value = "/check-user/{PointID}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse qryCheckUserById(@ApiParam(value = "点编号", required = true) @PathVariable int PointID) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        HashMap<String, Object> paramsMap = buildMybatisDaoCriterias(loginOrgCode, roleTypeName);
        List<CheckUserBo> userList = checkService.getAuthUserInfo(paramsMap);
        return CommonResponseUtil.success(userList);
    }

    /**
     * 巡检记录查询
     *
     * @param
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检记录查询", notes = "巡检记录查询")
    @RequestMapping(value = "/check-info/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse qryCheckInfoPage(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
                                           @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        HashMap<String, Object> paramMap = buildMybatisDaoCriterias(loginOrgCode, roleTypeName);
        CheckInfoListPageParam params = CheckPageParamUtil.fillChkInfoListParam(queryRequests, commonPageable, paramMap);
        Page<Map<String, Object>> checkInfoBoList = checkService.getCheckInfoList1(getToken(), getProduct(), getAppKey(), params);
        return CommonResponseUtil.success(checkInfoBoList);
    }

    /**
     * 根据巡检记录id查询巡检检查项
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据巡检记录id查询巡检检查项", notes = "根据巡检记录id查询巡检检查项")
    @RequestMapping(value = "check-input", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse fetchCheckInputById(@ApiParam(value = "查询参数", required = true) @RequestBody CheckDetailInputPageParam param) {
        CommonPage<CheckInputBo> checkInputBos = null;
        try {
            checkInputBos = checkService.getCheckInputByCheckId(param);
            checkInputBos.setResult("SUCCESS");
        } catch (Exception e) {
            e.printStackTrace();
            if (ObjectUtils.isEmpty(checkInputBos)) {
                checkInputBos = new CommonPage(null, null, 0);
            }
            checkInputBos.setMessage(e.getMessage());
            checkInputBos.setResult("FAILED");
        }
        return CommonResponseUtil.success(checkInputBos);
    }

    /**
     * 根据巡检记录id查询巡检检查项
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据巡检记录id查询巡检点装备(新)", notes = "根据巡检记录id查询巡检点装备(新)")
    @RequestMapping(value = "check-input-new", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse newfetchCheckInputById(@ApiParam(value = "查询参数", required = true) @RequestBody CheckDetailInputPageParam param) {
        List<HashMap<String, Object>> checkInputBos = checkService.getEquipByCheckId(param);
        return CommonResponseUtil.success(checkInputBos);
    }

    /**
     * 根据巡检记录id查询装备检查项
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据巡检记录id查询巡检点装备(新)", notes = "根据巡检记录id查询巡检点装备(新)")
    @RequestMapping(value = "equip-input", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse newfetchEquipInputById(@ApiParam(value = "查询参数", required = true) @RequestBody CheckDetailInputPageParam param) {
        List<HashMap<String, Object>> checkInputBos = checkService.getEquipInputByCheckId(param);
        return CommonResponseUtil.success(checkInputBos);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风险点管控措施", notes = "风险点管控措施")
    @ApiImplicitParam(name = "PointID", value = "风险点ID", dataType = "int", paramType = "path")
    @RequestMapping(value = "/measures/{PointID}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse qryMeasuresByPointID(@PathVariable int PointID) {
        if (ObjectUtils.isEmpty(PointID)) {
            return CommonResponseUtil.failure("pointID不可以为空");
        }
        List<Measure> meausers = measuresService.queryMeasuresByPointID(PointID);
        return CommonResponseUtil.success(meausers);
    }

    /**
     * 巡检点查询
     *
     * @param queryRequests
     * @param commonPageable
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风险点查询", notes = "风险点查询")
    @RequestMapping(value = "/point/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse findPointList(
            @ApiParam(value = "查询条件") @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数") CommonPageable commonPageable) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, null);
        CheckPtListPageParam params = CheckPageParamUtil.fillChkPtParam(queryRequests, commonPageable, paramMap);
        Page<CheckPtListBo> checkPtListBo = pointService.getCheckPtList(getToken(), getProduct(), getAppKey(), params);
        return CommonResponseUtil.success(checkPtListBo);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风险点", notes = "通过ID查询风险点")
    @ApiImplicitParam(name = "PointID", value = "风险点ID", dataType = "int", paramType = "path")
    @RequestMapping(value = "/queryPointById/{PointID}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse qryPointByID(@PathVariable int PointID) {
        CheckPtListBo point = pointService.qryPointByID(PointID);


        //获取点的部门，以及负责人
        if (point != null) {
            if (point.getRealName() != null && !"".equals(point.getRealName())) {
                List<AgencyUserModel> userModels = remoteSecurityService.listUserByUserIds(getToken(), getProduct(), getAppKey(), point.getRealName());
                if (userModels != null && userModels.size() > 0) {
                    String name = "";
                    String mobile = "";

                    for (int i = 0; i < userModels.size(); i++) {
                        if (i == userModels.size() - 1) {
                            name = name + userModels.get(i).getRealName();
                            mobile = userModels.get(i).getMobile();
                        } else {
                            name = name + userModels.get(i).getRealName() + ",";
                            mobile = userModels.get(i).getMobile() + ",";

                        }
                    }

                    point.setRealName(name);
                    point.setMobile(mobile);

                }

            }
            if (point.getGroupName() != null && !"".equals(point.getGroupName())) {
                List<LinkedHashMap> deptList = remoteSecurityService.listDepartmentByDeptIds(getToken(), getProduct(), getAppKey(), point.getGroupName());

                if (deptList != null && deptList.size() > 0) {

                    point.setGroupName(deptList.get(0).get("departmentName").toString());

                }
            }


        }

        return CommonResponseUtil.success(point);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据巡检记录id查询巡检详细信息", notes = "根据巡检记录id查询巡检详细信息")
    @RequestMapping(value = "check-detail", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse fetchCheckDetailById(
            @ApiParam(value = "查询参数", required = true) @RequestBody CheckDetailInputPageParam param) {
        CheckDetailBo checkDetail = checkService.getCheckDetailById(param);
        return CommonResponseUtil.success(checkDetail);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/state", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "获取巡检点状态枚举集合", notes = "获取巡检点状态枚举集合")
    public CommonResponse getCheckState() {
        List<Map<String, Object>> pointStateEnumList = new ArrayList<Map<String, Object>>();
        PointStatusEnum[] pointStateEnums = PointStatusEnum.values();
        for (int i = 0; i < pointStateEnums.length; i++) {
            PointStatusEnum pointStateEnum = pointStateEnums[i];
            Map<String, Object> checkStateEnumMap = new HashMap<>();
            checkStateEnumMap.put("name", pointStateEnum.getName());
            checkStateEnumMap.put("value", pointStateEnum.getCode());
            checkStateEnumMap.put("color", pointStateEnum.getColor());
            pointStateEnumList.add(checkStateEnumMap);
        }
        return CommonResponseUtil.success(pointStateEnumList);
    }


    /**
     * 获取巡检点状态枚举
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/check/state", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "获取巡检点状态枚举集合", notes = "获取巡检点状态枚举集合")
    public CommonResponse getCheckStateList() {
        return CommonResponseUtil.success(CheckStatusEnum.getEnumList());
    }

    /**
     * 巡检轨迹查询
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检轨迹查询", notes = "巡检轨迹查询")
    @RequestMapping(value = "/trajectory/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse findTrajectoryList(
            @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        try {
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            String roleTypeName = getRoleTypeName(reginParams);
            HashMap<String, Object> paramMap = buildMybatisDaoCriterias(loginOrgCode, roleTypeName);
            CheckPtListPageParam params = CheckPageParamUtil.fillTraParam(queryRequests, commonPageable, paramMap);
            Page<CheckTraListBo> checkTraListBo = checkService.getCheckTraList(params);
            return CommonResponseUtil.success(checkTraListBo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponseUtil.failure();
        }
    }

    /**
     * 路线计划点最近巡检记录查询
     *
     * @param param
     * @return
     */
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "点id", notes = "路线计划点最近巡检记录查询")
    @RequestMapping(value = "/routePlanPoint/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse findRoutePlanPointList(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        HashMap<String, Object> paramMap = buildMybatisDaoCriterias(loginOrgCode, roleTypeName);
        CheckPtListPageParam params = CheckPageParamUtil.fillChkPtParam(queryRequests, null, paramMap);
        List<PlanRoutePointBo> checkChkExListBo = checkService.getRoutePlanPointList(params);
        return CommonResponseUtil.success(checkChkExListBo);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询条件初始化口(<font color='blue'>release</font>)", notes = "查询条件初始化口")
    @RequestMapping(value = "/queryConditions/init/{type}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse findCheckSystemInit(@ApiParam(value = "类型", required = true) @PathVariable String type) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        String departmentId = getDepartmentId(reginParams);
        String companyId = getCompanyId(reginParams);
        if (ObjectUtils.isEmpty(reginParams)) {
            return CommonResponseUtil.failure("用户session过期");
        }
        try {
            QueryCriteriaRespone respone = checkService.findCheckSystemInit(getToken(), getProduct(), getAppKey(), type, loginOrgCode, roleTypeName, departmentId, companyId);

            return CommonResponseUtil.success(respone);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponseUtil.failure();
        }
    }
}
