/*
*  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.base.BaseEntity;
import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.repository.DesignListRepository;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.service.DesignListService;
import com.youchain.basicdata.service.dto.DesignListQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.handler.ApiError;
import com.youchain.utils.FileUtil;
import com.youchain.utils.OptionalUtils;
import com.youchain.utils.SecurityUtils;
import com.youchain.utils.UserUtils;
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.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @author LY
* @date 2024-04-26
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "design管理")
@RequestMapping("/api/designList")
public class DesignListController {

    private final DesignListService designListService;


    //导入
    private final FileProperties properties;
    private final DesignListRepository designListRepository;
    private final BigItemRepository bigItemRepository;
    private final ItemRepository itemRepository;

    @Log("导入设变清单")
    @PostMapping(value = "/importDesignList")
    @ApiOperation("导入设变清单")
    @PreAuthorize("@el.check('designList:list')")
    public ResponseEntity<Object> importAutomaticPlanning(@RequestParam("file") MultipartFile multipartFile) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        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);
        ExcelReader reader = ExcelUtil.getReader(file);
        List<Map<String, Object>> readAll = reader.readAll();
        int i = 0;
        for (i = 0; i < readAll.size(); i++) {
            String no = OptionalUtils.getTrimmedString(readAll.get(i), "No", null);
            if(no==null||no.equals("")){
                break;
            }
            String bt = OptionalUtils.getTrimmedString(readAll.get(i), "変通No.11桁", null);
            String sbh = OptionalUtils.getTrimmedString(readAll.get(i), "设变号", null);
            String ykfh = OptionalUtils.getTrimmedString(readAll.get(i), "一括番号", null);
            String jfh = OptionalUtils.getTrimmedString(readAll.get(i), "旧品番", null);
            String glsb =OptionalUtils.getTrimmedString(readAll.get(i), "关联设变", null);
            String xfh = OptionalUtils.getTrimmedString(readAll.get(i), "新品番", null);
            String gysdm =OptionalUtils.getTrimmedString(readAll.get(i), "供应商代码", null);
            String gysmc = OptionalUtils.getTrimmedString(readAll.get(i), "供应商名称", null);
            String ac = OptionalUtils.getTrimmedString(readAll.get(i), "A/C", null);
            String jgnr =OptionalUtils.getTrimmedString(readAll.get(i), "加工内容", null);
            String pm = OptionalUtils.getTrimmedString(readAll.get(i), "品名(中文)", null);
            Integer dy = OptionalUtils.getTrimmedInteger(readAll.get(i), "单用", 0);
            boolean yf = OptionalUtils.getBooleanValue(readAll.get(i), "订货要否", false);
            String ns = OptionalUtils.getTrimmedString(readAll.get(i), "纳所", null);
            String ycl = OptionalUtils.getTrimmedString(readAll.get(i), "月产量", null);
            String txdm =OptionalUtils.getTrimmedString(readAll.get(i), "T型式代码", null);
            String txm = OptionalUtils.getTrimmedString(readAll.get(i), "T型式名", null);
            String jpcl = OptionalUtils.getTrimmedString(readAll.get(i), "旧品处理", null);
            String xtss = OptionalUtils.getTrimmedString(readAll.get(i), "系统\n" + "实施日", null);
            DesignList d=new DesignList();
            d.setNo(no);
            d.setChaseCenter(bt);
            d.setContraposition(sbh);
            d.setDesignation(ykfh);
            d.setHypothesis(glsb);
            d.setSupplierCode(gysdm);
            d.setSupplierName(gysmc);
            d.setAc(ac);
            d.setContent(jgnr);
            d.setProductName(pm);
            d.setUseSingly(dy);
            d.setEnable(yf);
            d.setNaso(ns);
            d.setMonthlyOutput(ycl);
            d.setTTypeCode(txdm);
            d.setTTypeName(txm);
            d.setScrapDisposal(jpcl);
            d.setImplementationDate(xtss);
            d.setCreateBy(SecurityUtils.getCurrentUser().getUsername());
            //查询完成品番的id
            BigItem bigItem = bigItemRepository.findByCode(txdm);
            //查询旧品番的id
            Item oitem = itemRepository.findByCode(jfh);
            //查询新品番的id
            Item nitem = itemRepository.findByCode(xfh);
            d.setNitem(nitem);
            d.setOitem(oitem);
            d.setBigItem(bigItem);
            d.setOldItemCode(jfh);
            d.setNewItemCode(xfh);
            d.setBigItemCode(txdm);
            designListService.create(d);
        }
        return new ResponseEntity<>("导入成功",HttpStatus.OK);
    }


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('designList:list')")
    public void exportDesignList(HttpServletResponse response, DesignListQueryCriteria criteria) throws Exception {
        designListService.download(designListService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询design")
    @ApiOperation("查询design")
    @PreAuthorize("@el.check('designList:list')")
    public ResponseEntity<Object> queryDesignList(DesignListQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(designListService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增design")
    @ApiOperation("新增design")
    @PreAuthorize("@el.check('designList:add')")
    public ResponseEntity<Object> createDesignList(@Validated @RequestBody DesignList resources){
        return new ResponseEntity<>(designListService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改design")
    @ApiOperation("修改design")
    @PreAuthorize("@el.check('designList:edit')")
    public ResponseEntity<Object> updateDesignList(@Validated @RequestBody DesignList resources){
        designListService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

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