package cn.ezhizao.project.business.controller;


import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;


import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.datasource.DynamicDataSource;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.*;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 盘点时间Controller
 *
 * @author ezhizao
 * @date 2024-08-15
 */
@RestController
@RequestMapping("/business/takeStockPeriod")
public class BizTakeStockPeriodController extends BaseController
{
    @Resource
    private IBizTakeStockPeriodService bizTakeStockPeriodService;
    @Resource
    private IBizDayworkService bizDayworkService;
    @Resource
    private IBizTaksStockLotService bizTaksStockLotService;
    @Resource
    private IBizLotService bizLotService;
    @Resource
    private IBizTaksStockStorageRetrievalService bizTaksStockStorageRetrievalService;
    @Resource
    private IBizStorageRetrievalService bizStorageRetrievalService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;

    /**
     * 查询盘点时间列表
     */
    @GetMapping("/list")
    @Log(title = "查询盘点时间列表", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizTakeStockPeriod bizTakeStockPeriod) throws NoSuchFieldException, IllegalAccessException
    {
        List<BizTakeStockPeriod> allList = bizTakeStockPeriodService.query().list();
        boolean hasTakeStockStatus = allList.stream().anyMatch(item -> item.getStatus() == 1);
        boolean hasAddTakeStockStatus = allList.stream().anyMatch(item -> item.getStatus() == 0);
        if(bizTakeStockPeriod.getCreateStartTime()!=null) {
            bizTakeStockPeriod.setCreateStartTime(bizTakeStockPeriod.getCreateStartTime()+ " 00:00:00");
        }
        if(bizTakeStockPeriod.getCreateEndTime()!=null) {
            bizTakeStockPeriod.setCreateEndTime(bizTakeStockPeriod.getCreateEndTime()+ " 23:59:59");
        }
        if(bizTakeStockPeriod.getStartTimeStr()!=null) {
            bizTakeStockPeriod.setStartTimeStr(bizTakeStockPeriod.getStartTimeStr()+ " 00:00:00");
        }
        if(bizTakeStockPeriod.getStartTimeEnd()!=null) {
            bizTakeStockPeriod.setStartTimeEnd(bizTakeStockPeriod.getStartTimeEnd()+ " 23:59:59");
        }
        if(bizTakeStockPeriod.getEndTimeStr()!=null) {
            bizTakeStockPeriod.setEndTimeStr(bizTakeStockPeriod.getEndTimeStr()+ " 00:00:00");
        }
        if(bizTakeStockPeriod.getEndTimeEnd()!=null) {
            bizTakeStockPeriod.setEndTimeEnd(bizTakeStockPeriod.getEndTimeEnd()+ " 23:59:59");
        }
        startPage();
        List<BizTakeStockPeriod> list = bizTakeStockPeriodService.getList(bizTakeStockPeriod);
        TableDataInfo info = getDataTable(list);
        Map<String, Object> map = new HashMap<>();
        map.put("hasTakeStockStatus",hasTakeStockStatus);
        map.put("hasAddTakeStockStatus",hasAddTakeStockStatus);
        info.setOthers(map);
        return info;
    }

    /**
     * 导出盘点时间列表
     */
    @Log(title = "导出盘点时间", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizTakeStockPeriod bizTakeStockPeriod) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizTakeStockPeriod);
        List<BizTakeStockPeriod> list = bizTakeStockPeriodService.getList(bizTakeStockPeriod);
        ExcelUtil<BizTakeStockPeriod> util = new ExcelUtil<BizTakeStockPeriod>(BizTakeStockPeriod.class);
        util.exportExcel(response, list, "盘点时间数据");
    }

    /**
     * 获取盘点时间详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:takeStockPeriod:query')")
    @GetMapping(value = "/{id}")
    @Log(title = "获取盘点时间详细信息", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizTakeStockPeriodService.getById(id));
    }

    /**
     * 新增盘点时间
     */
    @Log(title = "新增盘点时间", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizTakeStockPeriod bizTakeStockPeriod) throws NoSuchFieldException, IllegalAccessException
    {
        bizTakeStockPeriodService.saveOrUpdate(bizTakeStockPeriod);
        return success();
    }
    //判断当前是否在盘点
    @GetMapping("/isTakeStock")
    @Log(title = "判断当前是否在盘点中", businessType = BusinessType.SELECT)
    public AjaxResult isTakeStock()
    {
        BizTakeStockPeriod bizTakeStockPeriod = bizTakeStockPeriodService.query().eq("status",1).one();
        if(bizTakeStockPeriod!=null && bizTakeStockPeriod.getStatus() == 1) {
            return success(true);
        }
        return success(false);
    }
    /**
     * 修改盘点时间
     */
    @Log(title = "修改盘点时间", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody BizTakeStockPeriod bizTakeStockPeriod) throws NoSuchFieldException, IllegalAccessException, SQLException {
        if(bizTakeStockPeriod.getFlag() !=null) {
            bizTakeStockPeriod.setStatus(1);
        }
        //添加盘点时间
        bizTakeStockPeriodService.updateById(bizTakeStockPeriod);
        //新增盘点批次
        if(bizTakeStockPeriod.getStatus() == 1) {
            //扩大连接池
            bizTakeStockPeriodService.updateDruidPoolSize(5000);
            //已生产的批次
            List<BizDaywork> dayworkList = bizDayworkService.selectNeedTakeStock();
            List<BizTaksStockLot> list = new ArrayList<>();
            dayworkList.forEach(item -> {
//                BizDayworkItem conditions = new BizDayworkItem();
//                conditions.setDayworkId(item.getId());
//                BizDayworkItem latestItem = bizDayworkItemService.getLastItem(conditions);
                BizTaksStockLot bizTaksStockLot = new BizTaksStockLot();
                bizTaksStockLot.setStockYear(bizTakeStockPeriod.getStockYear());
                bizTaksStockLot.setStockMonth(bizTakeStockPeriod.getStockMonth());
                bizTaksStockLot.setDrawingNumber(item.getDrawingNumber());
                bizTaksStockLot.setDayworkId(item.getId());
                bizTaksStockLot.setFromLotId(item.getFromId());
                bizTaksStockLot.setIsWaste(item.getIsWaste());
                bizTaksStockLot.setIsSuperaddition(item.getIsSuperaddition());
                bizTaksStockLot.setTenantId(item.getTenantId());
                bizTaksStockLot.setProductionPlanId(item.getProductionPlanId());
                bizTaksStockLot.setProductionPlanDetailId(item.getProductionPlanDetailId());
                bizTaksStockLot.setProductDescription(item.getProductDescription());
                bizTaksStockLot.setTakeStockPeriodId(bizTakeStockPeriod.getId());
                bizTaksStockLot.setLotId(item.getLotId());
                bizTaksStockLot.setLotCode(item.getLotCode());
                bizTaksStockLot.setDeptId(item.getDeptId());
                bizTaksStockLot.setProductId(item.getProductId());
                bizTaksStockLot.setIsTaksStock(0);
                bizTaksStockLot.setTaksStockNum(0);
                bizTaksStockLot.setProcessAlias(item.getProcessAlias());
                bizTaksStockLot.setProcessId(item.getProcessId());
                bizTaksStockLot.setTechnologicalProcessId(item.getTechnologicalProcessId());
                bizTaksStockLot.setProdNum(item.getProdNum());
                bizTaksStockLot.setIsLast(item.getIsLast());
                bizTaksStockLot.setIsWasteRecycling(item.getIsWasteRecycling());
                bizTaksStockLot.setIsAmend(item.getIsAmend());
                bizTaksStockLot.setTemporaryProcessQualifiedNum(item.getTemporaryProcessQualifiedNum());
                bizTaksStockLot.setRemark(item.getRemark());
                bizTaksStockLot.setStatus(item.getStatus());
                bizTaksStockLot.setHasSpecial(item.getHasSpecial());
                bizTaksStockLot.setIsProductStatus(1);
                bizTaksStockLot.setOutsourceFormNo(item.getOutsourceFormNo());
                bizTaksStockLot.setStatusLabel(item.getReportStatus());
//                if (latestItem != null) {
//                    bizTaksStockLot.setOutsourceFormNo(latestItem.getOutsourceFormNo());
//                    bizTaksStockLot.setStatusLabel(latestItem.getStatus());
//                }

                list.add(bizTaksStockLot);
            });
            //未生产的批次
            List<BizLot> bizLots = bizLotService.selectNeedTakeStock();
            bizLots.forEach(item -> {
                BizTaksStockLot bizTaksStockLot = new BizTaksStockLot();
                bizTaksStockLot.setStockYear(bizTakeStockPeriod.getStockYear());
                bizTaksStockLot.setStockMonth(bizTakeStockPeriod.getStockMonth());
                bizTaksStockLot.setDrawingNumber(item.getDrawingNumberName());
                bizTaksStockLot.setTenantId(item.getTenantId());
                bizTaksStockLot.setProductionPlanId(item.getProductionPlanId());
                bizTaksStockLot.setProductionPlanDetailId(item.getProductionPlanDetailId());
                bizTaksStockLot.setProductDescription(item.getDescription());
                bizTaksStockLot.setTakeStockPeriodId(bizTakeStockPeriod.getId());
                bizTaksStockLot.setLotId(item.getId());
                bizTaksStockLot.setFromLotId(item.getFromId());
                bizTaksStockLot.setIsWaste(item.getIsWaste());
                bizTaksStockLot.setLotCode(item.getLotCode());
                bizTaksStockLot.setDeptId(item.getDeptId());
                bizTaksStockLot.setIsSuperaddition(item.getIsSuperaddition());
                bizTaksStockLot.setProductId(item.getProductId());
                bizTaksStockLot.setIsTaksStock(0);
                bizTaksStockLot.setTaksStockNum(0);
                bizTaksStockLot.setTechnologicalProcessId(item.getTechnologicalProcessId());
                bizTaksStockLot.setProdNum(item.getProductionQuantity());
                bizTaksStockLot.setIsLast(item.getIsLast());
                bizTaksStockLot.setIsWasteRecycling(item.getIsWasteRecycling());
                bizTaksStockLot.setIsAmend(item.getIsAmend());
                bizTaksStockLot.setIsProductStatus(0);
                list.add(bizTaksStockLot);
            });
            bizTaksStockLotService.saveBatch(list);
            //保存盘点零存库
            List<BizStorageRetrieval> notRetrievalList = bizStorageRetrievalService.query().eq("status", 0).list();
            if(notRetrievalList.size()>0) {
                List<BizTaksStockStorageRetrieval> needAddList = new ArrayList<>();
                notRetrievalList.forEach(item ->{
                    BizTaksStockStorageRetrieval newItem = new BizTaksStockStorageRetrieval();
                    newItem.setStatus(item.getStatus());
                    newItem.setTakeStockPeriodId(bizTakeStockPeriod.getId());
                    newItem.setProductionPlanDetailId(item.getProductionPlanDetailId());
                    newItem.setProductDescription(item.getProductDescription());
                    newItem.setDrawingNumber(item.getDrawingNumber());
                    newItem.setLotId(item.getLotId());
                    newItem.setLotCode(item.getLotCode());
                    newItem.setProductId(item.getProductId());
                    newItem.setDeptId(item.getDeptId());
                    newItem.setTechnologyVersion(item.getTechnologyVersion());
                    newItem.setStorageNum(item.getStorageNum());
                    newItem.setType(item.getType());
                    newItem.setStoragerId(item.getStoragerId());
                    newItem.setCreateTime(item.getCreateTime());
                    newItem.setRetrievalLotId(item.getRetrievalLotId());
                    newItem.setRetrievalLotCode(item.getRetrievalLotCode());
                    newItem.setRetrievalerId(item.getRetrievalerId());
                    newItem.setRetrievalTime(item.getRetrievalTime());
                    needAddList.add(newItem);
                });
                bizTaksStockStorageRetrievalService.saveBatch(needAddList);
            }
        }else{
            //缩小连接池
            bizTakeStockPeriodService.updateDruidPoolSize(200);
        }
        return success();
    }

    /**
     * 删除盘点时间
     */
    @PreAuthorize("@ss.hasPermi('business:takeStockPeriod:remove')")
    @Log(title = "删除盘点时间", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizTakeStockPeriodService.removeBatchByIds(ids));
    }
}
