package com.sw.mes.yb.pad.controller;

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.redis.server.RedisUtils;
import com.sw.mes.yb.accessory.entity.EquipmentDeviceStatus;
import com.sw.mes.yb.accessory.service.EquipmentDeviceStatusService;
import com.sw.mes.yb.deviceCheck.dto.DeviceCheckPadDto;
import com.sw.mes.yb.deviceCheck.entity.DeviceCheck;
import com.sw.mes.yb.deviceCheck.entity.DeviceCleanRecord;
import com.sw.mes.yb.deviceCheck.entity.SpotCheckItem;
import com.sw.mes.yb.deviceCheck.service.DeviceCheckService;
import com.sw.mes.yb.deviceCheck.service.DeviceCleanRecordService;
import com.sw.mes.yb.deviceCheck.service.SpotCheckItemService;
import com.sw.mes.yb.pc.service.StoreMixInfoService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author liuzemin
 * @date 2022/5/18 15:30
 * @description
 */
@RestController
@RequestMapping("/mes/pad")
@Slf4j
@Api(description = "PAD设备点检")
public class PadDeviceCheckController {

    @Autowired
    private SpotCheckItemService spotCheckItemService;

    @Autowired
    @Qualifier(value = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    private final String DEVICE_CHECK_PREFIX = "DEVICE_CHECK_";

    public static final String DEVICE_CHECK_BUTTON_PREFIX = "DEVICE_CHECK_BUTTON_";

    @Autowired
    private StoreMixInfoService storeMixInfoService;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private DeviceCheckService deviceCheckService;

    @Autowired
    private EquipmentDeviceStatusService equipmentDeviceStatusService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private DeviceCleanRecordService deviceCleanRecordService;


    @ApiOperation(value = "PAD获取拆清点检配置列表")
    @ApiImplicitParams({
    })
    @PostMapping("/deviceCheck/getCheckList")
    public Result getDeviceCheck() {
        List<SpotCheckItem> spotCheckItems = spotCheckItemService.findAllOrderByPriority();
        Map<String, List<SpotCheckItem>> map = new HashMap<>();
        List<SpotCheckItem> list;
        // TODO 不区分 拆清类别
//        SpotCheckItem xiaoqing;
//        SpotCheckItem kongshao;
        for (SpotCheckItem item : spotCheckItems) {
//            xiaoqing = new SpotCheckItem();
//            BeanUtils.copyProperties(item, xiaoqing);
//            xiaoqing.setCleanFlag(0);
//            kongshao = new SpotCheckItem();
//            BeanUtils.copyProperties(item, kongshao);
//            kongshao.setCleanFlag(2);
            if (map.containsKey(item.getParent())) {
                list = map.get(item.getParent());
                list.add(item);
//                list.add(xiaoqing);
//                list.add(kongshao);
            } else {
                list = new ArrayList<>();
                list.add(item);
//                list.add(xiaoqing);
//                list.add(kongshao);
                map.put(item.getParent(), list);
            }
        }
        return ResultGenerator.success(map);
    }

    @ApiOperation(value = "PAD根据设备编号获取拆清点检暂存数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceNo", value = "设备编号", dataType = "String", paramType = "query")
    })
    @GetMapping("/deviceCheck/getCache")
    public Result getCache(String deviceNo) {

        try {
            Boolean has = redisTemplate.hasKey(DEVICE_CHECK_PREFIX + deviceNo);
            if (has != null && has) {
                String result = redisTemplate.opsForValue().get(DEVICE_CHECK_PREFIX + deviceNo).toString();
                return ResultGenerator.success(result);
            } else {
                return ResultGenerator.success("");
            }
        } catch (Exception e) {
            return ResultGenerator.success("");
        }
    }

    @ApiOperation(value = "PAD根据设备编号获取拆清点检暂存数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceNo", value = "设备编号", dataType = "String", paramType = "query")
    })
    @GetMapping("/deviceCheck/deleteCache")
    public Result deleteCache(String deviceNo) {

        try {
            redisTemplate.delete(DEVICE_CHECK_PREFIX + deviceNo);
        } catch (Exception e) {
            return ResultGenerator.fail("暂存信息删除失败！");
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "拆清点检暂存")
    @PostMapping("/deviceCheck/createCache")
    public Result createCache(@RequestBody @ApiParam(value = "设备点检对象") DeviceCheckPadDto deviceCheckDto) {
        if (StringUtils.isBlank(deviceCheckDto.getDeviceNo())) {
            return ResultGenerator.fail("设备编号不能为空！");
        }

//        DeviceCheck deviceCheck = fromDeviceCheckDto(deviceCheckDto);
//
//        String lotNo = storeMixInfoService.findLastByDeviceNo(deviceCheck.getDeviceNo());
//        deviceCheck.setLotNo(lotNo);
//
//        try {
//            WorkhourLog log = workhourLogService.findByDeviceNameAndName(deviceCheck.getDeviceNo(), "停炉");
//            if (log != null) {
//                // 24小时之外
//                if (log.getStartDateTime().after(DateUtil.getDate(new Date(), -24))) {
//                    deviceCheck.setShutdownTime(log.getStartDateTime());
//                }
//            } else {
//                RealtimeWorkhour workhour = realtimeWorkhourService.findByDeviceNameAndNameAndIsFinishedOrderByIdDescLimit1(deviceCheck.getDeviceNo(), "停炉");
//                if (workhour != null && workhour.getStartDateTime().after(DateUtil.getDate(new Date(), -24))) {
//                    deviceCheck.setShutdownTime(workhour.getStartDateTime());
//
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            redisTemplate.opsForValue().set("DEVICE_CHECK_" + deviceCheckDto.getDeviceNo(), JSONObject.toJSONString(deviceCheckDto), 48, TimeUnit.HOURS);
        } catch (Exception e) {
            return ResultGenerator.fail("暂存失败：" + e.getMessage());
        }

//        deviceCheck.setRemark(DeviceCheckRemarkEnum.退单.getKey());
//        deviceCheck.setCreateTime(new Date());
//        deviceCheckService.saveOrUpdate(deviceCheck);

        return ResultGenerator.success();
    }

    @ApiOperation(value = "创建拆清点检信息")
    @PostMapping("/deviceCheck/create")
    public Result create(@RequestBody @ApiParam(value = "设备点检对象") DeviceCheckPadDto deviceCheckDto) {
        DeviceCheck deviceCheck = fromDeviceCheckDto(deviceCheckDto);

        String lotNo = storeMixInfoService.findLastByDeviceNo(deviceCheck.getDeviceNo());
        if(StringUtils.isBlank(lotNo)){
            throw new RuntimeException("无法查询到炉次号");
        }
        deviceCheck.setLotNo(lotNo);

        if(deviceCheckDto.getShutdownTime() == null){
            EquipmentDeviceStatus equipmentDeviceStatus = equipmentDeviceStatusService.findByDeviceNo(deviceCheck.getDeviceNo());
            if (equipmentDeviceStatus != null){
                deviceCheck.setShutdownTime(equipmentDeviceStatus.getEndTime());
            }
        }

        DeviceCleanRecord deviceCleanRecord = deviceCleanRecordService.findByLotNo(lotNo);
        if (deviceCleanRecord == null){
            throw new RuntimeException("未查询到拆清记录！");
        }

        Date newDate = new Date();
        deviceCheck.setCreateTime(newDate);
        deviceCheck.setOperateTime(newDate); //点检完成时间
        // 需要拆清操作人，拆清开始时间、拆清结束时间、拆清耗时
        deviceCheck.setStartTime(deviceCleanRecord.getCleanEndTime()); //点检开始时间 == 拆清结束时间
        deviceCheck.setOperateUser(deviceCleanRecord.getCleanOpertor1()); //拆清操作人1
        deviceCheck.setOperateUser2(deviceCleanRecord.getCleanOpertor2()); //拆清操作人2
        deviceCheck.setDismantleStartTime(deviceCleanRecord.getCleanStartTime()); //拆清开始时间
        deviceCheck.setDismantleEndTime(deviceCleanRecord.getCleanEndTime());  //拆清结束时间
        deviceCheck.setDismantleConsume(deviceCleanRecord.getCleanHour());  //拆清耗时
        deviceCheck.setTransferTime(deviceCleanRecord.getTransferTime());  //转单时间
        deviceCheck.setPokeOpertor(deviceCleanRecord.getPokeOpertor());    //捅管管道操作人
        deviceCheck.setPokeStartTime(deviceCleanRecord.getPokeStartTime()); //捅管道开始时间
        deviceCheck.setPokeEndTime(deviceCleanRecord.getPokeEndTime());  //捅管道结束时间
        deviceCheck.setPolishOpertor(deviceCleanRecord.getPolishOpertor()); //打磨人
        deviceCheck.setPolishStartTime(deviceCleanRecord.getPolishStartTime()); //开始打磨时间
        deviceCheck.setPolishEndTime(deviceCleanRecord.getPolishEndTime());  //结束打磨时间
        deviceCheckService.saveOrUpdate(deviceCheck);

        //按钮置灰
        redisUtils.set(DEVICE_CHECK_BUTTON_PREFIX+deviceCheck.getDeviceNo(),0);
//        try {
//            WorkhourLog stopLog = new WorkhourLog();
//            WorkhourLog log = workhourLogService.findByDeviceNameAndName(deviceCheck.getDeviceNo(), "停炉");
//            if (log != null) {
//                // 24小时之外
//                if (log.getStartDateTime().before(DateUtil.getDate(new Date(), -24))) {
//                    stopLog.setStartOperator("");
//                    stopLog.setStartDateTime(null);
//                    stopLog.setStartDescription("");
//                } else {
//                    deviceCheck.setShutdownTime(log.getStartDateTime());
//
//                    BeanUtils.copyProperties(log, stopLog);
//                    stopLog.setId(null);
//
//                    stopLog.setStartOperator(log.getEndOperator());
//                    stopLog.setStartDateTime(DateUtil.getDate(log.getStartDateTime(), 7));
//                    stopLog.setStartDescription(log.getEndDescription());
//                }
//            } else {
//                RealtimeWorkhour workhour = realtimeWorkhourService.findByDeviceNameAndNameAndIsFinishedOrderByIdDescLimit1(deviceCheck.getDeviceNo(), "停炉");
//                if (workhour != null && workhour.getStartDateTime().after(DateUtil.getDate(new Date(), -24))) {
//                    deviceCheck.setShutdownTime(workhour.getStartDateTime());
//
//                    stopLog.setStartOperator(workhour.getStartOperator());
//                    stopLog.setStartDateTime(DateUtil.getDate(workhour.getStartDateTime(), 7));
//                    stopLog.setStartDescription(workhour.getStartDescription());
//                } else {
//                    stopLog.setStartOperator("");
//                    stopLog.setStartDateTime(null);
//                    stopLog.setStartDescription("");
//                }
//            }
//
//            stopLog.setDeviceName(deviceCheck.getDeviceNo());
//            stopLog.setUid(UUID.randomUUID().toString());
//            stopLog.setName("拆清");
//            stopLog.setEndDateTime(deviceCheck.getOperateTime());
//            stopLog.setEndOperator(deviceCheck.getOperateUser());
//            stopLog.setEndDescription("拆清点检提交自动创建");
//            stopLog.setLotNo(lotNo);
//
//            if (stopLog.getStartDateTime() != null) {
//                stopLog.setActualTime(DateUtil.hourBetween(stopLog.getStartDateTime(), stopLog.getEndDateTime()));
//            } else {
//                stopLog.setActualTime(0d);
//
//            }
//
//            workhourLogService.createLog(stopLog);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//

        return ResultGenerator.success();
    }

    private DeviceCheck fromDeviceCheckDto(DeviceCheckPadDto dto) {
        return modelMapper.map(dto, DeviceCheck.class);
    }
}
