/*
*  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.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.youchain.DuplicateSubmission.DuplicateSubmission;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.BomAccountRepository;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.repository.TableConfigRepository;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.BomAccountLogService;
import com.youchain.basicdata.service.BomAccountService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.*;
import com.youchain.basicdata.service.impl.TableConfigServiceImpl;
import com.youchain.basicdata.service.mapstruct.BomAccountMapper;
import com.youchain.businessdata.returnJson.*;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.*;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.JsonUtil;
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.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @author baobinglin
* @date 2024-01-02
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "bomAccount管理")
@RequestMapping("/api/bomAccount")
public class BomAccountController {

    private final BomAccountService bomAccountService;
    private final BomAccountLogService bomAccountLogService;
    private final BomAccountMapper bomAccountMapper;
    private final PointRepository pointRepository;
    private final PointService pointService;
    private final AreaService areaService;
    private final BomAccountRepository bomAccountRepository;

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

    @GetMapping
    @Log("查询bomAccount")
    @ApiOperation("查询bomAccount")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomAccount(BomAccountQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(bomAccountService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @GetMapping("/queryBomAccountList")
    @Log("查询bomAccount全部")
    @ApiOperation("查询bomAccount全部")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomAccountList(BomAccountQueryCriteria criteria){
        return new ResponseEntity<>(bomAccountService.queryAll(criteria),HttpStatus.OK);
    }


    @GetMapping("/queryBomPrintListD")
    @Log("查询中大物标签")
    @ApiOperation("查询中大物标签")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomPrintListD(BomAccountQueryCriteria criteria){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        redisUtils.del(SecurityUtils.getCurrentUsername()+"_BiaoQian_D");
        List<BomPrint> list=bomAccountService.queryPrintAll(criteria,"中大物标签");
        redisUtils.set(SecurityUtils.getCurrentUsername()+"_BiaoQian_D",JsonUtil.toJson(list));
        return new ResponseEntity<>(list,HttpStatus.OK);
    }

    @GetMapping("/queryBomPrintListX")
    @Log("查询小物标签")
    @ApiOperation("查询小物标签")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomPrintListX(BomAccountQueryCriteria criteria){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        redisUtils.del(SecurityUtils.getCurrentUsername()+"_BiaoQian_X");
        List<BomPrint> list=bomAccountService.queryPrintAll(criteria,"小物标签");
        redisUtils.set(SecurityUtils.getCurrentUsername()+"_BiaoQian_X",JsonUtil.toJson(list));
        return new ResponseEntity<>(list,HttpStatus.OK);
    }

    @GetMapping("/queryBomPrintListTC_old")
    @Log("查询台车标签")
    @ApiOperation("查询台车标签")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomPrintListTC_old(BomAccountQueryCriteria criteria){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        redisUtils.del(SecurityUtils.getCurrentUsername()+"_BiaoQian_TC");
        List<BomPrint> list=bomAccountService.queryTckwPrintAll(criteria);
        redisUtils.set(SecurityUtils.getCurrentUsername()+"_BiaoQian_TC",JsonUtil.toJson(list));
        return new ResponseEntity<>(list,HttpStatus.OK);
    }

    @GetMapping("/queryBomPrintListTC")
    @Log("查询台车标签")
    @ApiOperation("查询台车标签")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomPrintListTC(BomAccountQueryCriteria criteria){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        redisUtils.del(SecurityUtils.getCurrentUsername()+"_BiaoQian_TC");
        List<BomPrint> list=bomAccountService.queryTckwPrintAll(criteria);
        redisUtils.set(SecurityUtils.getCurrentUsername()+"_BiaoQian_TC",JsonUtil.toJson(list));
        return new ResponseEntity<>(list,HttpStatus.OK);
    }
    @GetMapping("/queryBomPrintList")
    @Log("查询Bom标签")
    @ApiOperation("查询Bom标签")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomPrintList(BomAccountQueryCriteria criteria,Pageable pageable){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        redisUtils.del(SecurityUtils.getCurrentUsername()+BaseStatus.XWBQ);
        redisUtils.del(SecurityUtils.getCurrentUsername()+BaseStatus.ZDWBQ);
        List<BomPrint> list=bomAccountService.queryPrintAll(criteria);
        List<String> sortList=new ArrayList<>();
        HashMap<String ,List<BomPrint>> map=new HashMap<>();
        for(BomPrint l:list){
            String key=l.getCode()+"]"+l.getNs()+"]"+l.getBonded()+"]"+l.getHw();
            if(map.containsKey(key)){
                List<BomPrint> list2=map.get(key);
                list2.add(l);
                map.put(key,list2);
            }else{
                List<BomPrint> list2=new ArrayList<>();
                list2.add(l);
                map.put(key,list2);
                sortList.add(key);
            }
        }
        List<BomPrint_BiaoQian> list2=new ArrayList<>();
        List<BomPrint_BiaoQian> listd=new ArrayList<>();
        List<BomPrint_BiaoQian> listx=new ArrayList<>();
//        for (String key : map.keySet()) {
        for(String key:sortList){
            List<BomPrint> bqs=map.get(key);
            BomPrint_BiaoQian bq=new BomPrint_BiaoQian();
            BomPrint l=bqs.get(0);
            String code=l.getCode().substring(0,5)+"-"+l.getCode().substring(5,l.getCode().length());
            bq.setNs(l.getNs()+"/"+code);
            bq.setNsv(l.getNs());
            bq.setCode(code);
            String hw=l.getHw();
            hw=hw.substring(0,3)+"-"+hw.substring(3,hw.length());
            bq.setHw(hw);
            bq.setPm(l.getPm());
            bq.setEwm(key);
            bq.setBonded(l.getBonded());
            bq.setSrs(l.getSrs());
            bq.setXz(l.getXz());
            bq.setSupplier(l.getSupplier());
            bq.setDxw(l.getDxw());
            bq.setId(l.getId());
            String[] jxs=new String[bqs.size()];
            String[] tyls=new String[bqs.size()];
            String jx="";
            String tyl="";
            for(int i=0;i<bqs.size();i++){
                jxs[i]=bqs.get(i).getJxs();
                tyls[i]=bqs.get(i).getTyls();
                jx+=bqs.get(i).getJxs()+";";
                tyl+=bqs.get(i).getTyls()+";";
            }
            bq.setJx(jx);
            bq.setTyl(tyl);
            bq.setJxs(jxs);
            bq.setTyls(tyls);
            list2.add(bq);
            if(l.getDxw()!=null&&l.getDxw().equals("中大物标签")){
                listd.add(bq);
            }else if(l.getDxw()!=null&&l.getDxw().equals("小物标签")){
                listx.add(bq);
            }
        }
        redisUtils.set(SecurityUtils.getCurrentUsername()+BaseStatus.XWBQ,JsonUtil.toJson(listx));
        redisUtils.set(SecurityUtils.getCurrentUsername()+BaseStatus.ZDWBQ,JsonUtil.toJson(listd));
        Map<String,Object> map2=new HashMap<>();
        int pageNum=pageable.getPageNumber();//当前页
        int pageSize=pageable.getPageSize();//条数
        List<BomPrint_BiaoQian> result = list2.stream()
                .skip((pageNum)*pageSize)  // 跳过前100个
                .limit(pageSize) // 取100个（101-200行）
                .collect(Collectors.toList());
        map2.put("content",result);
        map2.put("totalElements",list2.size());
        return new ResponseEntity<>(map2,HttpStatus.OK);
    }


    @GetMapping("/queryBomTckwPrintList")
    @Log("查询Bom台车标签")
    @ApiOperation("查询Bom台车标签")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomTckwPrintList(BomAccountQueryCriteria criteria,Pageable pageable){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        redisUtils.del(SecurityUtils.getCurrentUsername()+BaseStatus.TCBQ);
        List<BomPrint> list=bomAccountService.queryTckwPrintAll(criteria);
        List<BomPrint_BiaoQian> list_bq=new ArrayList<>();
        for(BomPrint p:list){
            BomPrint_BiaoQian bq=new BomPrint_BiaoQian();
//            String key=p.getHw();
//            String jx=p.getJxs();
//            String[] jxs=jx.split(",");
//            bq.setCode(key);
//            bq.setHw(key);
//            bq.setJxs(jxs);
//            bq.setJx(jx);
            bq.setCode(p.getCode());
            bq.setHw(p.getHw());
            bq.setPm(p.getPm());
            bq.setJx(p.getCode());
            bq.setEwm(p.getHw()+"]"+p.getCode());
            list_bq.add(bq);
        }
        redisUtils.set(SecurityUtils.getCurrentUsername()+BaseStatus.TCBQ,JsonUtil.toJson(list_bq));
        Map<String,Object> map2=new HashMap<>();
        int pageNum=pageable.getPageNumber();//当前页
        int pageSize=pageable.getPageSize();//条数
        List<BomPrint_BiaoQian> result = list_bq.stream()
                .skip((pageNum)*pageSize)  // 跳过前100个
                .limit(pageSize) // 取100个（101-200行）
                .collect(Collectors.toList());
        map2.put("content",result);
        map2.put("totalElements",list_bq.size());
        return new ResponseEntity<>(map2,HttpStatus.OK);
    }
    @GetMapping("/bomPrintBiaoQianList/{dxw}")
    @Log("获取Bom中库位标签")
    @ApiOperation("获取Bom中库位标签")
    @AnonymousAccess
    public ResponseEntity<Object> bomPrintBiaoQianList(@PathVariable("dxw") String dxw){
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        String key=SecurityUtils.getCurrentUsername()+dxw;
        String json=(String)redisUtils.get(key);
        log.info("---"+key+"-----"+json);
        List<BomPrint_BiaoQian> list= JSONUtil.toList(json, BomPrint_BiaoQian.class);
        return new ResponseEntity<>(list,HttpStatus.OK);
    }


    @GetMapping(value = "/queryBigItemByStationType/{stationType}")
    @Log("根据工位查询bomAccount")
    @ApiOperation("根据工位查询bomAccount")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomAccountByStationType(@PathVariable("stationType") String stationType){
        List<BigItem> bigItems = bomAccountService.queryBigItemByType(stationType);
        return new ResponseEntity<>(bigItems,HttpStatus.OK);
    }

    @GetMapping(value = "/queryItemByArea/{areaId}")
    @Log("根据库区查询bomAccount品番")
    @ApiOperation("根据库区查询bomAccount品番")
    @AnonymousAccess
    public ResponseEntity<Object> queryItemByArea(@PathVariable("areaId") Long areaId){
        List<BomAccountDto> boms=bomAccountService.queryByArea(areaId);
        return new ResponseEntity<>(boms,HttpStatus.OK);
    }

    @GetMapping(value = "/queryByAreaId/{areaId}")
    @Log("根据库区查询bomAccount完成品品番")
    @ApiOperation("根据库区查询bomAccount完成品品番")
    @AnonymousAccess
    public ResponseEntity<Object> queryByAreaId(@PathVariable("areaId") Long areaId){
        List<BigItem> boms=bomAccountService.queryByAreaId(areaId);
        return new ResponseEntity<>(boms,HttpStatus.OK);
    }

    @GetMapping(value = "/queryBomAccountPoints")
    @Log("查询bomAccount品番库位")
    @ApiOperation("查询bomAccount品番库位")
    @AnonymousAccess
    public ResponseEntity<Object> queryBomAccountPoints(){
        List<BomAccountPointDto> boms=bomAccountService.queryBomAccountPoints();
        return new ResponseEntity<>(boms,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增bomAccount")
    @ApiOperation("新增bomAccount")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createBomAccount(@Validated @RequestBody BomAccount resources){
        Area area=areaService.findByCode(BaseStatus.DEFAULT_AREA);
        resources.setRArea(resources.getZPoint().getArea());
        resources.setCArea(area);
        resources.setBigItemName(resources.getBigItem().getName());
        resources.setBigItemCode(resources.getBigItem().getCode());
        resources.setEnabled(true);
        resources.setBp_type("大");
        return new ResponseEntity<>(bomAccountService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改bomAccount")
    @ApiOperation("修改bomAccount")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updateBomAccount(@Validated @RequestBody BomAccount resources){
        resources.setBigItemName(resources.getBigItem().getName());
        resources.setBigItemCode(resources.getBigItem().getCode());
        resources.setRArea(resources.getZPoint().getArea());
        bomAccountService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除bomAccount")
    @ApiOperation("删除bomAccount")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> deleteBomAccount(@RequestBody Long[] ids) {
        bomAccountService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/tcOut")
    @Log("台车配料出库")
    @ApiOperation("台车配料出库")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(10)
    public ResponseEntity<Object> tcOut(@Validated @RequestBody String[] tckws){
        for (String tckw : tckws) {
            bomAccountService.tcCount(tckw,null);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/tcOutApp")
    @Log("台车配料出库App")
    @ApiOperation("台车配料出库")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(10)
    public ResponseEntity<Object> tcOutApp( @RequestBody HashMap map){
        String ewm=map.get("tckw")==null?null:map.get("tckw").toString();
        String tckw=null;
        String bigItemCode=null;
        if(ewm.length()>=82) {
            tckw=ewm.substring(3,13);
        }else{
            String[] tckws = ewm.split("]");
            if (tckws.length < 2) {
                throw new BadRequestException("扫描内容有误");
            }
            tckw=tckws[0];
            bigItemCode=tckws[1];
        }
        bomAccountService.tcCount(tckw,bigItemCode);
        return new ResponseEntity<>("配料成功", HttpStatus.OK);
    }

    @PostMapping("/tcOutList")
    @Log("制造叫料拣货列表")
    @ApiOperation("制造叫料拣货列表")
    @AnonymousAccess
    public ResponseEntity<Object> tcOutList(@RequestBody HashMap map) throws Exception {
        String ewm=map.get("tckw")==null?null:map.get("tckw").toString();
        String tckw=null;
        String bigItemCode=null;
        if(ewm.length()>=82) {
            tckw=ewm.substring(3,13);
        }else{
            String[] tckws = ewm.split("]");
            if (tckws.length < 2) {
                throw new BadRequestException("扫描内容有误");
            }
            tckw=tckws[0];
            bigItemCode=tckws[1];
        }
        //查询叫料返回数据
        List<TcOutList> list=bomAccountService.queryTckwList(tckw,bigItemCode);
        return new ResponseEntity<>(list,HttpStatus.OK);
    }
}