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

import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.library.repository.DeviceLibraryDao;
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.selfcheck.service.SelfCheckBillService;
import com.tykj.dev.device.selfcheck.subject.domin.SelfCheckBill;
import com.tykj.dev.device.selfcheck.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.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.List;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/selfCheck")
@AutoDocument
@Api(tags = "自查模块",description = "自查接口")
public class SelfCheckController {

    @Autowired
    private SelfCheckBillService selfExaminationBillService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TaskService taskService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private DeviceLibraryDao deviceLibraryDao;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private MyWebSocket myWebSocket;

    @ApiOperation(value = "装备比较",notes = "可以通过这个接口发起比较装备")
    @PostMapping(value = "/compare")
    public ResponseEntity<CompareResultVo> compare(@RequestBody CompareVo compareVo){
        List<Integer> list = compareVo.getDeivceIdList();
        List<String> list1 = new ArrayList<>();
        List<DeviceLibrary> deviceLibraryEntities = new ArrayList<>();
        List<DeviceLibrary> newList = new ArrayList<>();
        List<DeviceLibrary> resultList = new ArrayList<>();
        for (Integer id:list) {
            DeviceLibrary d = deviceLibraryService.getOne(id);
            //list1存应查装备rfid卡号
            list1.add(d.getRfidCardId());
            //deviceLibraryEntities存应查装备
            deviceLibraryEntities.add(d);
        }
        //list2存扫码得到的rfid卡号
        List<String> list2 = compareVo.getRfidResultList();
        //取交集
        list1.retainAll(list2);
        //遍历应查装备
        for (DeviceLibrary d:deviceLibraryEntities) {
            //如果在交集中，检查结果为正常
            if (list1.contains(d.getRfidCardId())){
                d.setCheckResult(1);
            }
            //否则检查结果为丢失
            else {
                d.setCheckResult(0);
            }
        }
        //遍历扫码结果
        for (String s:list2) {
            //如果不在交集中，则为新增
            if (!list1.contains(s)){
                List<DeviceLibrary> d = deviceLibraryDao.getAllByRfidCardId(s);
                //如果新增的为系统中存在的装备
                if (d.size()>0) {
                    for (DeviceLibrary deviceLibraryEntity:d) {
                        deviceLibraryEntity.setCheckResult(2);
                        resultList.add(deviceLibraryEntity);
                    }
                }
                //如果为系统中不存在的装备，添加到newList
                if (d.isEmpty()){
                    DeviceLibrary deviceLibraryEntity = new DeviceLibrary();
                    deviceLibraryEntity.setCheckResult(2);
                    deviceLibraryEntity.setSeqNumber("-");
                    deviceLibraryEntity.setName("-");
                    deviceLibraryEntity.setType(0);
                    deviceLibraryEntity.setModel("-");
                    deviceLibraryEntity.setRfidSurfaceId("-");
                    deviceLibraryEntity.setProdNumber("-");
                    deviceLibraryEntity.setRfidCardId(s);
                    newList.add(deviceLibraryEntity);
                }
            }
        }
        //在新增后面加丢失的装备
        for (DeviceLibrary d:deviceLibraryEntities) {
            if (d.getCheckResult()==0){
                resultList.add(d);
            }
        }
        //最后加正常的装备
        for (DeviceLibrary d:deviceLibraryEntities) {
            if (d.getCheckResult()==1){
                resultList.add(d);
            }
        }
        CompareResultVo compareResultVo = new CompareResultVo();
        compareResultVo.setNewList(newList);
        compareResultVo.setResultList(resultList);
        return ResultUtil.success(compareResultVo);
    }

    @ApiOperation(value = "发起自查业务",notes = "可以通过这个接口发起自查业务")
    @PostMapping(value = "/addBill")
    public ResponseEntity<SelfCheckBill> addSelfExaminationBill(@RequestBody SelfCheckSaveVo selfCheckSaveVo) {
        //添加账单
        SelfCheckBill selfExaminationBillEntity = selfCheckSaveVo.toDo();
        selfExaminationBillEntity.setTitle(userUtils.getCurrentUserUnitName()+"发起的自查任务");
        selfExaminationBillEntity.setUseraId(userUtils.getCurrentUserId());
        selfExaminationBillEntity.setCheckUnit(userUtils.getCurrentUserUnitName());
        selfExaminationBillEntity.setCreateUnitId(userUtils.getCurrentUnitId());
        if (selfCheckSaveVo.getNewDeviceList()!=null) {
            //按新增不在系统的装备按rfid卡号拼接保存
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(".");
            for (String s : selfCheckSaveVo.getNewDeviceList()) {
                stringBuffer.append(s);
                stringBuffer.append(".");
            }
            selfExaminationBillEntity.setNewDeviceDetail(stringBuffer.toString());
        }
        SelfCheckBill selfExaminationBillEntity1 = selfExaminationBillService.addEntity(selfExaminationBillEntity);
        Integer userId = userUtils.getCurrentUserId();
        String deviceIdDetail = selfExaminationBillEntity.getCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        //发起任务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(selfExaminationBillEntity1.getUserbId());
        TaskBto taskBto = new TaskBto(StatusEnum.SELF_CHECK_CONFIRM.id,"自查业务",null,".",selfExaminationBillEntity1.getId(),4,userUtils.getCurrentUnitId(),1,null,userIds);
        Task saveEntity = taskService.start(taskBto);
        //存业务日志
        TaskLogBto taskLogBto = new TaskLogBto(saveEntity.getId(),"发起自查",null);
        taskLogService.addLog(taskLogBto);
        //添加装备日志
        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 ResultUtil.success(selfExaminationBillEntity1);
    }

    @ApiOperation(value = "自查审核",notes = "可以通过这个接口自查审核")
    @PatchMapping(value = "/selfExaminationConfirm")
    public ResponseEntity<String> selfExaminationConfirm(@RequestBody SelfCheckConfirmVo selfCheckConfirmVo){
        TaskBto taskBto = taskService.get(selfCheckConfirmVo.getTaskId());
        SelfCheckBill selfExaminationBillEntity = selfExaminationBillService.getOne(taskBto.getBillId());
        String deviceIdDetail = selfExaminationBillEntity.getCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        //审核通过，改变账单和任务状态，发起确认的任务
        if (selfCheckConfirmVo.getStatus()==0){
            taskService.update(taskService.moveToEnd(taskBto));
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"自查审核成功",null);
            taskLogService.addLog(taskLogBto);
            selfExaminationBillEntity.setCheckStatus(2);
            selfExaminationBillService.update(selfExaminationBillEntity);
            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 ResultUtil.success("审核通过自查完成");
        }
        //审核不通过，改变账单和任务状态
        if (selfCheckConfirmVo.getStatus()==1){
            taskService.update(taskService.moveToArchive(taskBto));
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"自查审核失败",null);
            taskLogService.addLog(taskLogBto);
            selfExaminationBillEntity.setCheckStatus(1);
            selfExaminationBillService.update(selfExaminationBillEntity);
            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 ResultUtil.success("自查审核失败");
        }
        else {
            return ResultUtil.failed("status只能为0或1");
        }
    }

    @ApiOperation(value = "查询自查任务",notes = "可以通过这个接口查询自查任务")
    @PostMapping(value = "/summary")
    public ResponseEntity<Page<SelfCheckBill>> selectSelfExaminationBill(@RequestBody SelfCheckSelectVo selfCheckSelectVo){
        Page<SelfCheckBill> page = selfExaminationBillService.getPage(selfCheckSelectVo, selfCheckSelectVo.getPageable());
        for (SelfCheckBill s:page.getContent()) {
            s.setCreateUnit(userPublicService.findByUnitsToname(s.getCreateUnitId()));
            String user = userPublicService.getOne(s.getUseraId()).getName();
            String user2 = userPublicService.getOne(s.getUserbId()).getName();
            String user3 = userPublicService.getOne(s.getCreateUserId()).getName();
            s.setCheckUser(user);
            s.setConfirmUser(user2);
            s.setCreateUser(user3);
        }
        return ResultUtil.success(page);
    }

    @ApiOperation(value = "查询自查任务详情",notes = "可以通过这个接口查询自查任务详情")
    @GetMapping(value = "/detail/{billId}")
    public ResponseEntity<SelfCheckDetailVo> selectDetail(@PathVariable("billId") int billId){
        SelfCheckDetailVo selfCheckDetailVo = new SelfCheckDetailVo();
        //获取业务
        TaskBto taskBto = taskService.get(billId, BusinessEnum.SELF_CHECK.id);
        //获取账单
        SelfCheckBill selfExaminationBillEntity = selfExaminationBillService.getOne(billId);
        if (selfExaminationBillEntity.getUseraId()!=0) {
            selfExaminationBillEntity.setCheckUser(userPublicService.getOne(selfExaminationBillEntity.getUseraId()).getName());
        }
        if (selfExaminationBillEntity.getUserbId()!=0) {
            selfExaminationBillEntity.setConfirmUser(userPublicService.getOne(selfExaminationBillEntity.getUserbId()).getName());
        }
        selfCheckDetailVo.setSelfCheckBill(selfExaminationBillEntity);
        //获取自查详情
        String str3 = selfExaminationBillEntity.getCheckDetail();
        String str4 = selfExaminationBillEntity.getNewDeviceDetail();
        String[] split = str3.split("x");
        //添加新增不在系统的装备
        if (str4!=null) {
            //分隔字符获得rfid卡号
            String[] split2 = str4.split("\\.");
            List<DeviceLibrary> newDeviceList = new ArrayList<>();
            for (String rfid:split2){
                if (rfid.length()>0){
                    DeviceLibrary d = new DeviceLibrary();
                    d.setCheckResult(2);
                    d.setSeqNumber("-");
                    d.setName("-");
                    d.setType(0);
                    d.setRfidSurfaceId("-");
                    d.setProdNumber("-");
                    d.setRfidCardId(rfid);
                    newDeviceList.add(d);
                }
            }
            selfCheckDetailVo.setNewDeviceList(newDeviceList);
        }
        List<DeviceLibrary> libraryEntities1 = new ArrayList<>();
        //添加自查装备
        for (String s:split) {
            if (s.length()>=2) {
                Integer i = Integer.parseInt(s.substring(0, s.length() - 1));
                Integer checkResult = Integer.parseInt(s.substring(s.length()-1));
                DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(i);
                deviceLibraryEntity.setCheckResult(checkResult);
                libraryEntities1.add(deviceLibraryEntity);
            }
        }
        selfCheckDetailVo.setCheckDeviceList(libraryEntities1);
        //添加业务日志
        selfCheckDetailVo.setTaskLogUserVos(taskLogService.getByTaskId(taskBto.getId()));
        return ResultUtil.success(selfCheckDetailVo);
    }

}
