/*
*  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.Area;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.StockType;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.ItemDto;
import com.youchain.basicdata.service.dto.ItemQueryCriteria;
import com.youchain.basicdata.service.dto.PointQueryCriteria;
import com.youchain.basicdata.service.dto.StockQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.handler.ApiError;
import com.youchain.modules.system.domain.Dept;
import com.youchain.modules.system.domain.DictDetail;
import com.youchain.modules.system.service.dto.DictQueryCriteria;
import com.youchain.utils.BaseStatus;
import com.youchain.utils.BizStatus;
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.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

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

/**
* @website https://eladmin.vip
* @author liuxue
* @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;

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

    @PostMapping(value = "/import_point")
    @ApiOperation("导入点位")
    @Transactional
    @PreAuthorize("@el.check('point:list')")
    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);
        log.error("--" + properties.getPath().getPath() + type + File.separator);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator);
        log.error("--" + file.getPath());

        Dept dept=UserUtils.getDept();
        log.error("--" + dept.getId());
        //代码、库区
        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 areaCode=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.findByCode(code,null,null);
                if(point==null){
                    point=new Point();
                    point.setCode(code);
                    point.setName(code);
                    point.setStatus(BaseStatus.FREE);
                    point.setEnabled(true);
                    log.error("-7--");
                    new_len++;
                    log.error("-70--");
                    point.setDept(dept);
                    log.error("-8--"+point.getDept().getId().toString());
                    pointService.create(point);
                    log.error("-9--");
                }else{
                    edit_len++;
                }
                log.error("-5--");
                point.setArea(area);
                pointService.update(point);
                log.error("-6--");
            }
        }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
    @Log("查询point")
    @ApiOperation("查询point")
    @PreAuthorize("@el.check('point:list')")
    public ResponseEntity<Object> queryPoint(PointQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(pointService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @GetMapping(value = "/queryKyPointList")
    @Log("查询可用空闲的点位point")
    @ApiOperation("查询可用空闲的点位point")
    @PreAuthorize("@el.check('point:list')")
    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);
    }
}