package com.ruoyi.app.controller.doubleDefense;

import com.ruoyi.app.controller.common.AppBaseController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.DangerStatusEnum;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JWTUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.doubledefense.dto.DangerDTO;
import com.ruoyi.doubledefense.dto.res.DangerResultDTO;
import com.ruoyi.doubledefense.service.IDangerService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * 隐患信息Controller
 *
 * @author ruoyi
 * @date 2023-08-03
 */
@Api(tags = "APP隐患信息相关接口")
@RestController
@RequestMapping("/app/doubledefense/danger")
public class DangerForAppController extends AppBaseController {
    @Autowired
    private IDangerService dangerService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询隐患信息列表
     */
    @ApiOperation("查询所有隐患信息列表")
    @GetMapping("/list")
    public TableDataInfo list() {
//        startPage();
        List<DangerResultDTO> list = dangerService.selectDangerList(new DangerDTO());
        return getDataTable(list);
    }


    /*
     * 废弃了
     * APP隐患代办请求接口：/app/doubledefense/danger/getUnclaimedList 接口要求普通人只查询自己相关的数据（自己是申请人或审核人）领导查询全部数据
     * 2023年9月26日15:37:27
     * @return
    @ApiOperation("查询待办隐患信息列表")
    @GetMapping("/getUnclaimedList")
    public TableDataInfo getUnclaimedList() {
        startPage();
        List<DangerResultDTO> list = dangerService.selectDangerList(new DangerDTO());
        return getDataTable(list);
    }
     */


    /**
     * 新增隐患信息
     */
    @ApiOperation("新增隐患信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "设备UUID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "checkRecordId", value = "排查记录ID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dangerName", value = "隐患名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dangerDesc", value = "隐患描述", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "registTime", value = "登记时间", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "dangerLevel", value = "隐患等级：0一般隐患，1重大隐患", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "dangerImage", value = "隐患图片，多张以逗号分割", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dangerSrc", value = "隐患来源：1日常排查，2综合排查，3专业性排查，4季节性排查，5重点时段及节假日前排查，6事故类比排查，7复产复工前排查，8外聘专家诊断式排查，9管控措施失效，10其它", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "hazardDangerType", value = "隐患类型：1安全，2工艺，3电气，4仪表，5消防，6总图，7设备，8其它", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "dangerManageType", value = "治理类型：0即查即改，1限期整改", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "cost", value = "整改资金", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "controlMeasures", value = "控制措施", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "suggest", value = "整改建议", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "deptId", value = "整改部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "areaId", value = "所属区域ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "manageUserId", value = "整改负责人ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "dangerManageDeaddline", value = "整改治理期限", dataType = "Date", dataTypeClass = Date.class)
    })
    @Log(title = "隐患信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DangerDTO danger) {
        danger.setCompanyCode(getCompanyCode());
//        danger.setCreateUserId(getUserId());
//        danger.setUpdateUserId(getUserId());
        danger.setCreateUserId(Long.parseLong(JWTUtil.getPCUserId()));
        danger.setUpdateUserId(Long.parseLong(JWTUtil.getPCUserId()));

        if(StringUtils.isBlank(danger.getDangerImage())){
            return AjaxResult.error("请添加隐患照片");
        }

        return toAjax(dangerService.insertDangerForApp(danger));
    }


    /**
     * 修改隐患信息
     */
    @ApiOperation("修改隐患信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键UUID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "deviceId", value = "设备UUID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "checkRecordId", value = "排查记录ID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dangerName", value = "隐患名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dangerDesc", value = "隐患描述", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "registTime", value = "登记时间", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "dangerLevel", value = "隐患等级：0一般隐患，1重大隐患", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "dangerImage", value = "隐患图片，多张以逗号分割", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dangerSrc", value = "隐患来源：1日常排查，2综合排查，3专业性排查，4季节性排查，5重点时段及节假日前排查，6事故类比排查，7复产复工前排查，8外聘专家诊断式排查，9管控措施失效，10其它", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "hazardDangerType", value = "隐患类型：1安全，2工艺，3电气，4仪表，5消防，6总图，7设备，8其它", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "dangerManageType", value = "治理类型：0即查即改，1限期整改", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "cost", value = "整改资金", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "controlMeasures", value = "控制措施", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "suggest", value = "整改建议", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "deptId", value = "整改部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "areaId", value = "所属区域ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "manageUserId", value = "整改负责人ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "dangerManageDeaddline", value = "整改治理期限", dataType = "Date", dataTypeClass = Date.class)
    })
    @Log(title = "隐患信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DangerDTO danger) {
//        danger.setUpdateUserId(getUserId());
        danger.setUpdateUserId(Long.parseLong(JWTUtil.getPCUserId()));
        return toAjax(dangerService.updateDangerForApp(danger, false));
    }

    /**
     * 获取隐患信息详细信息
     */
    @ApiOperation("获取隐患信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(dangerService.selectDangerById(id));
    }

    /**
     * 隐患审核
     */
    @ApiOperation("隐患审核")
    @PostMapping("/dangerReview")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "审核类型：1-驳回，2-通过", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "dangerId", value = "隐患主键", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "remark", value = "备注：驳回原因或审核通过备注", dataType = "String", dataTypeClass = String.class)
    })
    public AjaxResult dangerReview(@RequestBody Map<String, Object> map) {
        Object type = map.get("type");
        Object remark = map.get("remark");
        Object dangerId = map.get("dangerId");
        if (Objects.isNull(type) || Objects.isNull(dangerId)) {
            return error("参数错误!");
        }
        DangerDTO dangerDTO = new DangerDTO();
        dangerDTO.setId(dangerId.toString());
        if (type.toString().equals("1")) {
            //设置驳回人的昵称
//            String pcUserId = JWTUtil.getPCUserId();
//            String id = JWTUtil.getUserId();
//            String userName = JWTUtil.getUserName();
//            System.out.println("pcUserId = " + pcUserId);
//            System.out.println("id = " + id);
//            System.out.println("userName = " + userName);
//            SysUser sysUser = sysUserService.selectUserById(Long.parseLong(JWTUtil.getPCUserId()));
//            dangerDTO.setRejectUserName(sysUser != null ? sysUser.getNickName() : null);
            dangerDTO.setRejectUserName(JWTUtil.getNickName());
            dangerDTO.setDangerStatus(DangerStatusEnum.CANCELED.getValue());
            if (Objects.nonNull(remark)) {
                dangerDTO.setRemarkInfo((String) remark);
            }
        } else {
            dangerDTO.setDangerStatus(DangerStatusEnum.UNCLAIMED.getValue());
        }
        return dangerService.dangerReview(dangerDTO);
    }

    /**
     * 领取隐患
     */
    @ApiOperation("领取隐患")
    @PostMapping("/receiveDanger/{id}")
    public AjaxResult receiveDanger(@PathVariable String id) {
        return dangerService.receiveDanger(id);
    }

    /**
     * 提交整改信息
     */
    @ApiOperation("提交整改信息")
    @PostMapping("/submitDangerManage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dangerId", value = "隐患主键", dataType = "String", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "rectificationTime", value = "添加整改时间,yyyy-MM-dd HH:mm:ss", dataType = "String", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "controlMeasures", value = "整改措施", dataType = "String", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "cost", value = "整改资金", dataType = "String", dataTypeClass = String.class, required = false),
            @ApiImplicitParam(name = "rectifyImage", value = "整改后图片", dataType = "String", dataTypeClass = String.class, required = true),
    })
    public AjaxResult submitDangerManage(@RequestBody Map<String, String> map) {
        String dangerId = map.get("dangerId");
        String rectificationTime = map.get("rectificationTime");
        String controlMeasures = map.get("controlMeasures");
        String cost = map.get("cost");
        String rectifyImage = map.get("rectifyImage");
        if (StringUtils.isBlank(dangerId)) {
            return error("参数错误!");
        }
        DangerDTO dangerDTO = new DangerDTO();
        dangerDTO.setId(dangerId.toString());
        dangerDTO.setDangerStatus(DangerStatusEnum.WAIT_FOR_ACCEPTANCE.getValue());
        try {
            dangerDTO.setRectificationTime(DateUtils.parseDate(rectificationTime, DateUtils.YYYY_MM_DD_HH_MM_SS));
        } catch (Exception e) {
            return AjaxResult.error("整改时间错误！");
        }
        dangerDTO.setControlMeasures(controlMeasures);
        dangerDTO.setCost(StringUtils.isNotBlank(cost) ? cost : null);
        dangerDTO.setRectifyImage(rectifyImage);
        return dangerService.submitDangerManage(dangerDTO);
    }

    /**
     * 风险隐患整改验收
     */
    @ApiOperation("隐患整改验收")
    @PostMapping("/checkDangerManage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "验收类型：1驳回，2通过", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "dangerId", value = "隐患主键", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "checkAcceptTime", value = "验收时间：yyyy-MM-dd HH:mm:ss", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "sign", value = "验收人签字", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "remark", value = "备注：驳回原因或审核通过备注", dataType = "String", dataTypeClass = String.class)
    })
    public AjaxResult checkDangerManage(@RequestBody Map<String, Object> map) {
        Object type = map.get("type");
        Object dangerId = map.get("dangerId");
        Object checkAcceptTime = map.get("checkAcceptTime");
        Object sign = map.get("sign");
        Object remark = map.get("remark");
        if (Objects.isNull(type) || Objects.isNull(dangerId)) {
            return error("参数错误【1】!");
        }
        if (Objects.isNull(sign) || Objects.isNull(sign)) {
            return error("参数错误，验收人签字图片为空!");
        }

        DangerDTO dangerDTO = new DangerDTO();
        dangerDTO.setId(dangerId.toString());
        dangerDTO.setCheckAcceptComment((String) remark);//验收情况描述：通过/驳回都有值
        try {
            dangerDTO.setCheckAcceptTime(DateUtils.parseDate(checkAcceptTime.toString(), DateUtils.YYYY_MM_DD_HH_MM_SS));
        } catch (Exception e) {
            return AjaxResult.error("验收时间错误！");
        }
        dangerDTO.setCheckSignature(sign.toString());

        if (type.toString().equals("1")) {
            dangerDTO.setDangerStatus(DangerStatusEnum.RECTIFICATION.getValue());
            //设置驳回人的昵称
            SysUser sysUser = sysUserService.selectUserById(Long.parseLong(JWTUtil.getPCUserId()));
            dangerDTO.setRejectUserName(sysUser != null ? sysUser.getNickName() : null);
            if (Objects.nonNull(remark)) {
                dangerDTO.setRemarkInfo((String) remark);
            }
        } else {
            dangerDTO.setDangerStatus(DangerStatusEnum.COMPLETED.getValue());
//            if (Objects.nonNull(remark)) {通过不写驳回原因
//                dangerDTO.setRemarkInfo((String) remark);
//            }
        }
        return dangerService.checkDangerManage(dangerDTO);
    }


}
