package com.tykj.dev.device.packing.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.subject.domin.DeviceLibrary;
import com.tykj.dev.device.packing.repository.PackingLibraryDao;
import com.tykj.dev.device.packing.service.PackingLibraryService;
import com.tykj.dev.device.packing.subject.domin.PackingLibrary;
import com.tykj.dev.device.packing.subject.vo.*;
import com.tykj.dev.misc.utils.*;
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.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dengdiyi
 */
@RestController
@Api(tags = "列装管理模块", description = "列装管理接口")
@AutoDocument
@RequestMapping("/packing")
@Validated
public class PackingLibraryController {

    @Autowired
    PackingLibraryService packingLibraryService;

    @Autowired
    DeviceLibraryDao deviceLibraryDao;

    @Autowired
    DeviceLibraryService deviceLibraryService;

    @Autowired
    PackingLibraryDao packingLibraryDao;

    @ApiOperation(value = "申请后入库获取父子结构列装（去除已入库序列号）", notes = "获取父子结构列装")
    @PostMapping("/merge")
    public ResponseEntity merge(@RequestBody List<PackingLibrary> packingLibraries){
        Map<String,DeviceLibrary> map = deviceLibraryService.getAllDeviceSeqMap();
        packingLibraries.forEach(packingLibrary -> {
            List<String> inputSeqs = DeviceSeqUtil.selectDeviceSeqs(packingLibrary.getSeq());
            List<String> outputSeqs = new ArrayList<>();
            inputSeqs.forEach(s -> {
                if (map.get(s)==null){
                    outputSeqs.add(s);
                }
            });
            packingLibrary.setSeq(StringSplitUtil.stringListToString(DeviceSeqUtil.getContinuousSeqs(outputSeqs)));
        });
        //返回父子结构
        Map<Integer, PackingLibrary> nodeCollect =
                packingLibraries.stream().collect(Collectors.toMap(PackingLibrary::getId, packingLibrary -> packingLibrary));
        return ResponseEntity.ok(GetTreeUtils.parseTreeFromDown(
                packingLibraries,
                PackingLibrary::getId,
                packingLibrary -> Optional.ofNullable(nodeCollect.get(packingLibrary.getPartParentId())),
                PackingLibrary::addChildNode
        ));
    }

    @ApiOperation(value = "获取装备单据显示", notes = "获取装备单据显示")
    @PostMapping("/getAllotScript")
    public ResponseEntity getAllotScript(@RequestBody List<Integer> ids){
        return ResponseEntity.ok(packingLibraryService.getDevcieAllotScript(ids));
    }

    @ApiOperation(value = "获取装备单据显示", notes = "获取装备单据显示")
    @PostMapping("/getScript")
    public ResponseEntity setRecord(@RequestBody List<Integer> ids){
//        throw new ApiException(ResponseEntity.status(303).body("aaa"));
        return ResponseEntity.ok(packingLibraryService.getDevcieScript(ids));
    }

    @ApiOperation(value = "列装库分页查询", notes = "可以通过这个接口进行列装查询")
    @PostMapping("/serve/summary")
    public ResponseEntity getPage(@RequestBody PackingLibrarySelectVo packingLibrarySelectVo) {
        Page<PackingLibrary> packingLibraryEntityPage = packingLibraryService.getPage(packingLibrarySelectVo, packingLibrarySelectVo.getPageable());
        packingLibraryEntityPage.getContent().forEach(PackingLibrary::setConfigName);
        return ResultUtil.success(packingLibraryEntityPage);
    }

    @ApiOperation(value = "列装库退装分页查询", notes = "可以通过这个接口进行列装查询")
    @PostMapping("/retired/summary")
    public ResponseEntity getInvalidPage(@RequestBody PackingLibrarySelectVo packingLibrarySelectVo) {
        List<PackingLibrary> resultList = packingLibraryService.getInvalidPage(packingLibrarySelectVo, packingLibrarySelectVo.getPageable());
        //返回父子结构
        Map<Integer, PackingLibrary> nodeCollect =
                resultList.stream().collect(Collectors.toMap(PackingLibrary::getId, packingLibrary -> packingLibrary));
        List<PackingLibrary> resultList2 =  GetTreeUtils.parseTreeFromDown(
                resultList,
                PackingLibrary::getId,
                packingLibrary -> Optional.ofNullable(nodeCollect.get(packingLibrary.getPartParentId())),
                PackingLibrary::addChildNode
        );
        Page<PackingLibrary> packingLibraries = PageUtil.getPerPage(packingLibrarySelectVo.getPage(),packingLibrarySelectVo.getSize(),resultList2,packingLibrarySelectVo.getPageable());
        Map<String,Object> map = new HashMap<>();
        map.put("pages",packingLibraries);
        map.put("models",resultList.stream().map(PackingLibrary::getModel).collect(Collectors.toSet()));
        map.put("names",resultList.stream().map(PackingLibrary::getName).collect(Collectors.toSet()));
        return ResultUtil.success(map);
    }

    @ApiOperation(value = "列装库列表查询", notes = "可以通过这个接口进行列装查询")
    @PostMapping("/getList")
    public ResponseEntity getList(@RequestBody PackingLibrarySelectVo packingLibrarySelectVo) {
        List<PackingLibrary> packingLibraryEntities = packingLibraryService.getList(packingLibrarySelectVo);
//        if (packingLibrarySelectVo.ids!=null&&packingLibrarySelectVo.ids.size()>0) {
//            packingLibraryEntities.removeIf(p -> packingLibrarySelectVo.ids.contains(p.getId()));
//            packingLibraryEntities.forEach(packingLibrary -> {
//                List<PackingLibrary> childs = packingLibrary.getChilds();
//                if (childs!=null&&childs.size()>0){
//                    childs.removeIf(packingLibrary1 -> packingLibrarySelectVo.ids.contains(packingLibrary1.getId()));
//                }
//            });
//        }
        Map<String,Object> map = new HashMap<>();
        map.put("pages",packingLibraryEntities);
        List<String> models = new ArrayList<>();
        for (PackingLibrary p : packingLibraryEntities){
            models.add(p.getModel());
        }
        map.put("models",models);
        return ResultUtil.success(map);
    }


    @ApiOperation(value = "更新列装库", notes = "可以通过这个接口更新列装")
    @PostMapping("/updatePackingLibrary")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity updatePackingLibrary(@RequestBody @Validated PackingEditVo packingEditVo) {
        //更新列装信息
        if (packingEditVo.getUpdateVoList() != null) {
            PackingLibrary packingLibraryEntity = packingLibraryService.getOne(packingEditVo.getPackingId());
            //获取配件列装
            List<PackingLibrary> packingLibraries = packingLibraryService.selectAllPart(packingEditVo.getPackingId());
            //获取该列装所有装备
            List<DeviceLibrary> deviceLibraries = deviceLibraryDao.getAllByPackingId(packingEditVo.getPackingId());
            //获取所有列装配件装备
            List<DeviceLibrary> deviceLibraryList = new ArrayList<>();
            packingLibraries.forEach(packingLibrary -> deviceLibraryList.addAll(deviceLibraryDao.getAllByPackingId(packingLibrary.getId())));
            PackingLibraryUpdateVo p = packingEditVo.getUpdateVoList();
            if (p.getApplyType() != null) {
                packingLibraryEntity.setApplyType(p.getApplyType());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setApplyType(p.getApplyType()));
            }
            if (p.getCreateUnit() != null) {
                packingLibraryEntity.setCreateUnit(p.getCreateUnit());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setCreateUnit(p.getCreateUnit()));
            }
            if (p.getFileName() != null) {
                packingLibraryEntity.setFileName(p.getFileName());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setFileName(p.getFileName()));
            }
            if (p.getFileUrl() != null) {
                packingLibraryEntity.setFileUrl(p.getFileUrl());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setFileUrl(p.getFileUrl()));
            }
            if (p.getImageName() != null) {
                packingLibraryEntity.setImageName(p.getImageName());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setImageName(p.getImageName()));
            }
            if (p.getImageUrl() != null) {
                packingLibraryEntity.setImageUrl(p.getImageUrl());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setImageUrl(p.getImageUrl()));
            }
            if (p.getInvisibleRange() != null) {
                packingLibraryEntity.setInvisibleRange(p.getInvisibleRange());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setInvisibleRange(p.getInvisibleRange()));
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setInvisibleRange(p.getInvisibleRange()));
                deviceLibraryList.forEach(deviceLibrary -> deviceLibrary.setInvisibleRange(p.getInvisibleRange()));
            }
            if (p.getMatchingRange() != null) {
                packingLibraryEntity.setMatchingRange(p.getMatchingRange());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setMatchingRange(p.getMatchingRange()));
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setMatchingRange(p.getMatchingRange()));
                deviceLibraryList.forEach(deviceLibrary -> deviceLibrary.setMatchingRange(p.getMatchingRange()));
            }
            if (p.getModel() != null) {
                packingLibraryEntity.setModel(p.getModel());
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setModel(p.getModel()));
            }
            if (p.getName() != null) {
                packingLibraryEntity.setName(p.getName());
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setName(p.getName()));
            }
            if (p.getNature() != null) {
                packingLibraryEntity.setNature(p.getNature());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setNature(p.getNature()));
            }
            if (p.getPrice() != null) {
                packingLibraryEntity.setPrice(p.getPrice());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setPrice(p.getPrice()));
            }
            if (p.getProdUnit() != null) {
                packingLibraryEntity.setProdUnit(p.getProdUnit());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setProdUnit(p.getProdUnit()));
            }
            if (p.getSecretLevel() != null) {
                packingLibraryEntity.setSecretLevel(p.getSecretLevel());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setSecretLevel(p.getSecretLevel()));
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setSecretLevel(p.getSecretLevel()));
                deviceLibraryList.forEach(deviceLibrary -> deviceLibrary.setSecretLevel(p.getSecretLevel()));
            }
            if (p.getStatus() != null) {
                packingLibraryEntity.setStatus(p.getStatus());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setStatus(p.getStatus()));
            }
            if (p.getType() != null) {
                packingLibraryEntity.setType(p.getType());
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setType(p.getType()));
            }
            packingLibraryService.update(packingLibraryEntity);
            packingLibraries.forEach(packingLibrary -> packingLibraryService.update(packingLibrary));
            deviceLibraries.forEach(deviceLibrary -> deviceLibraryService.update(deviceLibrary));
            deviceLibraryList.forEach(deviceLibrary -> deviceLibraryService.update(deviceLibrary));
        }
        //更新配件信息
        if (packingEditVo.getPartUpdateVoList()!=null){
            packingEditVo.getPartUpdateVoList().forEach(packingLibraryUpdateVo -> {
                if (packingLibraryUpdateVo.getPackingId() > 0){
                    PackingLibrary packingLibrary = packingLibraryService.getOne(packingLibraryUpdateVo.getPackingId());
                    //获取该配件所有装备
                    List<DeviceLibrary> deviceLibraries = deviceLibraryDao.getAllByPackingId(packingLibraryUpdateVo.getPackingId());
                    if (packingLibraryUpdateVo.getModel()!=null){
                        packingLibrary.setModel(packingLibraryUpdateVo.getModel());
                        deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setModel(packingLibraryUpdateVo.getModel()));
                    }
                    if (packingLibraryUpdateVo.getName()!=null){
                        packingLibrary.setName(packingLibraryUpdateVo.getName());
                        deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setName(packingLibraryUpdateVo.getName()));
                    }
                    if (packingLibraryUpdateVo.getType()!=null){
                        packingLibrary.setType(packingLibraryUpdateVo.getType());
                        deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setType(packingLibraryUpdateVo.getType()));
                    }
                    deviceLibraries.forEach(deviceLibrary -> deviceLibraryService.update(deviceLibrary));
                    packingLibraryService.update(packingLibrary);
                }
            });
        }
        //添加新增配件
        if (packingEditVo.getPartAddList() != null) {
            for (PartSaveVo p : packingEditVo.getPartAddList()) {
                PackingLibrary packingLibraryEntity = packingLibraryService.getOne(packingEditVo.getPackingId());
                if (packingLibraryEntity.getIsPart() == 0 && packingLibraryEntity.getPartParentId() == null) {
                    PackingLibrary p2 = new PackingLibrary();
                    BeanUtils.copyProperties(packingLibraryEntity, p2);
                    BeanUtils.copyProperties(p, p2);
                    p2.setId(null);
                    p2.setIsPart(1);
                    p2.setPartParentId(packingLibraryEntity.getId());
                    packingLibraryService.addEntity(p2);
                }
            }
        }
        //删除绑定的配件
        if (packingEditVo.getPartIdDeleteList() != null) {
            for (Integer id : packingEditVo.getPartIdDeleteList()) {
                if (id > 0) {
                    PackingLibrary packingLibraryEntity = packingLibraryService.getOne(id);
                    if (packingLibraryEntity.getIsPart() == 1 && packingLibraryEntity.getPartParentId().equals(packingEditVo.getPackingId())) {
                        packingLibraryEntity.setPartParentId(null);
                        packingLibraryService.update(packingLibraryEntity);
                        packingLibraryService.delete(packingLibraryEntity.getId());
                    }
                }
            }
        }
        return ResultUtil.success("更新成功");
    }

    @ApiOperation(value = "查询存在的型号", notes = "可以通过这个接口查询存在的型号")
    @GetMapping("/selectAllMode")
    public ResponseEntity selectAllMode() {
        return ResultUtil.success(packingLibraryService.getModelList());
    }

    @ApiOperation(value = "查询存在的类型", notes = "可以通过这个接口查询存在的类型")
    @GetMapping("/selectAllType")
    public ResponseEntity selectAllType() {
        return ResultUtil.success(packingLibraryService.getTypeList());
    }

    @ApiOperation(value = "查询列装库详情页", notes = "可以通过这个接口查询存在的类型")
    @GetMapping("/serve/detail/{id}")
    public ResponseEntity selectPackingDetail(@PathVariable("id") @Min(value = 1,message = "id不能小于1") int id) {
        return ResultUtil.success(packingLibraryService.getPackingDetail(id));
    }

    @ApiOperation(value = "查询多个列装详情", notes = "可以通过这个接口查询多个列装详情")
    @PostMapping("/selectMoreDetail")
    public ResponseEntity selectMorePackingDetail(@RequestBody List<Integer> ids) {
        List<PackingLibrary> packingLibraries = new ArrayList<>();
        ids.forEach(integer -> packingLibraries.add(packingLibraryService.getOne(integer).setConfigName()));
        return ResultUtil.success(packingLibraries);
    }

    @ApiOperation(value = "查询退装详情页", notes = "可以通过这个接口查询存在的类型")
    @GetMapping("/retired/detail/{id}")
    public ResponseEntity selectInvalidDetail(@PathVariable("id") @Min(value = 1,message = "id不能小于1") int id) {
        return ResultUtil.success(packingLibraryService.getInvalidDetail(id));
    }

    @ApiOperation(value = "查询父子结构列装")
    @PostMapping("/selectList")
    public ResponseEntity selectPack(@RequestBody SelectPack selectPack){
        return ResultUtil.success(packingLibraryService.getInsertList(selectPack));
    }

}
