/*
*  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.youchain.annotation.Log;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Studen;
import com.youchain.basicdata.service.StudenService;
import com.youchain.basicdata.service.dto.StudenQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.handler.ApiError;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.BaseStatus;
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.scheduling.annotation.Scheduled;
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.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

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

/**
* @website https://eladmin.vip
* @author LY
* @date 2024-04-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "studen管理")
@Slf4j
@RequestMapping("/api/studen")
public class StudenController {

    private final StudenService studenService;

    //导入
    private final FileProperties properties;

    @Log("导入点位")
    @PostMapping(value = "/import_studen")
    @ApiOperation("导入点位")
    @PreAuthorize("@el.check('studen:importStuden')")
    public ResponseEntity<Object> importPoint(@RequestParam("file") MultipartFile multipartFile) {

        System.out.println("multipartFile:"+multipartFile);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        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();

        System.out.println("dept:"+dept);

        ExcelReader reader = ExcelUtil.getReader(file);
        int i = 0;
        int edit_len = 0;
        int new_len = 0;
        try {
            List<Map<String, Object>> readAll = reader.readAll();
            System.out.println("list:"+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 enabled = readAll.get(i).get("是否启用").toString().trim();
                String creator = readAll.get(i).get("创建人").toString().trim();
                String modifier = readAll.get(i).get("修改人").toString().trim();
                Timestamp creationTime =Timestamp.valueOf(readAll.get(i).get("创建时间").toString().trim());
                Timestamp modificationTime =Timestamp.valueOf(readAll.get(i).get("修改时间").toString().trim());
                boolean flay = studenService.findBycode(code);
                System.out.println("flay"+flay);
                if(!flay){
                    Studen  stu = new Studen();
                    stu.setCode(code);
                    stu.setName(name);
                    if (enabled.equals("true")) {
                        stu.setEnabled(true);
                    } else {
                        stu.setEnabled(false);
                    }
                    stu.setCreator(creator);
                    stu.setModifier(modifier);
                    stu.setCreationTime(creationTime);
                    stu.setModificationTime(modificationTime);
                    studenService.create(stu);
                    System.out.println("stu"+stu);
                    new_len++;
                    log.info("导入" + (i + 1) + "行");
                }else{
                    log.info("第" + (i + 1) + "行已存在");
                    edit_len++;
                    new_len--;
                }

//                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);
//                if (point == null) {

//                } 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.setDept(dept);
//                    point.setDescription(ccTYPE);
//                    point.setPosX(x);
//                    point.setPosY(y);
//                    pointService.update(point);
//                    edit_len++;
//                }

                if(new_len<0){
                    new_len=0;
                }
            }
        }
        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()));

    }


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

    @GetMapping
    @Log("查询studen")
    @ApiOperation("查询studen")
    @PreAuthorize("@el.check('studen:list')")
    public ResponseEntity<Object> queryStuden(StudenQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(studenService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增studen")
    @ApiOperation("新增studen")
    @PreAuthorize("@el.check('studen:add')")
    public ResponseEntity<Object> createStuden(@Validated @RequestBody Studen resources){
        return new ResponseEntity<>(studenService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改studen")
    @ApiOperation("修改studen")
    @PreAuthorize("@el.check('studen:edit')")
    public ResponseEntity<Object> updateStuden(@Validated @RequestBody Studen resources){
        studenService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除studen")
    @ApiOperation("删除studen")
    @PreAuthorize("@el.check('studen:del')")
    public ResponseEntity<Object> deleteStuden(@RequestBody Integer[] ids) {
        studenService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}