/*
*  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.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.StockType;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.StockTypeService;
import com.youchain.basicdata.service.dto.ItemDto;
import com.youchain.basicdata.service.dto.ItemQueryCriteria;
import com.youchain.basicdata.service.dto.StockTypeQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.handler.ApiError;
import com.youchain.modules.system.domain.DictDetail;
import com.youchain.modules.system.service.DictDetailService;
import com.youchain.modules.system.service.DictService;
import com.youchain.modules.system.service.dto.DictDetailDto;
import com.youchain.modules.system.service.dto.DictDto;
import com.youchain.modules.system.service.dto.DictQueryCriteria;
import com.youchain.utils.FileUtil;
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.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;


/**
* @website https://eladmin.vip
* @author houjianlan
* @date 2023-08-16
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "item管理")
@Slf4j
@RequestMapping("/api/item")
public class ItemController {

    private final ItemService itemService;
    private final FileProperties properties;
    private final StockTypeService stockTypeService;
    private final DictDetailService dictDetailService;

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

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

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

    @PostMapping(value = "/import_data")
    @ApiOperation("导入物料")
    @Transactional
    @AnonymousAccess
    public ResponseEntity<Object> createSysAppUpdate( @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());

        Map<String, StockType> map_stock = stockTypeService.queryAll();
        DictQueryCriteria dictQueryCriteria=new DictQueryCriteria();
        dictQueryCriteria.setBlurry("item_unit");
        Map<String, DictDetail> map_dic = dictDetailService.getDictDetailByName("item_unit");



        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++) {
                Item item = new Item();
                item.setExtendStr1("" + readAll.get(i).get("产品"));
                log.error(i+"---" + readAll.get(i).get("编码")+"--");
                String code=readAll.get(i).get("编码").toString().trim();
                item.setCode(code);
                item.setExtendD1(Double.parseDouble(readAll.get(i).get("规划节拍") + ""));
                item.setExtendD2(Double.parseDouble(readAll.get(i).get("UPH") + ""));
                item.setName("" + readAll.get(i).get("物料名称"));
                item.setExtendNum3(Long.parseLong(readAll.get(i).get("BOM") + ""));
                String unit=readAll.get(i).get("单位")+"";
                item.setUnit(map_dic.get(unit).getValue());
                //容器类型
                String stocktype_Str = "" + readAll.get(i).get("规划存储容器");
                item.setStockType(map_stock.get(stocktype_Str));
                item.setLength(Double.parseDouble("" + readAll.get(i).get("长")));
                item.setWidth(Double.parseDouble("" + readAll.get(i).get("宽")));
                item.setHeight(Double.parseDouble("" + readAll.get(i).get("高")));
                item.setExtendNum4(Long.parseLong(readAll.get(i).get("存储装载量(单元包装方式1") + ""));
                item.setExtendD3(Double.parseDouble("" + readAll.get(i).get("小时流量(箱)")));
                item.setExtendD4(Double.parseDouble("" + readAll.get(i).get("缓存量周期（H）")));
                item.setExtendD5(Double.parseDouble("" + readAll.get(i).get("线边缓存量（箱）")));

                ItemQueryCriteria itemQueryCriteria=new ItemQueryCriteria();
                itemQueryCriteria.setCode(code);
                List<ItemDto> itemDto_list=itemService.queryAll(itemQueryCriteria);
                if(itemDto_list.size()<=0){
                    new_len++;
                    log.error("不存在--" + readAll.get(i).get("编码")+"--");
                    itemService.create(item);
                }else{
                    edit_len++;
                    log.error("存在--" + readAll.get(i).get("编码")+"--");
                    item.setId(itemDto_list.get(0).getId());
                    itemService.update(item);
                }
            }
        }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()));

    }

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

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