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

import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.allot.service.AllotBillService;
import com.tykj.dev.device.allot.subject.domin.AllotBill;
import com.tykj.dev.device.allot.subject.vo.AllotBillConfirmVo;
import com.tykj.dev.device.allot.subject.vo.AllotBillSaveVo;
import com.tykj.dev.device.allot.subject.vo.AllotReceiveConfirmVo;
import com.tykj.dev.device.allot.subject.vo.AllotReceiveVo;
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.vo.FileVo;
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.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.base.ResultObj;
import com.tykj.dev.misc.utils.TimestampUtil;
import com.tykj.dev.socket.MyWebSocket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/allot")
@AutoDocument
@Api(tags = "装备配发模块",description = "装备配发接口")
public class AllotBillController {

    @Autowired
    private AllotBillService allotBillService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TaskService taskService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private MyWebSocket myWebSocket;

    @ApiOperation(value = "发起配发业务", notes = "可以通过这个接口发起配发任务")
    @PostMapping(value = "/addAllotBill")
    public ResponseEntity addAllotBill(@RequestBody AllotBillSaveVo allotBillSaveVo) {
        //1.添加配发单
        AllotBill a = allotBillSaveVo.toDo();
        a.setSendUseraId(userUtils.getCurrentUserId());
        AllotBill allotBillEntity = allotBillService.addEntity(a);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(allotBillEntity.getCreateTime());
        int year = calendar.get(Calendar.YEAR);
        String num = "NO:第" + year + "PF" + allotBillEntity.getId() + "号";
        allotBillEntity.setNum(num);
        allotBillService.update(allotBillEntity);
        Integer billId = allotBillEntity.getId();
        Integer userId = userUtils.getCurrentUserId();
        String deviceIdDetail = allotBillEntity.getAllotCheckDetail();
        //2.发起任务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(allotBillSaveVo.getSendUserbId());
        TaskBto taskBto = new TaskBto(StatusEnum.ALLOT_SEND_CONFIRM.id,"配发业务",null,".",billId,3,userUtils.getCurrentUnitId(),1,null,userIds);
        Task saveEntity = taskService.start(taskBto);
        //存业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("出库确认单",allotBillEntity.getFileName(),allotBillEntity.getFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(saveEntity.getId(),"对"+allotBillEntity.getReceiveUnit()+"发起配发",fileVoList);
        taskLogService.addLog(taskLogBto);
        //存装备日志
        String[] strings = deviceIdDetail.split("x");
        for (String s:strings) {
            if (s.length()>=2) {
                Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                DeviceLogDto deviceLogDto = new DeviceLogDto(id,"对"+allotBillEntity.getReceiveUnit()+"发起配发",fileVoList);
                deviceLogService.addLog(deviceLogDto);
            }
        }
        myWebSocket.sendMessage1();
        return ResponseEntity.ok(new ResultObj(allotBillEntity,"发起成功"));
    }

    @ApiOperation(value = "配发审核", notes = "可以通过这个接口对配发审核")
    @PostMapping(value = "/allotConfirm")
    public ResponseEntity allotConfirm(@RequestBody AllotBillConfirmVo allotBillConfirmVo) {
        TaskBto taskBto = taskService.get(allotBillConfirmVo.getTaskId());
        //1.审核通过，改变装备状态，审核任务完成，发起新的配发接收任务
        if (allotBillConfirmVo.getStatus() == 0) {
            //更新账单状态
            AllotBill allotBillEntity = allotBillService.getOne(taskBto.getBillId());
            allotBillEntity.setAllotStatus(2);
            allotBillEntity.setSendTime(TimestampUtil.getCurrentTimestamp());
            allotBillService.update(allotBillEntity);
            //task推至下一阶段
            TaskBto taskBto1 = taskService.moveToNext(taskBto, allotBillEntity.getReceiveUseraId());
            taskBto1.setOwnUnit(userPublicService.findUnitIdByName(allotBillEntity.getReceiveUnit()));
            taskService.update(taskBto1);
            //存业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"审核成功并出库",null);
            taskLogService.addLog(taskLogBto);
            //获取装备信息
            String deviceIdDetail = allotBillEntity.getAllotCheckDetail();
            String[] strings = deviceIdDetail.split("x");
            for (String s:strings) {
                if (s.length()>=2) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //改变装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(3);
                    deviceLibraryEntity.setManageStatus(0);
                    //存装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"审核成功并出库",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("配发审核通过");
        }
        //2.审核失败
        if (allotBillConfirmVo.getStatus()==1){
            //业务封存
            taskService.update(taskService.moveToArchive(taskBto));
            //存业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"配发出库审核失败",null);
            taskLogService.addLog(taskLogBto);
            //更新账单状态
            AllotBill allotBillEntity = allotBillService.getOne(taskBto.getBillId());
            allotBillEntity.setAllotStatus(1);
            allotBillService.update(allotBillEntity);
            String deviceIdDetail = allotBillEntity.getAllotCheckDetail();
            String[] strings = deviceIdDetail.split("x");
            //添加装备日志
            for (String s:strings) {
                if (s.length()>=2) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"配发出库审核失败",null);
                    deviceLogService.addLog(deviceLogDto);
                }
            }
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("配发审核失败");
        }
        else {
            return ResponseEntity.ok("status只能为0或1");
        }
    }

    @ApiOperation(value = "接收配发装备", notes = "可以通过这个接口接收配发装备")
    @PostMapping(value = "/receiveDevice")
    public ResponseEntity receiveDevice(@RequestBody AllotReceiveVo allotReceiveVo) {
        //获取当前任务，推至下一阶段
        TaskBto taskBto = taskService.get(allotReceiveVo.getTaskId());
        taskService.update(taskService.moveToNext(taskBto, allotReceiveVo.getReceiveUserbId()));
        AllotBill allotBillEntity = allotBillService.getOne(taskBto.getBillId());
        //添加业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("配发单", allotBillEntity.getBillFileName(), allotBillEntity.getBillFileUrl()));
        fileVoList.add(new FileVo("入库确认单", allotBillEntity.getReceiveFileName(), allotBillEntity.getReceiveFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(), "接收并发起入库", fileVoList);
        taskLogService.addLog(taskLogBto);
        //更新账单状态
        allotBillEntity.setAllotStatus(3);
        BeanUtils.copyProperties(allotReceiveVo,allotBillEntity);
        allotBillEntity.setReceiveTime(TimestampUtil.getCurrentTimestamp());
        allotBillService.update(allotBillEntity);
        //分隔装备id信息
        String deviceIdDetail = allotReceiveVo.getReceiveCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        for (String s:strings) {
            if (s.length()>=2) {
                //接收无误
                if ("1".equals(s.substring(s.length() - 1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //改变装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(0);
                    deviceLibraryEntity.setLocationUnit(userUtils.getCurrentUserUnitName());
                    //存装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"接收并发起入库",fileVoList);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
                //接收缺失
                if ("0".equals(s.substring(s.length() - 1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //改变装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(11);
                    //存装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"接收入库丢失",fileVoList);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
        }
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("配发接收入库");
    }

    @ApiOperation(value = "接收配发装备审核", notes = "可以通过这个接口对接收配发装备审核")
    @PostMapping(value = "/receiveConfirm")
    public ResponseEntity receiveConfirm(@RequestBody AllotReceiveConfirmVo allotReceiveConfirmVo) {
        //获取任务和账单
        TaskBto taskBto = taskService.get(allotReceiveConfirmVo.getTaskId());
        AllotBill allotBillEntity = allotBillService.getOne(taskBto.getBillId());
        String deviceIdDetail = allotBillEntity.getReceiveCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        //审核通过
        if (allotReceiveConfirmVo.getStatus() == 0) {
            //业务完结
            taskService.update(taskService.moveToEnd(taskBto));
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(), "审核成功并入库", null);
            taskLogService.addLog(taskLogBto);
            //更新账单
            allotBillEntity.setAllotStatus(5);
            allotBillService.update(allotBillEntity);
            for (String s:strings) {
                //改变接收无误的装备的状态
                if (s.length()>=2&& "1".equals(s.substring(s.length()-1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(2);
                    deviceLibraryEntity.setOwnUnit(userUtils.getCurrentUserUnitName());
                    deviceLibraryEntity.setManageStatus(1);
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"审核成功并入库",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("入库审核通过配发接收成功");
        }
        //审核失败
        if (allotReceiveConfirmVo.getStatus()==1){
            //业务封存
            taskService.update(taskService.moveToArchive(taskBto));
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"配发入库审核失败",null);
            taskLogService.addLog(taskLogBto);
            //更新账单状态
            AllotBill allotBillEntity2 = allotBillService.getOne(taskBto.getBillId());
            allotBillEntity2.setAllotStatus(4);
            allotBillService.update(allotBillEntity2);
            for (String s:strings) {
                //改变接收无误的装备的状态
                if (s.length()>=2&& "1".equals(s.substring(s.length()-1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(1);
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"配发入库审核失败",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("配发接收入库审核失败");
        }
        else {
            return ResponseEntity.ok("status只能为0或1");
        }
    }
}
