package com.tykj.dev.device.matching.controller;

import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.library.repository.DeviceLogDao;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.service.DeviceLogService;
import com.tykj.dev.device.library.subject.Dto.DeviceLogDto;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.domin.DeviceLog;
import com.tykj.dev.device.library.subject.vo.DeviceLogUserVo;
import com.tykj.dev.device.library.subject.vo.FileVo;
import com.tykj.dev.device.matching.service.MatchingDeviceBillService;
import com.tykj.dev.device.matching.service.MatchingDeviceLibraryService;
import com.tykj.dev.device.matching.subject.domin.MatchingDeviceBill;
import com.tykj.dev.device.matching.subject.domin.MatchingDeviceLibrary;
import com.tykj.dev.device.matching.subject.vo.*;
import com.tykj.dev.device.task.service.TaskLogService;
import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.task.subject.bto.TaskLogBto;
import com.tykj.dev.device.task.subject.common.BusinessEnum;
import com.tykj.dev.device.task.subject.common.StatusEnum;
import com.tykj.dev.device.task.subject.domin.Task;
import com.tykj.dev.device.user.subject.service.UserPublicService;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.utils.ResultUtil;
import com.tykj.dev.misc.utils.StringSplitUtil;
import com.tykj.dev.socket.MyWebSocket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/matchingDevice")
@AutoDocument
@Api(tags = "配套设备模块",description = "配套设备模块")
public class MatchingDeviceController {

    @Autowired
    private MatchingDeviceLibraryService matchingDeviceLibraryService;

    @Autowired
    private MatchingDeviceBillService matchingDeviceBillService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private DeviceLogDao deviceLogDao;

    @Autowired
    private MyWebSocket myWebSocket;

    @ApiOperation(value = "添加配套设备",notes = "可以通过这个接口添加配套设备")
    @PostMapping(value = "/add")
    public ResponseEntity<String> addStorageBill(@RequestBody MatchingDeviceBillSaveVo matchingDeviceBillSaveVo) {
        //添加账单
        MatchingDeviceBill matchingDeviceBillEntity = matchingDeviceBillSaveVo.toDo();
        MatchingDeviceBill m = matchingDeviceBillService.addEntity(matchingDeviceBillEntity);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("x");
        Integer userId = userUtils.getCurrentUserId();
        //发起任务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(matchingDeviceBillSaveVo.getUserbId());
        TaskBto taskBto = new TaskBto(StatusEnum.ADD_MATCHING_DEVICE_CONFIRM.id,"新增配套",null,".",m.getId(),19,userUtils.getCurrentUnitId(),1,null,userIds);
        Task taskEntity1 = taskService.start(taskBto);
        //添加业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("新增确认单",matchingDeviceBillEntity.getFileName(),matchingDeviceBillEntity.getFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(taskEntity1.getId(),"发起新增配套",fileVoList);
        taskLogService.addLog(taskLogBto);
        for (MatchingDeviceSaveVo matchingDeviceSaveVo:matchingDeviceBillSaveVo.getMatchingDeviceSaveVoList()) {
            MatchingDeviceLibrary matchingDeviceLibraryEntity = matchingDeviceSaveVo.toDo();
            MatchingDeviceLibrary saveEntity = matchingDeviceLibraryService.addEntity(matchingDeviceLibraryEntity);
            stringBuffer.append(saveEntity.getId());
            stringBuffer.append("x");
            //存装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(1,saveEntity.getId(),"发起新增配套",fileVoList);
            deviceLogService.addLog(deviceLogDto);
        }
        //set账单新增设备详情
        m.setDeviceDetail(stringBuffer.toString());
        matchingDeviceBillService.update(m);
        myWebSocket.sendMessage1();
        return ResultUtil.success("添加成功");
    }

    @ApiOperation(value = "添加配套设备审核",notes = "可以通过这个接口添加配套设备审核")
    @PostMapping(value = "/confirm")
    public ResponseEntity<String> confirm(@RequestBody MatchingDeviceBillConfirmVo matchingDeviceBillConfirmVo) {
        TaskBto taskBto = taskService.get(matchingDeviceBillConfirmVo.getTaskId());
        //1.审核成功,入库任务结束,改变装备状态
        if(matchingDeviceBillConfirmVo.getStatus()==0){
            taskService.update(taskService.moveToEnd(taskBto));
            //添加日业务志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"添加配套设备审核成功",null);
            taskLogService.addLog(taskLogBto);
            //更新账单状态
            MatchingDeviceBill matchingDeviceBillEntity = matchingDeviceBillService.getOne(taskBto.getBillId());
            matchingDeviceBillEntity.setBillStatus(2);
            matchingDeviceBillService.update(matchingDeviceBillEntity);
            //改变设备状态，增加日志
            List<Integer> list = StringSplitUtil.userIdSplit(matchingDeviceBillEntity.getDeviceDetail());
            if (!list.isEmpty()) {
                for (Integer d : list) {
                    MatchingDeviceLibrary deviceLibraryEntity = matchingDeviceLibraryService.getOne(d);
                    deviceLibraryEntity.setLifeStatus(2);
                    DeviceLogDto deviceLogDto = new DeviceLogDto(1,deviceLibraryEntity.getId(),"添加配套设备审核成功",null);
                    deviceLogService.addLog(deviceLogDto);
                    matchingDeviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("审核通过新增成功");
        }
        //2.审核失败
        if (matchingDeviceBillConfirmVo.getStatus()==1){
            taskService.update(taskService.moveToArchive(taskBto));
            //添加日业务志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"添加配套设备审核失败",null);
            taskLogService.addLog(taskLogBto);
            //更新账单状态
            MatchingDeviceBill matchingDeviceBillEntity = matchingDeviceBillService.getOne(taskBto.getBillId());
            matchingDeviceBillEntity.setBillStatus(1);
            matchingDeviceBillService.update(matchingDeviceBillEntity);
            //改变设备状态，增加日志
            List<Integer> list = StringSplitUtil.userIdSplit(matchingDeviceBillEntity.getDeviceDetail());
            if (!list.isEmpty()) {
                for (Integer d : list) {
                    MatchingDeviceLibrary deviceLibraryEntity = matchingDeviceLibraryService.getOne(d);
                    deviceLibraryEntity.setLifeStatus(1);
                    DeviceLogDto deviceLogDto = new DeviceLogDto(1,deviceLibraryEntity.getId(),"添加配套设备审核失败",null);
                    deviceLogService.addLog(deviceLogDto);
                    matchingDeviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("入库审核失败");
        }
        else {
            return ResultUtil.success("status只能为0或1");
        }
    }

    @ApiOperation(value = "模糊查询配套装备分页",notes = "可以通过这个接口查询装备列表")
    @PostMapping("/feature/summary")
    public ResponseEntity<Page<MatchingDeviceLibrary>> getAll(@RequestBody MatchingDeviceSelectVo matchingDeviceSelectVo){
        Page<MatchingDeviceLibrary> page = matchingDeviceLibraryService.getPage(matchingDeviceSelectVo,matchingDeviceSelectVo.getPageable());
        //set关联装备的表面号
        for (MatchingDeviceLibrary m:page.getContent()) {
            if (m.getDeviceId()>0) {
                m.setRelateDevice(deviceLibraryService.getOne(m.getDeviceId()).getRfidSurfaceId());
            }
        }
        return ResultUtil.success(page);
    }

    @ApiOperation(value = "查询配套装备详情",notes = "可以通过这个接口查询配套装备详情")
    @GetMapping("/feature/detail/{id}")
    public ResponseEntity<MacthingDeviceDetailVo> getDetail(@PathVariable("id") int id){
        MacthingDeviceDetailVo macthingDeviceDetailVo = new MacthingDeviceDetailVo();
        //添加配套设备详情
        MatchingDeviceLibrary m = matchingDeviceLibraryService.getOne(id);
        macthingDeviceDetailVo.setMatchingDeviceLibrary(m);
        //添加关联装备详情
        if (m.getDeviceId()!=0){
            macthingDeviceDetailVo.setDeviceLibrary(deviceLibraryService.getOne(m.getDeviceId()));
        }
        //添加设备履历日志
        List<DeviceLogUserVo> deviceLogs = deviceLogDao.getAllByDeviceIdAndType(id,1).stream()
                .map(DeviceLog::parse2Dto)
                .map(DeviceLogDto::toVo)
                .sorted(Comparator.comparing(DeviceLogUserVo::getCreateTime))
                .collect(Collectors.toList());
        macthingDeviceDetailVo.setDeviceLogUserVos(deviceLogs);
        return ResultUtil.success(macthingDeviceDetailVo);
    }

    @ApiOperation(value = "更新配套设备",notes = "可以通过这个接口更新配套设备")
    @PostMapping("/update")
    public ResponseEntity<String> update(@RequestBody MatchingDeviceEditVo matchingDeviceEditVo) {
        MatchingDeviceLibrary m = matchingDeviceLibraryService.getOne(matchingDeviceEditVo.getMatchingDeviceId());
        if (matchingDeviceEditVo.getCreateUnit()!=null){
            m.setCreateUnit(matchingDeviceEditVo.getCreateUnit());
        }
        if (matchingDeviceEditVo.getLifeStatus()!=null){
            m.setLifeStatus(matchingDeviceEditVo.getLifeStatus());
        }
        if (matchingDeviceEditVo.getDeviceId()!=null&&m.getDeviceId()==0){
            m.setDeviceId(matchingDeviceEditVo.getDeviceId());
        }
        if (matchingDeviceEditVo.getModel()!=null){
            m.setModel(matchingDeviceEditVo.getModel());
        }
        if (matchingDeviceEditVo.getName()!=null){
            m.setName(matchingDeviceEditVo.getName());
        }
        if (matchingDeviceEditVo.getSeqNumber()!=null){
            m.setSeqNumber(matchingDeviceEditVo.getSeqNumber());
        }
        if (matchingDeviceEditVo.getType()!=null){
            m.setType(matchingDeviceEditVo.getType());
        }
        matchingDeviceLibraryService.update(m);
        return ResultUtil.success("修改成功");
    }

    @ApiOperation(value = "查询新增配套任务详情",notes = "可以通过这个接口查询新增配套任务详情")
    @GetMapping(value = "/detail/{billId}")
    public ResponseEntity<MacthingDetailVo> selectDetail(@PathVariable("billId") int billId){
        MacthingDetailVo macthingDetailVo = new MacthingDetailVo();
        //获取业务
        TaskBto taskBto = taskService.get(billId, BusinessEnum.ADD_MATCHING_DEVICE.id);
        //获取账单
        MatchingDeviceBill matchingDeviceBillEntity = matchingDeviceBillService.getOne(billId);
        macthingDetailVo.setMatchingDeviceBill(matchingDeviceBillEntity);
        //获取设备
        List<Integer> integerList = StringSplitUtil.userIdSplit(matchingDeviceBillEntity.getDeviceDetail());
        List<MatchingDeviceLibrary> matchingDeviceLibraryEntities = new ArrayList<>();
        if (integerList.size()>0){
            for (Integer id:integerList) {
                if (id>0){
                    matchingDeviceLibraryEntities.add(matchingDeviceLibraryService.getOne(id));
                }
            }
        }
        macthingDetailVo.setMatchingDeviceLibraries(matchingDeviceLibraryEntities);
        //获取业务日志
        macthingDetailVo.setTaskLogUserVos(taskLogService.getByTaskId(taskBto.getId()));
        return ResultUtil.success(macthingDetailVo);
    }
}
