/*
 * Copyright (c) 2024 codvision.com All Rights Reserved.
 */

package com.codvision.basic.controller.inspection;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.codvision.auth.entity.vo.SysUserVO;
import com.codvision.auth.support.UserContext;
import com.codvision.basic.entity.inspection.InspectionRecord;
import com.codvision.basic.entity.inspection.InspectionTask;
import com.codvision.basic.entity.vo.inspection.InspectionRecordVO;
import com.codvision.basic.service.inspection.InspectionRecordService;
import com.codvision.basic.service.inspection.InspectionTaskService;
import com.codvision.commoncore.common.ResponseEntity;
import com.codvision.commoncore.exception.BusinessException;
import com.codvision.commoncore.utils.DateUtil;
import com.codvision.webcore.bean.QueryPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author codvision
 */
@RestController
@RequestMapping("/InspectionRecord")
@Api(tags = "检查-记录")
@RequiredArgsConstructor
public class InspectionRecordController {

    private final InspectionRecordService service;
    private final InspectionTaskService inspectionTaskService;

    @PostMapping("/getPageResult")
    @ApiOperation("分页列表")
    public ResponseEntity<IPage<InspectionRecordVO>> getPageResult(@RequestBody QueryPage<Map<String, Object>> queryPage) {
        return new ResponseEntity<IPage<InspectionRecordVO>>().data(service.getPageResult(queryPage));
    }

    @ApiOperation(value = "添加检查记录", notes = "添加检查记录")
    @PostMapping(value = "/addInspectRecord")
    public ResponseEntity<InspectionRecord> addInspectRecord(@RequestParam(value = "refCode") String refCode,
                                                             @RequestParam(value = "refName") String refName,
                                                             @RequestParam(value = "inspectionId") Integer inspectionId,
                                                             @RequestParam(value = "taskId") Integer taskId,
                                                             @ApiParam(value = "数据来源") @RequestParam(value = "source") String source,
                                                             @ApiParam(value = "整改时限(天)") @RequestParam(value = "rectifyDeadline") Integer rectifyDeadline,
                                                             @RequestParam(value = "issueNumber", defaultValue = "0") int issueNumber,
                                                             @RequestParam(value = "inspectLng", defaultValue = "0") Double inspectLng,
                                                             @RequestParam(value = "inspectLat", defaultValue = "0") Double inspectLat,
                                                             @RequestParam(value = "checklist", required = false) String checklist) {
        ResponseEntity<InspectionRecord> responseEntity = new ResponseEntity<>();
        SysUserVO loginUser = UserContext.get();
        if (null == loginUser) {
            throw new BusinessException(10002);
        }
        InspectionTask task = inspectionTaskService.getOne(Wrappers.<InspectionTask>lambdaQuery().eq(InspectionTask::getId, taskId));
        if (task == null) {
            throw new BusinessException(10003, "该检查任务不存在！");
        }
        if (new Date().before(DateUtil.toDate(task.getStartTime()))) {
            throw new BusinessException(10003, "该检查任务暂未开始！");
        }
        if (new Date().after(DateUtil.toDate(task.getEndTime()))) {
            throw new BusinessException(10003, "该检查任务已结束！");
        }

        InspectionRecord record = InspectionRecord.builder().inspectionId(inspectionId).refCode(refCode)
                .issueNumber(issueNumber).creatorId(loginUser.getId()).creator(loginUser.getName()).inspectLng(inspectLng).inspectLat(inspectLat)
                .source(source).rectifyDeadline(rectifyDeadline).category(task.getCategory()).taskId(taskId).refName(refName).build();
        if (issueNumber != 0) {
            record.setStatus("0");
        } else {
            record.setStatus("2");
        }

        service.addInspectRecord(record, checklist);
        return responseEntity.data(record);
    }

    @PostMapping("/getById")
    @ApiOperation(value = "通过主键查询")
    public ResponseEntity<InspectionRecordVO> getById(@RequestParam(value = "id") Integer id) {
        return new ResponseEntity<InspectionRecordVO>().data(service.getById(id));
    }

    @PostMapping("/statByTask")
    @ApiOperation(value = "统计（任务）")
    public ResponseEntity statByTask(@RequestParam(required = false) Integer oid) {
        Map<String, Object> params = new HashMap<>(16);
        SysUserVO user = UserContext.get();
        if (null != oid) {
            params.put("oid", oid);
        } else {
            params.put("oid", user.getActiveOid());
        }
        return new ResponseEntity(service.statByTask(params));
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加(点击 Model 可以查看具体详情)")
    public ResponseEntity<InspectionRecord> add(@ApiParam(value = "对象") @RequestBody InspectionRecord inspectionRecord) {
        service.save(inspectionRecord);
        return new ResponseEntity<InspectionRecord>().data(inspectionRecord);
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新: 注意此更新只会更新不会NUll的数据, 若要不展示可置为空字符")
    public ResponseEntity<InspectionRecord> update(@ApiParam(value = "对象") @RequestBody InspectionRecord inspectionRecord) {
        ResponseEntity<InspectionRecord> responseEntity = new ResponseEntity<>();
        if (inspectionRecord.getId() == null) {
            throw new BusinessException(30002);
        }

        service.updateById(inspectionRecord);
        return responseEntity.ok();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    public ResponseEntity<InspectionRecord> delete(@ApiParam(value = "主键") @RequestParam(value = "key") Integer key) {
        service.removeById(key);
        return new ResponseEntity<InspectionRecord>().ok();
    }
}
