/*
 *  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.JSONObject;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.PointDto;
import com.youchain.basicdata.service.dto.PointQueryCriteria;
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.handler.ApiError;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.FileUtil;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * @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 ItemRepository itemRepository;
    private final InventoryService inventoryService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @AnonymousAccess
    public void exportPoint(HttpServletResponse response, PointQueryCriteria criteria) throws Exception {
        pointService.download(pointService.queryAll(criteria), response);
    }

    @Log("导入点位")
    @PostMapping(value = "/import_point")
    @ApiOperation("导入点位")
    @AnonymousAccess
    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();
        //编码、描述、库区、存储类型
        ExcelReader reader = ExcelUtil.getReader(file);
        int i = 0;
        int edit_len = 0;
        int new_len = 0;
        List<Map<String, Object>> readAll = reader.readAll();
        for (i = 0; i < readAll.size(); i++) {
            /*String code = readAll.get(i).get("编码").toString().trim();
            String types = readAll.get(i).get("存储类型").toString().trim();
            String areaCode = readAll.get(i).get("库区").toString().trim();
            String ccTYPE = readAll.get(i).get("描述") == null ? "" : readAll.get(i).get("描述").toString().trim();
            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 = pointService.getPoint(code, null, null, null);
            Boolean isNew=Boolean.FALSE;
            if (point == null) {
                point = new Point();
                point.setCode(code);
                point.setDept(dept);
                point.setEnabled(true);
                point.setStatus(BaseStatus.FREE);
                point.setName(code);
                isNew=Boolean.TRUE;
            }
                String lx = "";
                if (types.equals("存货")) {
                    lx = BaseStatus.CH;
                } else if (types.equals("制造库位")) {
                    lx = BaseStatus.ZZKW;
                }else if (types.equals("缓存库位")) {
                    lx = BaseStatus.HCKW;
                }
                point.setType(lx);
                point.setArea(area);
                point.setDescription(ccTYPE);
                if(isNew){
                    pointService.create(point);
                }else {
                    pointService.update(point);
                }*/
//            ExcelImportParam
        }
        ApiError apiError = ApiError.errorJosn(HttpStatus.OK.value(), "导入成功：" + (i) + "行 新增（" + new_len + ")修改（" + edit_len + ")");
        return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));

    }

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