/*
 *  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.core.date.DateUtil;
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.appupdate.inputJson.CurrentPage;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.AreaDto;
import com.youchain.basicdata.service.dto.PointQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.handler.ApiError;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.extern.slf4j.Slf4j;
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.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @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 AreaService areaService;

    private final FileProperties properties;

    private final BatchCreateOrUpdate batchCreateOrUpdate;

    private final RedisObjectUtils redisObjectUtils;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('point:list')")
    public void exportPoint(HttpServletResponse response, PointQueryCriteria criteria) throws IOException {
        pointService.download(pointService.queryAll(criteria), response);
    }

    @Log("导入点位")
    @PostMapping(value = "/import_point")
    @ApiOperation("导入点位")
    @PreAuthorize("@el.check('point:importPoint')")
    public ResponseEntity<Object> importPoint(@RequestParam("file") MultipartFile multipartFile) {
        //编码、类型、库区、存储类型、坐标X、坐标Y
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator);
        Dept dept = UserUtils.getDept();
        ExcelReader reader = ExcelUtil.getReader(file);
        List<Map<String, Object>> readAll = reader.readAll();
        try {
            Set<String> pointCodes = new HashSet<>();//点位集合
            for (Map<String, Object> record : readAll) {
                String pointCode = record.get("编码").toString().trim();
                if (!StringUtils.isEmpty(pointCode)) {
                    pointCodes.add(pointCode);
                }
            }


            //获取已存在的点位
            Map<String, Point> existingPoint = pointService.findByCodes(pointCodes);


            List<Point> pointsToCreate = new ArrayList<>();//新增点位集合
            List<Point> pointsToUpdate = new ArrayList<>();//修改点位集合
            for (Map<String, Object> record : readAll) {
                String pointCode = record.get("编码").toString().trim();
                String areaCode = record.get("库区").toString().trim();
                Area area = redisObjectUtils.getObjectFromCache(areaCode, () -> areaService.findByCode(areaCode), areaCode + " 系统无此库区!");
                //判断是否已存在点位
                if (existingPoint.containsKey(pointCode)) {
                    Point point = existingPoint.get(pointCode);
                    //更新点位
                    pointsToUpdate.add(updatePoints(point, area, dept, record));
                } else {
                    //新增点位
                    pointsToCreate.add(createPoint(area, dept, record));
                }
            }

            CompletableFuture<Void> createFuture = CompletableFuture.runAsync(() -> {
                //批量新增Mo票
                if (!pointsToCreate.isEmpty()) {
                    batchCreateOrUpdate.batchCreate(pointsToCreate);
                }
            });

            CompletableFuture<Void> updateFuture = CompletableFuture.runAsync(() -> {
                //批量更新Mo票
                if (!pointsToUpdate.isEmpty()) {
                    batchCreateOrUpdate.batchUpdate(pointsToUpdate);
                }
            });
            // 等待所有操作完成
            CompletableFuture.allOf(createFuture, updateFuture).join();
            return successRequest("导入成功：" + " 新增（" + pointsToCreate.size() + ")修改（" + pointsToUpdate.size() + ")", "");
        } catch (Exception e) {
            return badRequest("导入失败：" + e.getMessage());
        }

    }

    private Point updatePoints(Point point, Area area, Dept dept, Map<String, Object> record) {
        point.setArea(area);
        point.setDept(dept);
        point.setDescription(record.get("存储类型") == null ? "" : record.get("存储类型").toString().trim());
        String types = record.get("类型").toString().trim();
        String lx = "";
        if (types.equals("缓存点")) {
            lx = BaseStatus.STORAGE;

        } else if (types.equals("线边点位")) {
            lx = BaseStatus.BOX;
        }
        point.setType(lx);
        point.setPosX(record.get("坐标X") == null ? 0 : Double.parseDouble(record.get("坐标X").toString()));
        point.setPosY(record.get("坐标Y") == null ? 0 : Double.parseDouble(record.get("坐标Y").toString()));
        return point;
    }

    private Point createPoint(Area area, Dept dept, Map<String, Object> record) {
        Point point = new Point();
        point.setCode(record.get("编码").toString().trim());
        point.setName(record.get("编码").toString().trim());
        point.setArea(area);
        point.setDept(dept);
        point.setDescription(record.get("存储类型") == null ? "" : record.get("存储类型").toString().trim());
        String types = record.get("类型").toString().trim();
        String lx = "";
        if (types.equals("缓存点")) {
            lx = BaseStatus.STORAGE;

        } else if (types.equals("线边点位")) {
            lx = BaseStatus.BOX;
        }
        point.setType(lx);
        point.setPosX(record.get("坐标X") == null ? 0 : Double.parseDouble(record.get("坐标X").toString()));
        point.setPosY(record.get("坐标Y") == null ? 0 : Double.parseDouble(record.get("坐标Y").toString()));
        point.setEnabled(true);
        point.setStatus(BaseStatus.FREE);
        return point;
    }

    @GetMapping
    @ApiOperation("查询point")
    public ResponseEntity<Object> queryPoint(PointQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(pointService.queryAll(criteria, pageable), HttpStatus.OK);
    }

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

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

    @PostMapping
    @Log("新增point")
    @ApiOperation("新增point")
    @PreAuthorize("@el.check('point:add')")
    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('point:edit')")
    public ResponseEntity<Object> updatePoint(@Validated @RequestBody Point resources) {
        pointService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除point")
    @ApiOperation("删除point")
    @PreAuthorize("@el.check('point:del')")
    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);
    }

    @PostMapping("/multiAdjust")
    @Log("点位批量调整")
    @ApiOperation("点位批量调整")
    @AnonymousAccess
    public ResponseEntity<Object> multiAdjust(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        String smallArea = jsonObject.getString("smallArea") == null ? "" : jsonObject.getString("smallArea");//小库区
        String description = jsonObject.getString("description") == null ? "" : jsonObject.getString("description");//存储类型
        String areaId = jsonObject.getString("areaId") == null || jsonObject.getString("areaId").equals("") ? "0" : jsonObject.getString("areaId");//库区
        String enabled = jsonObject.getString("enabled") == null || jsonObject.getString("enabled").equals("") ? "" : jsonObject.getString("enabled");//是否启用

        if ((description == null || description.length() <= 0) && (areaId.equals("0"))) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "存储类型和库区至少选择一项!", ""), HttpStatus.BAD_REQUEST);
        }

        if ((description != null && description.length() > 0) && (!areaId.equals("0"))) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "存储类型和库区只能选择一项!", ""), HttpStatus.BAD_REQUEST);
        }

        List<Point> pointList = pointService.getPointByBeat_code(smallArea);
        if (pointList.size() <= 0) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), smallArea + "没有小库区对应的点位，请维护!", ""), HttpStatus.BAD_REQUEST);
        }

        //批量调整存储类型
        if (description != null && description.length() > 0) {
            Point point2 = pointList.get(0);
            Area area = point2.getArea();
            if (area.getName().equals("前后桶空车区")) {
                return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), smallArea + "小库区为前后桶空车区，不能绑定存储类型!", ""), HttpStatus.BAD_REQUEST);
            }
            for (Point point : pointList) {
                point.setDescription(description);
                point.setEnabled(Boolean.parseBoolean(enabled));
                pointService.update(point);
            }
            log.info(smallArea + "小库区批量调整存储类型为" + description + "状态为" + Boolean.parseBoolean(enabled));
        }

        //批量调整库区
        if (!areaId.equals("0")) {
            AreaDto areaDto = areaService.findById(Long.parseLong(areaId));
            Area area = areaService.toEntity(areaDto);
            for (Point point : pointList) {
                point.setArea(area);
                point.setEnabled(Boolean.parseBoolean(enabled));
                pointService.update(point);
            }
            log.info(smallArea + "小库区批量调整库区为" + area.getName() + "状态为" + Boolean.parseBoolean(enabled));

        }
        return successRequest("调整成功!", "");
    }

    @PostMapping("/queryPointInfo")
    @AnonymousAccess
    public ResponseEntity<Object> queryPointInfo(@RequestBody CurrentPage currentPage) {
        List<Point> pointList = pointService.getPoint(BaseStatus.STORAGE, "1F存储区", currentPage.getCurrentPage(), currentPage.getPageSize());
        int total = pointService.getPoint(BaseStatus.STORAGE, "1F存储区").size();
        JSONObject object = new JSONObject();
        object.put("total", total);
        object.put("data", pointList);
        return successRequest("", object);
    }

    private ResponseEntity<Object> badRequest(String message) {
        return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), message, ""), HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity<Object> successRequest(String message, Object object) {
        return new ResponseEntity<>(ApiResult.fail(OK.value(), message, object), HttpStatus.OK);
    }

}
