/*
 *  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.businessdata.rest;

import com.alibaba.fastjson.JSON;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.AutomaticPlanDetailRepository;
import com.youchain.basicdata.repository.BillTypeRepository;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.BomAccountService;
import com.youchain.basicdata.service.dto.BomAccountDto;
import com.youchain.basicdata.service.impl.BomAccountServiceImpl;
import com.youchain.businessdata.domain.PickDetail;
import com.youchain.businessdata.domain.PickTicket;
import com.youchain.businessdata.domain.PlanPickDetail;
import com.youchain.businessdata.inputJson.buttenJson.PlanPickButton;
import com.youchain.businessdata.inputJson.buttenJson.PlanPickSave;
import com.youchain.businessdata.inputJson.buttenJson.ProductionPlanButton;
import com.youchain.businessdata.repository.PickDetailRepository;
import com.youchain.businessdata.repository.PickTicketRepository;
import com.youchain.businessdata.repository.PlanPickDetailRepository;
import com.youchain.businessdata.service.InventoryService;
import com.youchain.businessdata.service.PickDetailService;
import com.youchain.businessdata.service.PickTicketService;
import com.youchain.businessdata.service.PlanPickDetailService;
import com.youchain.businessdata.service.dto.PlanPickDetailQueryCriteria;
import com.youchain.businessdata.service.impl.PickDetailServiceImpl;
import com.youchain.businessdata.service.impl.PlanPickDetailServiceImpl;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.BaseStatus;
import com.youchain.utils.BizStatus;
import com.youchain.utils.CodeUtils;
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.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.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jiangkun
 * @website https://eladmin.vip
 * @date 2024-01-23
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "planPickDetail管理")
@RequestMapping("/api/planPickDetail")
public class PlanPickDetailController {

    private final PlanPickDetailService planPickDetailService;
    private final PlanPickDetailRepository planPickDetailRepository;
    private final BillTypeRepository billTypeRepository;
    private final PickTicketService pickTicketService;
    private final PickTicketRepository pickTicketRepository;
    private final FileProperties properties;
    private final BomAccountService bomAccountService;
    private final PickDetailService ptdService;
    private final AreaService areaService;
    private final CodeUtils codeUtils;
    private final PickDetailRepository pickDetailRepository;
    private final InventoryService inventoryService;
    private final AutomaticPlanDetailRepository automaticPlanDetailRepository;

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

    @GetMapping
    @Log("查询planPickDetail")
    @ApiOperation("查询planPickDetail")
    @AnonymousAccess
    public ResponseEntity<Object> queryPlanPickDetail(PlanPickDetailQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(planPickDetailService.queryAll(criteria, pageable), HttpStatus.OK);
    }


    @GetMapping("/getAllCode")
    @Log("获取全部单号做下拉")
    @ApiOperation("获取全部单号做下拉")
    @AnonymousAccess
    public ResponseEntity<Object> getAllCode() {
//        //获取单号
//        List<PlanPickDetail> planPickDetails = planPickDetailRepository.queryPlanPickDetailByCode();
//        //获取所有的code
//        List<String> collect = planPickDetails.stream().map(PlanPickDetail::getCode).collect(Collectors.toList());
        List<String> collect = planPickDetailRepository.queryPlanPickDetailCode();
        return new ResponseEntity<>(collect, HttpStatus.OK);
    }

    @PostMapping
    @Log("新增planPickDetail")
    @ApiOperation("新增planPickDetail")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createPlanPickDetail(@Validated @RequestBody PlanPickDetail resources) {
        if(resources.getZone()!=null) {
            resources.setGcCode(resources.getZone().getGcCode());
        }
        return new ResponseEntity<>(planPickDetailService.create(resources), HttpStatus.CREATED);
    }

    @PostMapping("/cancelStockOperation")
    @Log("取消备货操作")
    @ApiOperation("取消备货操作")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> cancelStockOperation(@RequestBody PlanPickButton resources) {
        List<PlanPickDetail> planPickDetailList = resources.getPlanPickDetailList();
        //去重  获取单号
        List<String> collect = planPickDetailList.stream().map(PlanPickDetail::getCode).distinct().collect(Collectors.toList());
        for (String planPickDetailCode : collect) {
            //其他出库的删除
            List<PickTicket> pickTickets = pickTicketRepository.queryPickTicketByCodeAll(BizStatus.OPEN, "%"+planPickDetailCode+"%");
            for (PickTicket pt : pickTickets) {
                //查明细表的数据
                List<PickDetail> pickDetails = pickDetailRepository.queryByPickTicketId(pt.getId());
                for (PickDetail pd : pickDetails) {
                    pickDetailRepository.delete(pd);
                }
                pickTicketRepository.deleteById(pt.getId());
            }
            //备货计划明细修改
            List<PlanPickDetail> planPickDetails = planPickDetailRepository.findByStatusAndCode(BizStatus.YCD, planPickDetailCode);
            for (PlanPickDetail ppd : planPickDetails) {
                ppd.setStatus(BizStatus.WCD);
                planPickDetailService.update(ppd);
            }
        }
        return new ResponseEntity<>("取消备货成功", HttpStatus.OK);
    }


    @PostMapping("/generateStockOperation")
    @Log("生成备货操作")
    @ApiOperation("生成备货操作")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    public ResponseEntity<Object> generateStockOperation(@RequestBody PlanPickButton resources) {
        HashMap<String,String> map=new HashMap<String,String>();
        for (PlanPickDetail ppd : resources.getPlanPickDetailList()) {
           // planPickDetailService.createAutoPlan(1,ppd.getCode(),ppd.getZone().getId(),null,Boolean.FALSE,ppd.getCreateTime());
            map.put(ppd.getCode(),ppd.getCode());
//            if(codes.size()>=2){
//                throw new BadRequestException(HttpStatus.NOT_FOUND, ppd.getCode() + "请选择相同的单号");
//            }`
            if (!ppd.getStatus().equals(BizStatus.WCD)) {
                throw new BadRequestException(HttpStatus.NOT_FOUND, ppd.getBigItem().getCode() + "状态不正确");
            }
        }
//        //选中的数据
//        PlanPickDetail ppd_o = resources.getPlanPickDetailList().get(0);
//        //根据code 和 status 查询数据
//        List<PlanPickDetail> planPickDetails = planPickDetailService.queryPlanPickDetail(ppd_o.getCode());
//
//        for (PlanPickDetail ppd : planPickDetails) {
//            if (!ppd.getStatus().equals(BizStatus.WCD)) {
//                throw new BadRequestException(HttpStatus.NOT_FOUND, ppd.getBigItem().getCode() + "状态不正确");
//            }
//            List<BomAccount> bs = bomAccountService.queryBomAccount(ppd.getBigItem().getId(), ppd.getZone().getId(),ppd.getZone().getWorkingStation());
//            if (bs.size() <= 0) {
//                throw new BadRequestException(HttpStatus.NOT_FOUND, ppd.getBigItem().getCode() + "未查到对应工位清单");
//            }
//            ppd.setPickedQuantity(ppd.getOrderQuantity());
//            ppd.setStatus(BizStatus.YCD);
//            planPickDetailService.update(ppd);
//        }
        planPickDetailService.createAutoPlan(map.keySet().toArray(new String[map.size()]),null,"");
//        //得到所有的物料和明细
//        List<Object[]> objPicks = bomAccountService.queryBomAccountList(ppd_o.getCode(),null, ppd_o.getZone().getId(), null,"0");
////        String bpType="大";
//        for (Object[] objPick : objPicks) {
//            Long oAreaId = (Long) objPick[0];
//            String bpType = (String) objPick[1];
//            Area oArea=areaService.findEntityById(oAreaId);
//            //出库数据 pickTicket 其他出库
//            PickTicket pickTicket = pickTicketService.storePick(ppd_o.getBillType(), ppd_o.getZone(),oArea, bpType, ppd_o.getCode());
//            double orderQty = 0;
//            List<Object[]> objs = bomAccountService.queryBomAccountList(ppd_o.getCode(),oAreaId, ppd_o.getZone().getId(), bpType, "1");
//            //需求数量
//            double xqty = 0d;
//            //纯需求数量
//            double cxqty = 0d;
//            double xbsum=0d;
//            for (Object[] obj : objs) {
//                Long bId = (Long) obj[0];
//                double single = (Double) obj[1];
//                BomAccount ba = bomAccountService.findByEntity(bId);
//                PickDetail ptd = new PickDetail();
//                //需求数xq_qty=数量*单用
//                ptd.setXqQty(single);
//                //纯需求数orderQty=备货需求-线边数
//                Double xbQty=inventoryService.getInvQty(ba.getItem().getId(),pickTicket.getShArea().getId(),ba.getZPoint().getId());
//                ptd.setXbQty(xbQty);
//                xbsum+=xbQty;
//                if(xbQty.intValue()>=ptd.getXqQty().intValue()){
//                    ptd.setPropC4(0d);
//                }else {
//                    ptd.setPropC4(ptd.getXqQty() - ptd.getXbQty());
//                }
//                ptd.setPureXqBz(ptd.getPropC4());
//                //备货需求=（纯需求数/收容数向上取整）*收容数
//                ptd.setOrderQty(Math.ceil(ptd.getPropC4()/ba.getItem().getExtendD3())*ba.getItem().getExtendD3());
//                xqty += ptd.getXqQty();
//                cxqty += ptd.getPropC4();
//                ptd.setPoint(ba.getZPoint());
//                ptd.setItem(ba.getItem());
//                ptd.setPickTicket(pickTicket);
//                ptd.setContents(ba.getContents());
//                ptd.setAc(ba.getAc());
//                ptd.setSupplier(ba.getSupplier());
//                ptdService.create(ptd);
//                orderQty += ptd.getOrderQty();
//            }
//            pickTicket.setOrderQuantity(orderQty);
//            pickTicket.setBhQty(orderQty);
//            //纯需求数
//            pickTicket.setPureReqQty(cxqty);
//            //需求数量
//            pickTicket.setXqQty(xqty);
//            pickTicket.setXbQty(xbsum);
////            pickTicket.setStockingDate(new Timestamp(new Date().getTime()));
//            pickTicketRepository.save(pickTicket);
//        }
        return new ResponseEntity<>("备货成功", HttpStatus.OK);
    }

    @PostMapping("/savePlanPickDetail")
    @Log("新增planPickDetail")
    @ApiOperation("新增planPickDetail")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> savePlanPickDetail(@RequestBody PlanPickButton resources) {
        PlanPickSave planPickSave = resources.getPlanPickSave();
        if (planPickSave.getCode() == null||planPickSave.getCode().equals("")) {
            planPickSave.setCode(codeUtils.getCode_yyMMdd("JH", 3));
        }
        String code=planPickSave.getCode();
//        //判断是否在一个工位
//        List ls=planPickDetailService.queryGwList(code,planPickSave.getZone().getCode());
//        if(ls.size()>0){
//            throw new BadRequestException(HttpStatus.NOT_FOUND, planPickSave.getCode() + "请选择相同工位");
//        }
        //判断是否在一个工位
        List statuss=planPickDetailService.queryStatusList(code);
        if(statuss.size()>0){
            throw new BadRequestException(HttpStatus.NOT_FOUND,code + "仅未出单才可新增");
        }
        //插入bigitem，数量，单据类型为CKD单点，JH+年月日+3位流水
        PlanPickDetail planPickDetail = new PlanPickDetail();
        planPickDetail.setBigItem(planPickSave.getBigItem());
        //备货数量
        planPickDetail.setPickedQuantity(planPickSave.getOrderQuantity());
        //起始机号
//        planPickDetail.setStartNo(manualGeneration.getStartMachineNo());
        planPickDetail.setStatus(BizStatus.WCD);
        planPickDetail.setShippedQuantity(0d);
        planPickDetail.setAllocatedQuantity(0d);
        planPickDetail.setOrderQuantity(planPickSave.getOrderQuantity());
        //入库库区
        planPickDetail.setZone(planPickSave.getZone());
        planPickDetail.setGcCode(planPickSave.getZone().getGcCode());
        //单据类型(出库类型)
        BillType billType = billTypeRepository.findByName(BaseStatus.BT_DD);
        planPickDetail.setBillType(billType);
        planPickDetail.setRemark("手工维护");
        //存单号
        planPickDetail.setCode(code);
        planPickDetailService.create(planPickDetail);
        return new ResponseEntity<>("新增成功", HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改planPickDetail")
    @ApiOperation("修改planPickDetail")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updatePlanPickDetail(@Validated @RequestBody PlanPickDetail resources) {
        planPickDetailService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

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