/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.basicdata.rest;

import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.BomAccountQueryCriteria;
import com.youchain.basicdata.service.dto.PointDto;
import com.youchain.basicdata.service.dto.PointQueryCriteria;
import com.youchain.businessdata.returnJson.*;
import com.youchain.businessdata.service.InventoryService;
import com.youchain.businessdata.service.dto.InventoryDto;
import com.youchain.businessdata.service.dto.InventoryQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiError;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.JsonUtil;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import static org.springframework.http.HttpStatus.BAD_REQUEST;

/**
 * @author liuxue
 * @website https://eladmin.vip
 * @date 2023-07-26
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "ponit管理")
@Slf4j
@RequestMapping("/api/point")
public class PointController {

    private final PointService pointService;
    private final InventoryService inventoryService;
    private final AreaService areaService;

    private final FileProperties properties;
    private final ItemRepository itemRepository;
    private final PointRepository pointRepository;


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @AnonymousAccess
    public void exportPoint(HttpServletResponse response, PointQueryCriteria criteria) throws Exception {
        pointService.download(pointService.queryAll(criteria), response);
    }
    @GetMapping
    @Log("查询point")
    @ApiOperation("查询point")
    @AnonymousAccess
    public ResponseEntity<Object> queryPoint(PointQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(pointService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping("/getPoints")
    @Log("加载point下拉框")
    @ApiOperation("加载point下拉框")
    @AnonymousAccess
    public ResponseEntity<Object> getPointList(@RequestBody(required = false) String type) {
        return new ResponseEntity<>(pointService.getPointList(type), HttpStatus.OK);
    }

    @GetMapping(value = "/queryPointList")
    @Log("下拉查询点位")
    @ApiOperation("下拉查询点位")
    @AnonymousAccess
    public ResponseEntity<Object> queryPointList(PointQueryCriteria criteria) {
        return new ResponseEntity<>(pointService.queryAll(criteria), HttpStatus.OK);
    }

    @GetMapping(value = "/getOutPointAll")
    @Log("获取出库点位")
    @ApiOperation("获取出库点位")
    @AnonymousAccess
    public ResponseEntity<Object> getOutPointAll(PointQueryCriteria criteria) {
        InventoryQueryCriteria inventoryQueryCriteria = new InventoryQueryCriteria();
        if (criteria.getAreaName() != null) {
            List<Item> items = itemRepository.quryOneItemAll();
            List<String> itemCode = new ArrayList<>();
            for (Item item : items) {
                itemCode.add(item.getCode());
            }
            inventoryQueryCriteria.setItemCode(itemCode);
            inventoryQueryCriteria.setAreaName(criteria.getAreaName());
            List<InventoryDto> inventoryDtos = inventoryService.queryAll(inventoryQueryCriteria);
            List<PointDto> collect = inventoryDtos.stream().map(InventoryDto::getPoint).collect(Collectors.toList());
            return new ResponseEntity<>(collect, HttpStatus.OK);
        }
        return new ResponseEntity<>(null, HttpStatus.OK);
    }


    @GetMapping(value = "/queryKyPointList")
    @Log("查询可用空闲的点位point")
    @ApiOperation("查询可用空闲的点位point")
    @AnonymousAccess
    public ResponseEntity<Object> queryKyPointList(PointQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(pointService.queryKyPointList(), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增point")
    @ApiOperation("新增point")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createPoint(@Validated @RequestBody Point resources) {
        resources.setDept(UserUtils.getDept());
        return new ResponseEntity<>(pointService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改point")
    @ApiOperation("修改point")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updatePoint(@Validated @RequestBody Point resources) {
//        if (!Objects.isNull(resources.getPoint())){
//            if (resources.getPoint().getId() == null){
//                resources.setPoint(null);
//            }
//        }
        pointService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PutMapping("/updatePoint")
    @Log("修改point")
    @ApiOperation("修改point")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updatePointOK(@Validated @RequestBody Point resources) {
        pointService.update(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping
    @Log("删除point")
    @ApiOperation("删除point")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> deletePoint(@RequestBody Long[] ids) {
        pointService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/queryPoint")
    @Log("光电点位状态查询")
    @ApiOperation("光电点位状态查询")
    @AnonymousAccess
    public ResponseEntity<Object> queryPoint(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        String pointCode = jsonObject.getString("pointCode") == null ? "" : jsonObject.getString("pointCode");//输送线、光电编号
        pointService.queryPoint(pointCode);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("/queryPointPrintList")
    @Log("查询自由货位标签")
    @ApiOperation("查询自由货位标签")
    @AnonymousAccess
    public ResponseEntity<Object> queryPointPrintList(PointQueryCriteria criteria){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        redisUtils.del(SecurityUtils.getCurrentUsername()+"_BiaoQian_ZY");
        List<PointZyPrint> list=pointRepository.queryPrintAll(criteria.getAreaName(),criteria.getCode());
        redisUtils.set(SecurityUtils.getCurrentUsername()+"_BiaoQian_ZY", JsonUtil.toJson(list));
        return new ResponseEntity<>(list,HttpStatus.OK);
    }

    @GetMapping("/pointPrintBiaoQianList/{type}")
    @Log("获取Point中库位标签")
    @ApiOperation("获取Point中库位标签")
    @AnonymousAccess
    public ResponseEntity<Object> pointPrintBiaoQianList(@PathVariable("type") String type){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        String json=(String)redisUtils.get(SecurityUtils.getCurrentUsername()+type);
        log.info(SecurityUtils.getCurrentUsername()+type+"-----"+json);
        List<PointPrint_BiaoQian_Zy> list= JSONUtil.toList(json, PointPrint_BiaoQian_Zy.class);
        List<PointPrint_BiaoQian_Zy> list2=new ArrayList<>();
        for(PointPrint_BiaoQian_Zy zy:list){
            zy.setEwm(zy.getCode());
            zy.setCode(zy.getCode().substring(0,3)+"-"+zy.getCode().substring(3));
            list2.add(zy);
        }
        return new ResponseEntity<>( list2,HttpStatus.OK);
    }
}
