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

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.OrderByEnum;
import com.yeejoin.amos.maintenance.common.enums.PlanTaskDetailIsFinishEnum;
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.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 javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@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;

    /**
     * 计划执行查询
     * @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
     */
    @ApiOperation(value = "定时执行任务表生成", notes = "定时执行任务表生成")
    @RequestMapping(value = "/queryOmission", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse pushCarData() {
        try {
            planTaskService.taskExecution(null);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure();
        }
    }

    /**
     * 模拟定时任务调起服务
     *
     * @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();
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "维保设施分页列表-mobile", notes = "维保设施分页列表-mobile")
    @RequestMapping(value = "/point/{planTaskId}/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse 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 CommonResponseUtil.success(planTaskService.getPlanTaskPoints(param));
    }

    /**
     * 查询任务列表
     *
     * @param
     * @return
     */
    @PersonIdentify(isNeedIdentity = true)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "维保任务查询-mobile", notes = "根据用户条件查询所有计划任务-mobile")
    @RequestMapping(value = "/queryPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse qryLoginUserPlanTask(
            @ApiParam(value = "人员") @RequestParam(value = "userId", required = false) Long userId,
            @ApiParam(value = "开始日期", required = true) @RequestParam(value = "startDate") String startTime,
            @ApiParam(value = "结束日期", required = true) @RequestParam(value = "endDate") 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 {
        HashMap<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);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("finishStatus", finishStatus);
        params.put("orderBy", OrderByEnum.getEumByCode(orderBy).getOderBy());
        CommonPageable pageable = new CommonPageable(pageNumber, pageSize);
        return CommonResponseUtil.success(planTaskService.getPlanTasks(params, pageable));
    }

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

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "维保设施完成状态下拉枚举数据")
    @GetMapping(value = "/taskDetail/finishStatus/list")
    public CommonResponse planTaskPointDetail() {
        return CommonResponseUtil.success(PlanTaskDetailIsFinishEnum.getEnumList());
    }
}