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

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.maintenance.business.feign.JCSFeignClient;
import com.yeejoin.amos.maintenance.business.param.PlanTaskPageParam;
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.CommonResponse;
import com.yeejoin.amos.maintenance.business.util.CommonResponseUtil;
import com.yeejoin.amos.maintenance.business.util.FileHelper;
import com.yeejoin.amos.maintenance.business.util.PlanTaskPageParamUtil;
import com.yeejoin.amos.maintenance.business.vo.PlanTaskVo;
import com.yeejoin.amos.maintenance.common.enums.PlanTaskDetailIsFinishEnum;
import com.yeejoin.amos.maintenance.common.enums.PlanTaskFinishStatusEnum;
import com.yeejoin.amos.maintenance.common.enums.PlanTaskOrderByEnum;
import com.yeejoin.amos.maintenance.core.common.request.CommonPageable;
import com.yeejoin.amos.maintenance.core.common.request.CommonRequest;
import com.yeejoin.amos.maintenance.core.framework.PersonIdentify;
import com.yeejoin.amos.maintenance.core.util.StringUtil;
import com.yeejoin.amos.maintenance.exception.YeeException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DELL
 */
@RestController
@RequestMapping(value = "/api/planTask")
@Api(tags = "计划执行api")
public class PlanTaskController extends AbstractBaseController {
    private final Logger log = LoggerFactory.getLogger(PlanTaskController.class);

    @Autowired
    private IPlanTaskService planTaskService;

    @Autowired
    IPointService pointService;

    @Autowired
    JCSFeignClient jcsFeignClient;

    /**
     * 计划执行查询
     *
     * @param queryRequests
     * @param commonPageable
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "计划执行查询", notes = "计划执行查询")
    @RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse getPlanTaskList(
            @ApiParam(value = "查询条件") @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, null);
        PlanTaskPageParam params = new PlanTaskPageParam();
        PlanTaskPageParamUtil.fillChkInfoParam(queryRequests, commonPageable, params, paramMap);
        Page<HashMap<String, Object>> list = planTaskService.getPlanTaskInfo(params);
        return CommonResponseUtil.success(list);
    }

    /**
     * 计划执行重做
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "计划执行重做", notes = "计划执行重做")
    @RequestMapping(value = "/regenPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse planTaskReGen(
            @ApiParam(value = "巡检计划", required = true) @RequestBody HashMap<String, Object> param) {
        if (param.get("planId") == null) {
            throw new YeeException("计划编号不能为空");
        }
        if (param.get("beginDate") == null) {
            throw new YeeException("开始日期能为空");
        }
        if (param.get("endDate") == null) {
            throw new YeeException("结束日期不能为空");
        }
        if (param.get("changeFlag") == null) {
            throw new YeeException("是否记为合格不能为空");
        }
        try {
            planTaskService.reGenPlanTask(param);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("计划执行重做失败");
        }
    }

    /**
     * 计划执行删除
     *
     * @param strArry
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "计划执行删除", notes = "计划执行删除")
    @RequestMapping(value = "/deletePlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse planTaskDelete(@ApiParam(value = "计划id数组", required = true) @RequestBody String[] strArry) {
        try {
            planTaskService.planTaskDet(strArry);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("删除计划执行失败");
        }
    }

    /**
     * 执行计划导出
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "执行计划导出", notes = "执行计划导出")
    @PostMapping(value = "/reportPlanTask", produces = "application/vnd.ms-excel;charset=UTF-8")
    public void planTaskReport(
            @ApiParam(value = "导出参数") @RequestBody(required = false) List<CommonRequest> queryRequests,
            HttpServletResponse response) {
        try {
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            HashMap<String, Object> paramMap = buildMybatisDaoCriterias(loginOrgCode, null);
            PlanTaskPageParam params = new PlanTaskPageParam();
            PlanTaskPageParamUtil.fillChkInfoParam(queryRequests, null, params, paramMap);
            List<PlanTaskVo> list = planTaskService.planTaskReport(getToken(), getProduct(), getAppKey(), params);
            String fileName = "计划执行" + System.currentTimeMillis();
            FileHelper.exportExcel(list, "计划执行", "计划执行", PlanTaskVo.class, fileName + ".xls", response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出巡检记录", notes = "导出巡检记录")
    @RequestMapping(value = "/exportSelectPlanTask", method = RequestMethod.GET)
    public void exportSelectPlanTask(
            @ApiParam(value = "查询条件", required = false) @RequestParam(required = false) Long[] ids,
            HttpServletResponse response) {
        List<PlanTaskVo> list = planTaskService.getPlanTaskListByIds(getToken(), getProduct(), getAppKey(), ids);
        String fileName = "巡检记录" + System.currentTimeMillis();
        FileHelper.exportExcel(list, "计划执行", "计划执行", PlanTaskVo.class, fileName + ".xls", response);
    }

    /**
     * 模拟定时任务调起服务
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "模拟定时任务调起服务", notes = "模拟定时任务调起服务")
    @RequestMapping(value = "/schJobTest", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse schJobTest(@ApiParam(value = "跑批日期格式yyyyMMdd", required = false) @RequestParam(required = false) String runDate) {
        try {
            planTaskService.taskExecution(runDate);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure();
        }
    }

    /**
     * 模拟发送维保待办任务消息定时任务
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "模拟发送维保待办任务消息定时任务", notes = "模拟发送维保待办任务消息定时任务")
    @RequestMapping(value = "/taskMessage", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse taskMessage(@ApiParam(value = "跑批日期格式yyyyMMdd", required = false) @RequestParam(required = false) String runDate) {
        try {
            planTaskService.taskMessage(runDate);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure();
        }
    }

    /**
     * 查询任务列表
     *
     * @param
     * @return
     */
    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "维保任务查询-mobile", notes = "根据用户条件查询所有计划任务-mobile")
    @RequestMapping(value = "/queryPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public ResponseModel<Page<Map<String, Object>>> qryLoginUserPlanTask(
            @ApiParam(value = "人员") @RequestParam(value = "userId", required = false) Long userId,
            @ApiParam(value = "开始日期") @RequestParam(value = "startDate", required = false) String startTime,
            @ApiParam(value = "结束日期") @RequestParam(value = "endDate", required = false) String endTime,
            @ApiParam(value = "维保状态") @RequestParam(value = "finishStatus", required = false) Integer finishStatus,
            @ApiParam(value = "排序条件") @RequestParam(value = "orderBy", defaultValue = "1") String orderBy,
            @ApiParam(value = "业主单位") @RequestParam(value = "companyId", required = false) String companyId,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "pageNumber") int pageNumber,
            @ApiParam(value = "页大小", required = true) @RequestParam(value = "pageSize") int pageSize) throws Exception {
        Map<String, Object> params = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        Map<String, Object> authMap = Bean.BeantoMap(reginParams.getPersonIdentity());
        params.putAll(authMap);
        params.put("companyId", companyId);
        params.put("orgCode", loginOrgCode);
        params.put("userId", userId);
        if (StringUtil.isNotEmpty(userId)) {
            ResponseModel<String> idByAmosOrgId = jcsFeignClient.getIdByAmosOrgId(String.valueOf(userId));
            if (StringUtil.isNotEmpty(idByAmosOrgId.getResult())) {
                params.put("userId", idByAmosOrgId.getResult());
            }
        }
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("finishStatus", finishStatus);
        params.put("orderBy", PlanTaskOrderByEnum.getEumByCode(orderBy).getOderBy());
        CommonPageable pageable = new CommonPageable(pageNumber, pageSize);
        return ResponseHelper.buildResponse(planTaskService.getPlanTasks(params, pageable));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "维保设施分页列表-mobile", notes = "维保设施分页列表-mobile")
    @RequestMapping(value = "/point/{planTaskId}/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public ResponseModel qryPlanTaskById(
            @ApiParam(value = "巡检计划任务ID", required = true) @PathVariable Long planTaskId,
            @ApiParam(value = "建筑id", required = true) @RequestParam(value = "buildingId", required = false) String buildingId,
            @ApiParam(value = "维保状态", required = true) @RequestParam(value = "isFinish", required = false) String isFinish,
            @ApiParam(value = "消防系统id", required = true) @RequestParam(value = "systemId", required = false) String systemId,
            @ApiParam(value = "设备编号", required = true) @RequestParam(value = "pointNo", required = false) String pointNo,
            @ApiParam(value = "设备名称", required = true) @RequestParam(value = "pointName", required = false) String pointName
    ) {
        Map<String, Object> param = new HashMap<>();
        param.put("planTaskId", planTaskId);
        param.put("buildingId", buildingId);
        param.put("isFinish", isFinish);
        param.put("systemId", systemId);
        param.put("pointNo", pointNo);
        param.put("pointName", pointName);
        return ResponseHelper.buildResponse(planTaskService.getPlanTaskPoints(param));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据任务详情ID查信息(首页维保待办任务跳转试用)-mobile", notes = "根据任务详情ID查信息(首页维保待办任务跳转试用)-mobile")
    @RequestMapping(value = "/point/{planTaskDetailId}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public ResponseModel getByTaskDetailId(@ApiParam(value = "任务详情ID", required = true) @PathVariable Long planTaskDetailId) {
        return ResponseHelper.buildResponse(planTaskService.getByTaskDetailId(planTaskDetailId));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询维保设施，检查内容详情")
    @GetMapping(value = "/task-point-detail")
    public ResponseModel planTaskPointDetail(
            @RequestParam(value = "routePointId") String routePointId,
            @RequestParam(value = "id") String planTaskDetailId
    ) {
        return ResponseHelper.buildResponse(planTaskService.planTaskPointDetail(planTaskDetailId, routePointId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "维保设施完成状态下拉列表")
    @GetMapping(value = "/taskDetail/finishStatus/list")
    public ResponseModel planTaskPointDetail() {
        return ResponseHelper.buildResponse(PlanTaskDetailIsFinishEnum.getEnumList());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "计划任务完成状态列表", notes = "计划任务完成状态列表")
    @RequestMapping(value = "/finishStatus/list", method = RequestMethod.GET)
    public ResponseModel getPlanTaskFinishStatus() {
        return ResponseHelper.buildResponse(PlanTaskFinishStatusEnum.getEnumList());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "维保任务排序条件", notes = "维保任务排序条件")
    @RequestMapping(value = "/orderBy/list", method = RequestMethod.GET)
    public ResponseModel getOrderByList() {
        return ResponseHelper.buildResponse(PlanTaskOrderByEnum.getEnumList());
    }
}