/*
 *  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.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.repository.PointRepository;
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.BaseStatus;
import com.youchain.utils.FileUtil;
import com.youchain.utils.ImportEntityUtils;
import com.youchain.utils.UserUtils;
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.List;
import java.util.Map;
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 = "点位管理")
@Slf4j
@RequestMapping("/api/point")
public class PointController {

    private final PointService pointService;
    private final PointRepository pointRepository;

    private final AreaService areaService;

    private final FileProperties properties;

    @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) {


        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();
        //编码、类型、库区、存储类型、X、Y
        ExcelReader reader = ExcelUtil.getReader(file);
        int i = 0;
        int edit_len = 0;
        int new_len = 0;
        try {
            List<Map<String, Object>> readAll = reader.readAll();
            for (i = 0; i < readAll.size(); i++) {
                String code = readAll.get(i).get("外部编码").toString().trim();
                String name = readAll.get(i).get("名称").toString().trim();
                String types = readAll.get(i).get("存储类型").toString().trim();
                String beatCode = readAll.get(i).get("地标码").toString().trim();
                String areaCode = readAll.get(i).get("库区").toString().trim();
                String enabled = readAll.get(i).get("是否启用").toString().trim();
                Double x = readAll.get(i).get("坐标X") == null ? 0 : Double.parseDouble(readAll.get(i).get("坐标X").toString());
                Double y = readAll.get(i).get("坐标Y") == null ? 0 : Double.parseDouble(readAll.get(i).get("坐标Y").toString());
                Double z = readAll.get(i).get("坐标Z") == null ? 0 : Double.parseDouble(readAll.get(i).get("坐标Z").toString());
                Area area = areaService.findByCode(areaCode);
                if (area == null) {
                    ApiError apiError = ApiError.errorJosn(BAD_REQUEST.value(), "找不到库区" + areaCode);
                    return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));
                }
                Point point = pointRepository.findByCode(code);
                if (point == null) {
                    point = new Point();
                    point.setCode(code);
                    point.setName(name);
                    String lx = "";
                    if (types.equals("存储点")) {
                        lx = BaseStatus.STORAGE;

                    } else if (types.equals("线边点位")) {
                        lx = BaseStatus.BOX;
                    }
                    point.setType(lx);
                    point.setArea(area);
                    point.setDept(dept);
                    point.setPosX(x);
                    point.setPosY(y);
                    point.setPosZ(z);
                    point.setBeatCode(beatCode);
                    point.setEnabled(true);
                    point.setStatus(BaseStatus.FREE);
                    pointService.create(point);
                    new_len++;
                } else {
                    point.setCode(code);
                    point.setName(code);
                    String lx = "";
                    if (types.equals("存储点")) {
                        lx = BaseStatus.STORAGE;

                    } else if (types.equals("线边点位")) {
                        lx = BaseStatus.BOX;
                    }
                    point.setType(lx);
                    point.setArea(area);
                    point.setBeatCode(beatCode);
                    point.setDept(dept);
                    point.setPosX(x);
                    if (ImportEntityUtils.stringFlag(enabled)){
                        point.setEnabled(Boolean.valueOf(enabled));
                    }
                    point.setPosY(y);
                    point.setPosZ(z);
                    pointService.update(point);
                    edit_len++;
                }

                log.info("导入" + (i + 1) + "行");
            }
        } catch (Exception e) {
            ApiError apiError = ApiError.errorJosn(HttpStatus.BAD_REQUEST.value(), "导入异常---第" + (i + 1) + "行：" + e.toString());
            return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));
        }


        ApiError apiError = ApiError.errorJosn(HttpStatus.OK.value(), "导入成功：" + (i) + "行 新增（" + new_len + ")修改（" + edit_len + ")");
        return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));

    }

    @GetMapping
    @ApiOperation("查询point")
    public ResponseEntity<Object> queryPoint(PointQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(pointService.queryAll(criteria, pageable), HttpStatus.OK);
    }
    @PostMapping("/clearCk")
    @ApiOperation("清空备货位")
    @AnonymousAccess
    public ResponseEntity<Object> clearCk() {
        /* 清空出库接驳口*/
        List<Point> pointList = pointRepository.findByAreaAndStatus("出库接驳口", BaseStatus.USED);
        for (Point p : pointList) {
            p.setStatus(BaseStatus.FREE);
            pointRepository.save(p);
        }
        ApiResult apiResult=ApiResult.fail(200,"操作成功",null);
        return new ResponseEntity<>(apiResult, apiResult.getStatus());
    }


    @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);
    }

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

    @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 new ResponseEntity<>(ApiResult.success(HttpStatus.OK.value(), "调整成功!", ""), HttpStatus.OK);

    }

    @PostMapping("/queryPointInfo")
    @AnonymousAccess
    public ResponseEntity<Object> queryPointInfo(@RequestBody CurrentPage currentPage) {
//       List<Point> pointList= pointService.getPoint(BaseStatus.STORAGE,"存储区",currentPage.getCurrentPage(),currentPage.getPageSize());
       int total=pointRepository.getDataPointTotal().size();
       JSONArray dataArray=new JSONArray();
       List<Map<String,Object>> pointList= pointRepository.getDataPointLimit((currentPage.getCurrentPage()-1)*currentPage.getPageSize(),currentPage.getPageSize());
        for (int i = 0; i < pointList.size(); i++) {
            double x=Double.valueOf(pointList.get(i).get("pos_x")+"");
            double y=Double.valueOf(pointList.get(i).get("pos_y")+"");
            dataArray.add(pointRepository.getDataPointList(x,y));
        }
       JSONObject object=new JSONObject();
        object.put("total",total);
        object.put("pageSize",12);
        object.put("data",dataArray);
       return new ResponseEntity<>(ApiResult.success(HttpStatus.OK.value(), "", object), HttpStatus.OK);
    }

}
