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

import com.tykj.dev.config.swagger.AutoDocument;
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.DeviceLibrarySaveVo;
import com.tykj.dev.device.packing.service.PackingLibraryService;
import com.tykj.dev.device.packing.subject.domin.PackingLibrary;
import com.tykj.dev.device.storage.service.StorageBillService;
import com.tykj.dev.device.storage.subject.domin.StorageBill;
import com.tykj.dev.device.storage.subject.vo.StorageBillConfirmVo;
import com.tykj.dev.device.storage.subject.vo.StorageBillDetailVo;
import com.tykj.dev.device.storage.subject.vo.StorageBillSaveVo;
import com.tykj.dev.device.storage.subject.vo.StorageDetailVo;
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.library.subject.vo.FileVo;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/storage")
@AutoDocument
@Api(tags = "装备入库模块",description = "装备入库接口")
public class StorageBillController {
    @Autowired
    private StorageBillService storageBillService;

    @Autowired
    TaskService taskService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private PackingLibraryService packingLibraryService;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private MyWebSocket myWebSocket;

    @ApiOperation(value = "选择入库型号数量",notes = "可以通过这个接口选择入库型号数量")
    @PostMapping(value = "/addStorageDetail")
    public ResponseEntity<List<PackingLibrary>> addStorageDetail(@RequestBody List<StorageBillDetailVo> list) {
        List<PackingLibrary> libraryEntities=new ArrayList<>();
        Map<Integer,Integer> map=new HashMap<>();
        for (StorageBillDetailVo s:list) {
            int count=1;
            Integer deviceNum = s.getStorageCount();
            while (deviceNum>=count) {
                PackingLibrary packingLibraryEntity=new PackingLibrary();
                BeanUtils.copyProperties( packingLibraryService.getOne(s.getPackingId()),packingLibraryEntity);
                packingLibraryEntity.setCorresponding(count);
                libraryEntities.add(packingLibraryEntity);
                if (s.getList()!=null && s.getList().size()!=0) {
                    for (StorageBillDetailVo s2 : s.getList()) {
                        packingLibraryEntity = packingLibraryService.getOne(s2.getPackingId());
                        if (s2.getStorageCount() >= count) {
                            packingLibraryEntity.setCorresponding(count);
                            libraryEntities.add(packingLibraryEntity);
                        }
                        if (s2.getStorageCount() > deviceNum) {
                            map.put(s2.getPackingId(), s2.getStorageCount()-deviceNum);
                        }
                    }

                }
                count=count+1;
            }
        }
        for (Integer i:map.keySet()){
            for (int j=1;j<=map.get(i);j++) {
                PackingLibrary packingLibraryEntity = packingLibraryService.getOne(i);
                packingLibraryEntity.setCorresponding(0);
                libraryEntities.add(packingLibraryEntity);
            }
        }
        return ResultUtil.success(libraryEntities);
    }

    @ApiOperation(value = "添加入库单",notes = "可以通过这个接口发起入库业务")
    @PostMapping(value = "/addStorageBill")
    public ResponseEntity<StorageBill> addStorageBill(@RequestBody StorageBillSaveVo storageBillSaveVo) {
        //1.存入库单
        Integer userId = userUtils.getCurrentUserId();
        StorageBill storageBillEntity = storageBillService.addEntity(storageBillSaveVo.toDo());
        Integer storageBillId = storageBillEntity.getId();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("x");
        //2.发起入库任务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(storageBillSaveVo.getReceiveUserbId());
        TaskBto taskBto = new TaskBto(StatusEnum.STORAGE_CONFIRM.id,"入库业务",null,".",storageBillEntity.getId(),2,userUtils.getCurrentUnitId(),1,null,userIds);
        Task taskEntity1 = taskService.start(taskBto);
        //存业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("配发单",storageBillEntity.getFileName(),storageBillEntity.getFileUrl()));
        fileVoList.add(new FileVo("入库确认单",storageBillEntity.getReceiveFileName(),storageBillEntity.getReceiveFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(taskEntity1.getId(),"发起入库",fileVoList);
        taskLogService.addLog(taskLogBto);
        //3.存装备
        Integer parentId = null;
        for (DeviceLibrarySaveVo d:storageBillSaveVo.getDeviceLibrarySaveVoList()) {
            DeviceLibrary saveEntity = new DeviceLibrary();
            DeviceLibrary deviceLibraryEntity = new DeviceLibrary();
            PackingLibrary packingLibraryEntity = packingLibraryService.getOne(d.getPackingId());
            BeanUtils.copyProperties(packingLibraryEntity,deviceLibraryEntity);
            deviceLibraryEntity.setId(null);
            deviceLibraryEntity.setLifeStatus(0);
            BeanUtils.copyProperties(d,deviceLibraryEntity);
            deviceLibraryEntity.setStorageBillId(storageBillId);
            deviceLibraryEntity.setLocationUnit(userUtils.getCurrentUserUnitName());
            deviceLibraryEntity.setOwnUnit(userUtils.getCurrentUserUnitName());
            //如果不是单独的配件，设置父装备id为上一个装备的id
            if (d.getIsSinglePart()==0) {
                if (deviceLibraryEntity.getIsPart() == 0) {
                    saveEntity = deviceLibraryService.addEntity(deviceLibraryEntity);
                    parentId = saveEntity.getId();
                }
                if (deviceLibraryEntity.getIsPart() == 1) {
                    deviceLibraryEntity.setPartParentId(parentId);
                    saveEntity = deviceLibraryService.addEntity(deviceLibraryEntity);
                }
            }
            //如果是单独的配件，不用设置父装备id
            else {
                saveEntity = deviceLibraryService.addEntity(deviceLibraryEntity);
            }
            stringBuffer.append(saveEntity.getId());
            //存装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(saveEntity.getId(),"发起入库",fileVoList);
            deviceLogService.addLog(deviceLogDto);
            stringBuffer.append("x");
        }
        //4.更新入库单入库详情
        storageBillEntity.setStorageDetail(stringBuffer.toString());
        myWebSocket.sendMessage1();
        return ResultUtil.success(storageBillService.update(storageBillEntity));
    }

    @ApiOperation(value = "入库审核",notes = "可以通过这个接口入库审核")
    @PostMapping(value = "/confirmStorageBill")
    public ResponseEntity<String> confirmStorageBill(@RequestBody StorageBillConfirmVo storageBillConfirmVo) {
        TaskBto taskBto = taskService.get(storageBillConfirmVo.getTaskId());
        //1.审核成功,入库任务结束，发起新的确认任务,改变装备状态
        if(storageBillConfirmVo.getStatus()==0){
            taskService.update(taskService.moveToEnd(taskBto));
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"入库审核成功",null);
            taskLogService.addLog(taskLogBto);
            StorageBill storageBillEntity = storageBillService.getOne(taskBto.getBillId());
            storageBillEntity.setStorageStatus(2);
            storageBillService.update(storageBillEntity);
            List<DeviceLibrary> libraryEntities = deviceLibraryService.getListByBillId(taskBto.getBillId());
            //改变装备状态，添加装备日志
            for (DeviceLibrary d:libraryEntities) {
                d.setLifeStatus(2);
                DeviceLogDto deviceLogDto = new DeviceLogDto(d.getId(),"入库审核成功",null);
                deviceLogService.addLog(deviceLogDto);
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("审核通过入库成功");
        }
        //2.审核失败
        if (storageBillConfirmVo.getStatus()==1){
            taskService.update(taskService.moveToArchive(taskBto));
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"入库审核失败",null);
            taskLogService.addLog(taskLogBto);
            StorageBill storageBillEntity = storageBillService.getOne(taskBto.getBillId());
            storageBillEntity.setStorageStatus(1);
            storageBillService.update(storageBillEntity);
            List<DeviceLibrary> libraryEntities = deviceLibraryService.getListByBillId(taskBto.getBillId());
            //改变装备状态，添加装备日志
            for (DeviceLibrary d:libraryEntities) {
                d.setLifeStatus(1);
                DeviceLogDto deviceLogDto = new DeviceLogDto(d.getId(),"入库审核失败",null);
                deviceLogService.addLog(deviceLogDto);
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("入库审核失败");
        }
        else {
            return ResultUtil.failed("status只能为0或1");
        }
    }

    @ApiOperation(value = "查询入库详情",notes = "可以通过这个接口查询入库详情")
    @GetMapping(value = "/detail/{billId}")
    public ResponseEntity<StorageDetailVo> selectDetail(@PathVariable("billId") int billId) {
        StorageDetailVo storageDetailVo = new StorageDetailVo();
        //获取taskBto和账单
        TaskBto taskBto = taskService.get(billId, BusinessEnum.STORAGE.id);
        StorageBill storageBillEntity = storageBillService.getOne(billId);
        storageBillEntity.setReceiveUserA(userPublicService.getOne(storageBillEntity.getReceiveUseraId()).getName());
        storageBillEntity.setReceiveUserB(userPublicService.getOne(storageBillEntity.getReceiveUserbId()).getName());
        storageDetailVo.setStorageBill(storageBillEntity);
        String str = storageBillEntity.getStorageDetail();
        List<Integer> list1= StringSplitUtil.userIdSplit(str);
        //获取入库装备
        List<DeviceLibrary> libraryEntities = new ArrayList<>();
        for (Integer deviceId:list1) {
            DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(deviceId);
            libraryEntities.add(deviceLibraryEntity);
        }
        storageDetailVo.setDeviceLibraryList(libraryEntities);
        //获取业务日志
        storageDetailVo.setTaskLogUserVos(taskLogService.getByTaskId(taskBto.getId()));
        return ResultUtil.success(storageDetailVo);
    }
}
