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

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.ScriptSaveVo;
import com.tykj.dev.device.repair.repository.RepairDetailDao;
import com.tykj.dev.device.repair.repository.RepairSendBillDao;
import com.tykj.dev.device.repair.service.RepairBackBillService;
import com.tykj.dev.device.repair.service.RepairBillService;
import com.tykj.dev.device.repair.service.RepairDetailService;
import com.tykj.dev.device.repair.subject.domin.RepairBackBill;
import com.tykj.dev.device.repair.subject.domin.RepairBill;
import com.tykj.dev.device.repair.subject.domin.RepairDetail;
import com.tykj.dev.device.repair.subject.domin.RepairSendBill;
import com.tykj.dev.device.repair.subject.vo.*;
import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.task.subject.vo.TaskSelectVo;
import com.tykj.dev.device.task.subject.vo.TaskUserVo;
import com.tykj.dev.device.task.utils.TaskUtils;
import com.tykj.dev.device.user.subject.service.UserPublicService;
import com.tykj.dev.misc.base.RepairStatusEnum;
import com.tykj.dev.misc.utils.JacksonUtil;
import com.tykj.dev.misc.utils.PageUtil;
import com.tykj.dev.misc.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/business")
@AutoDocument
@Api(tags = "业务模块", description = "业务模块")
@Slf4j
public class RepairBillSelectController {

    @Autowired
    private RepairBillService repairBillService;

    @Autowired
    private RepairBackBillService repairBackBillService;

    @Autowired
    private RepairSendBillDao repairSendBillDao;

    @Autowired
    private RepairDetailDao repairDetailDao;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private RepairDetailService repairDetailService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskUtils taskUtils;

    @Autowired
    private RepairController repairController;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private DeviceLibraryDao deviceLibraryDao;

    @ApiOperation(value = "查询工作台维修装备数量", notes = "可以通过这个接口查询工作台维修装备数量")
    @GetMapping(value = "/repairNum")
    public ResponseEntity getRepairNum(){
        //返回数量对象
        RepairNum repairNum = new RepairNum();
        //查询器
        RepairTaskSelectVo repairTaskSelectVo = new RepairTaskSelectVo(1,null);
        repairTaskSelectVo.setPage(0);
        repairTaskSelectVo.setSize(Integer.MAX_VALUE);
        //type=1的记录
        Page<RepairDetail> repairDetails = (Page)repairController.getRepairList(repairTaskSelectVo).getBody();
        //type=2的记录
        repairTaskSelectVo.setType(2);
        Page<WaitingRepairEquipmentVo> waitingRepaireEquipmentVos = (Page) repairController.getRepairList(repairTaskSelectVo).getBody();

        //        Page<RepairDetail> repairDetails2 = (Page)repairController.getRepairList(repairTaskSelectVo).getBody();
        //type=3的记录
        repairTaskSelectVo.setType(3);
//        Page<RepairDetail> repairDetails3 = (Page)repairController.getRepairList(repairTaskSelectVo).getBody();
        Page<WaitingRepairEquipmentVo> waitingRepaireEquipmentVos2 = (Page) repairController.getRepairList(repairTaskSelectVo).getBody();
        //set数量
        repairNum.setNum1(Long.valueOf(repairDetails.getTotalElements()).intValue());
//        repairNum.setNum2(Long.valueOf(repairDetails2.getTotalElements()).intValue());
//        repairNum.setNum3(Long.valueOf(repairDetails3.getTotalElements()).intValue());
        repairNum.setNum2(Long.valueOf(waitingRepaireEquipmentVos.getTotalElements()).intValue());
        repairNum.setNum3(Long.valueOf(waitingRepaireEquipmentVos2.getTotalElements()).intValue());
        return ResponseEntity.ok(repairNum);
    }

    @ApiOperation(value = "查询维修管理任务", notes = "可以通过这个接口查询查询维修管理任务")
    @PostMapping(value = "/repair")
    public ResponseEntity selectRepairTasks(@RequestBody TaskSelectVo taskSelectVo){
        List<TaskUserVo> taskUserVos;
        //如果是待办
        if (taskSelectVo.getSelectNum()==2){
            //筛选出状态为维修或领取待上传签收单的状态，状态为704或804\722\810
            taskUserVos = taskService.getManageList(taskSelectVo).stream().filter(taskUserVo -> taskUserVo.getBusinessType()==5||taskUserVo.getBusinessType()==10).collect(Collectors.toList());
        }
        else {
            taskUserVos = taskService.getManageList(taskSelectVo).stream().filter(taskUserVo -> taskUserVo.getBusinessType()==5||taskUserVo.getBusinessType()==10).collect(Collectors.toList());
        }
        return ResultUtil.success(PageUtil.getPerPage(taskSelectVo.getPage(), taskSelectVo.getSize(), taskUserVos, taskSelectVo.getPageable()));
    }

    @ApiOperation(value = "上传任务备注", notes = "可以通过这个接口上传任务备注")
    @PostMapping(value = "/remark")
    public ResponseEntity selectRepairTasks(@RequestBody TaskRemark taskRemark){
        TaskBto taskBto = taskService.get(taskRemark.getId());
        taskBto.setRemark(taskRemark.getRemark());
        taskService.update(taskBto);
        return ResponseEntity.ok("更新成功");
    }

    @ApiOperation(value = "查询维修单", notes = "可以通过这个接口查询维修单")
    @PostMapping(value = "/archives/repair/summary")
    public ResponseEntity selectRepairBill(@RequestBody RepairBillSelectVo repairBillSelectVo) {
        return ResultUtil.success(repairBillService.getPage(repairBillSelectVo, repairBillSelectVo.getPageable()));
    }

    @ApiOperation(value = "查询领取单", notes = "可以通过这个接口查询领取单")
    @PostMapping(value = "/archives/repairBack/summary")
    public ResponseEntity selectRepairBackBill(@RequestBody RepairBillSelectVo repairBillSelectVo) {
        Page<RepairBackBill> repairBackBills =repairBackBillService.getPage(repairBillSelectVo, repairBillSelectVo.getPageable());
        repairBackBills.getContent().forEach(repairBackBill -> {
            if (repairBackBill.getStartUseraId() != null) {
                repairBackBill.setStartUserA(userPublicService.getOne(repairBackBill.getStartUseraId()).getName());
            }
            repairBackBill.setStartUserB(repairBackBill.getAgent());
            if (repairBackBill.getReceiveUseraId() != null) {
                repairBackBill.setReceiveUserA(userPublicService.getOne(repairBackBill.getReceiveUseraId()).getName());
            }
            if (repairBackBill.getReceiveUserbId() != null) {
                repairBackBill.setReceiveUserB(userPublicService.getOne(repairBackBill.getReceiveUserbId()).getName());
            }
        });
        return ResultUtil.success(repairBackBills);
    }

    @ApiOperation(value = "查询维修单详情", notes = "可以通过这个接口查询维修单详情")
    @GetMapping(value = "/archives/repair/detail/{id}")
    public ResponseEntity selectRepairBillDetail(@PathVariable("id") int id) {
        Map<Integer,DeviceLibrary> deviceLibraryMap = deviceLibraryService.getAllDeviceMap();
        List<Object> list = new ArrayList<>();
        //获取维修单
        RepairBill repairBill = repairBillService.getOne(id);
        list.add(repairBill);
        //获取装备列表
        RepairSendBill repairSendBill = repairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
        repairSendBill.setSendFileList(FilesUtil.stringFileToList(repairSendBill.getSendFiles()));
        repairSendBill.setReceiveFileList(FilesUtil.stringFileToList(repairSendBill.getReceiveFiles()));
        if (repairSendBill.getScriptJson()!=null){
            repairSendBill.setScripts(JacksonUtil.readValue(repairSendBill.getScriptJson(),new TypeReference<List<ScriptSaveVo>>() {}));
        }
        list.add(repairSendBill);
        List<DeviceLibrary> deviceLibraries = new ArrayList<>();
        if (repairSendBill.getRepairDeviceCheckDetail() != null) {
            String[] strings1 = repairSendBill.getRepairDeviceCheckDetail().split("x");
            for (String s : strings1) {
                if (s.length() >= 2 && "1".equals(s.substring(s.length() - 1))) {
                    Integer deviceId = Integer.parseInt(s.substring(0, s.length() - 1));
                    Integer checkResult = Integer.parseInt(s.substring(s.length() - 1));
                    DeviceLibrary deviceLibraryEntity = deviceLibraryMap.get(deviceId);
                    deviceLibraryEntity.setCheckResult(checkResult);
                    deviceLibraries.add(deviceLibraryEntity);
                }
            }
        }
        //获取维修详情
        List<RepairDetail> repairDetails = getRepairDetail(repairBill.getId());
        //设置装备备注
        deviceLibraries.forEach(deviceLibrary -> {
            for (RepairDetail r : repairDetails) {
                if (r.getDeviceId().equals(deviceLibrary.getId())) {
                    deviceLibrary.setRemark(r.getRemark());
                    deviceLibrary.setRepairStatus(r.getRepairStatus());
                }
            }
        });
        list.add(deviceLibraries);
        return ResponseEntity.ok(list);
    }

    @ApiOperation(value = "查询领取单详情", notes = "可以通过这个接口查询领取单详情")
    @GetMapping(value = "/archives/repairBack/detail/{id}")
    public ResponseEntity selectRepairBackBillDetail(@PathVariable("id") int id) {
        Map<Integer,DeviceLibrary> deviceLibraryMap = deviceLibraryService.getAllDeviceMap();
        List<Object> list = new ArrayList<>();
        //获取维修单
        RepairBackBill repairBackBill = repairBackBillService.getOne(id);
        if (repairBackBill.getStartUseraId() != null) {
            repairBackBill.setStartUserA(userPublicService.getOne(repairBackBill.getStartUseraId()).getName());
        }
        repairBackBill.setStartUserB(repairBackBill.getAgent());
//        if (repairBackBill.getStartUserbId() != null) {
//            repairBackBill.setStartUserB(userPublicService.getOne(repairBackBill.getStartUserbId()).getName());
//        }
        if (repairBackBill.getReceiveUseraId() != null) {
            repairBackBill.setReceiveUserA(userPublicService.getOne(repairBackBill.getReceiveUseraId()).getName());
        }
        if (repairBackBill.getReceiveUserbId() != null) {
            repairBackBill.setReceiveUserB(userPublicService.getOne(repairBackBill.getReceiveUserbId()).getName());
        }
        if (repairBackBill.getScriptJson()!=null){
            repairBackBill.setScripts(JacksonUtil.readValue(repairBackBill.getScriptJson(),new TypeReference<List<ScriptSaveVo>>() {}));
        }
        list.add(repairBackBill);
        repairBackBill.setSendFileList(FilesUtil.stringFileToList(repairBackBill.getSendFiles()));
        repairBackBill.setReceiveFileList(FilesUtil.stringFileToList(repairBackBill.getReceiveFiles()));
        List<DeviceLibrary> deviceLibraries = new ArrayList<>();
        if (repairBackBill.getBackCheckDetail() != null) {
            String[] strings1 = repairBackBill.getBackCheckDetail().split("x");
            for (String s : strings1) {
                if (s.length() >= 2 && "1".equals(s.substring(s.length() - 1))) {
                    Integer deviceId = Integer.parseInt(s.substring(0, s.length() - 1));
                    Integer checkResult = Integer.parseInt(s.substring(s.length() - 1));
                    DeviceLibrary deviceLibraryEntity = deviceLibraryMap.get(deviceId);
                    deviceLibraryEntity.setCheckResult(checkResult);
                    deviceLibraries.add(deviceLibraryEntity);
                }
            }
        }
        //获取维修详情
        List<RepairDetail> repairDetails = repairDetailDao.findByRepairBackBillId(repairBackBill.getId());
        //设置装备备注
        deviceLibraries.forEach(deviceLibrary -> {
            for (RepairDetail r : repairDetails) {
                if (r.getDeviceId().equals(deviceLibrary.getId())) {
                    deviceLibrary.setRemark(r.getRemark());
                    if (r.getPid()!=null) {
                        deviceLibrary.setRepairStatus(repairDetailService.getOne(r.getPid()).getRepairStatus());
                    }
                    else {
                        deviceLibrary.setRepairStatus(r.getRepairStatus());
                    }
                }
            }
        });
        list.add(deviceLibraries);
        return ResponseEntity.ok(list);
    }

    /**
     * @param repairBillId 维修单id
     * @return 维修详情列表
     * 根据维修单Id查询维修详情，排序返回
     */
    private List<RepairDetail> getRepairDetail(int repairBillId) {
        List<RepairDetail> repairDetails = repairDetailService.findByBillId(repairBillId);
        List<RepairDetail> orderList = new ArrayList<>();
        repairDetails.forEach(repairDetail -> {
            if (!repairDetail.getRepairStatus().equals(RepairStatusEnum.CHANGE_NEW.id) && !repairDetail.getRepairStatus().equals(RepairStatusEnum.CHANGE_NEW_DEVICE.id)) {
                orderList.add(repairDetail);
                if (repairDetail.getRepairStatus().equals(RepairStatusEnum.SCRAPPED.id)) {
                    if (repairDetail.getNewDeviceDetailId() != null && repairDetail.getNewDeviceDetailId() > 0) {
                        orderList.add(repairDetailService.getOne(repairDetail.getNewDeviceDetailId()));
                    }
                }
            }
        });
        return orderList;
    }
}
