package com.yunfeiyun.agmp.fms.service.impl;

import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.enums.*;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.DictUtils;
import com.yunfeiyun.agmp.common.utils.SecurityUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.serialno.NoGenerator;
import com.yunfeiyun.agmp.common.utils.uuid.IdUtils;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.common.web.system.mapper.SysResMapper;
import com.yunfeiyun.agmp.fms.domain.*;
import com.yunfeiyun.agmp.fms.domain.reqvo.*;
import com.yunfeiyun.agmp.fms.domain.resvo.WmsFinishgoodsListResVo;
import com.yunfeiyun.agmp.fms.mapper.*;
import com.yunfeiyun.agmp.fms.domain.dto.FmsTaskrcdListDto;
import com.yunfeiyun.agmp.fms.domain.resvo.AgmTaskPickListResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.FmsTaskResVo;
import com.yunfeiyun.agmp.fms.service.IAgmTaskpickService;
import com.yunfeiyun.agmp.fms.service.IMppProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 农事任务采收Service业务层处理
 * 
 * @author 杨晓辉
 * @date 2023-05-23
 */
@Service
public class AgmTaskpickServiceImpl implements IAgmTaskpickService
{
    @Autowired
    private AgmTaskpickMapper agmTaskpickMapper;
    @Autowired
    private WmsStockMapper wmsStockMapper;
    @Resource
    private WmsGoodsMapper wmsGoodsMapper;
    @Resource
    private WmsChangeMapper wmsChangeMapper;
    @Resource
    private WmsChangeapplyMapper wmsChangeapplyMapper;
    @Resource
    private WmsChangeapplyitemMapper wmsChangeapplyitemMapper;
    @Resource
    private WmsFinishgoodsMapper wmsFinishgoodsMapper;
    @Resource
    private FmsPeriodMapper fmsPeriodMapper;
    @Autowired
    private FmsTaskMapper fmsTaskMapper;
    @Autowired
    private FmsTaskrcdMapper fmsTaskrcdMapper;
    @Autowired
    private SysResMapper sysResMapper;
    @Autowired
    private FmsTaskpickMapper fmsTaskpickMapper;
    @Autowired
    private TssSourceperiodMapper tssSourceperiodMapper;
    @Autowired
    private TssGoodsperiodrcdMapper tssGoodsperiodrcdMapper;
    @Autowired
    private MppQualitycheckMapper mppQualitycheckMapper;
    @Autowired
    private MppTaskMapper mppTaskMapper;
    @Autowired
    private IMppProductService mppProductService;
    @Resource
    NoGenerator noGenerator;


    /**
     * 查询农事任务采收列表
     * 
     * @param reqVo 农事任务采收
     * @return 农事任务采收
     */
    @Override
    public List<AgmTaskPickListResVo> selectFmsTaskpickList(AgmTaskPickListReqVo reqVo)
    {
        return agmTaskpickMapper.selectFmsTaskpickList(reqVo);
    }

    @Override
    public List<WmsFinishgoodsListResVo> selectWmsFinishgoodsList(AgmTaskPickListReqVo reqVo) {
        return agmTaskpickMapper.selectWmsFinishgoodsList(reqVo);
    }

    @Override
    public AgmTaskPickListResVo selectFmsTaskpickByTaskpickId(String taskpickId) {
        return agmTaskpickMapper.selectFmsTaskpickByTaskpickId(taskpickId);
    }

    @Transactional
    @Override
    public AjaxResult add(AddAgmTaskPickReqVo reqVo) {
        //查询详情
        AgmTaskPickListResVo agmTaskPickListResVo = agmTaskpickMapper.selectFmsTaskpickByTaskpickId(reqVo.getTaskpickId());
        String taskpickId = agmTaskPickListResVo.getTaskpickId();
        String dictValue = DictUtils.getDictValue(DictTypeEnums.WMS_GOODS_UNIT.getCode(), CommonEnums.GOOD_UNIT_KG.getCode());
        if (StringUtils.isEmpty(dictValue)) {
            return AjaxResult.error(ErrorCode.GOOD_UNIT_KG_EXIST.getCode(), ErrorCode.GOOD_UNIT_KG_EXIST.getMessage());
        }
        if (CommonEnums.PICK_CHANGE_STATUS_YES.getCode().equals(agmTaskPickListResVo.getPickChangestatus())) {
            return AjaxResult.error(ErrorCode.PICK_CHANGE_STATUS_HAS_IN.getCode(), ErrorCode.PICK_CHANGE_STATUS_HAS_IN.getMessage());
        }


        //需要新增的周期列表
        List<TssGoodsperiodrcd> addList = new ArrayList<>();
        //需要增加的图片信息
        List<SysRes> addResList = new ArrayList<>();

        //查询作物周期，农事任务记录信息
        generateSourceperiod(addList, addResList, agmTaskPickListResVo, reqVo);

        // 生成货物
        WmsGoods wmsGoods = new WmsGoods();
        BeanUtils.copyProperties(reqVo, wmsGoods);
        MppProduct product = new MppProduct();
        product.setProductCode(reqVo.getProductValue());
        List<MppProduct> mppProducts = mppProductService.selectMppProductList(product);
        wmsGoods.setGoodsName(mppProducts.size() == 0 ? "" : mppProducts.get(0).getProductName());
        wmsGoods.setGoodsUnit(dictValue);
        wmsGoods.setGoodsId(wmsGoods.getId());
        wmsGoods.setGoodsSpec("1");
        // 保存
        wmsGoodsMapper.insertWmsGoods(wmsGoods);

        //生成农产品货物
        WmsFinishgoods wmsFinishgoods = new WmsFinishgoods();
        wmsFinishgoods.setFinishgoodsId(wmsFinishgoods.getId());
        wmsFinishgoods.setGoodsId(wmsGoods.getGoodsId());
        wmsFinishgoods.setFinishgoodPickno(agmTaskPickListResVo.getPickNo());
        wmsFinishgoods.setFinishgoodNo(agmTaskPickListResVo.getPickNo());
        wmsFinishgoods.setFinishgoodCreateddate(DateUtils.dateTimeNow());
        wmsFinishgoods.setFinishgoodsType(CommonEnums.FINISH_GOODS_TYPE_PICK.getCode());
        wmsFinishgoods.setFinishgoodscode(reqVo.getProductValue());
        wmsFinishgoods.setSourceinfoId(reqVo.getSourceinfoId());
        wmsFinishgoodsMapper.insertWmsFinishgoods(wmsFinishgoods);

        // 生成库存
        WmsStock wmsStock = new WmsStock();
        wmsStock.setStockAmount(reqVo.getStockAmount());
        wmsStock.setWarehouseId(reqVo.getWarehouseId());
        wmsStock.setStockId(wmsStock.getId());
        wmsStock.setGoodsId(wmsGoods.getGoodsId());
        // 保存
        wmsStockMapper.insertWmsStock(wmsStock);
        // 保存变动申请
        WmsChangeapply wmsChangeapply = generateWmsChangeApply(ChangeBizType.PICK.getCode());
        wmsChangeapplyMapper.insertWmsChangeapply(wmsChangeapply);
        // 保存变动申请物件
        WmsChangeapplyitem wmsChangeapplyitem = generateWmsChangeApplyItem(wmsGoods, wmsFinishgoods, wmsChangeapply, reqVo);
        wmsChangeapplyitemMapper.insertWmsChangeapplyitem(wmsChangeapplyitem);
        // 保存变动记录
        WmsChange wmsChange = generateWmsChange(wmsStock, wmsChangeapply);
        wmsChangeMapper.insertWmsChange(wmsChange);

        //改变采收表是否入库状态
        FmsTaskpick fmsTaskpick = new FmsTaskpick();
        fmsTaskpick.setTaskpickId(agmTaskPickListResVo.getTaskpickId());
        fmsTaskpick.setPickChangestatus(CommonEnums.PICK_CHANGE_STATUS_YES.getCode());
        fmsTaskpickMapper.updateFmsTaskpick(fmsTaskpick);

        if (addList.size() > 0) {
            tssGoodsperiodrcdMapper.insertTssGoodsperiodrcdBatch(addList);
        }
//        sysResMapper.insertSysReses(addResList);
        for (SysRes sysRes : addResList) {
            sysResMapper.insertSysRes(sysRes);
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult add(AddAgmTaskPickOutReqVo reqVo) {
        String dictValue = DictUtils.getDictValue(DictTypeEnums.WMS_GOODS_UNIT.getCode(), CommonEnums.GOOD_UNIT_KG.getCode());
        if (StringUtils.isEmpty(dictValue)) {
            return AjaxResult.error(ErrorCode.GOOD_UNIT_KG_EXIST.getCode(), ErrorCode.GOOD_UNIT_KG_EXIST.getMessage());
        }

        // 生成货物
        WmsGoods wmsGoods = new WmsGoods();
        MppProduct product = new MppProduct();
        product.setProductCode(reqVo.getProductValue());
        List<MppProduct> mppProducts = mppProductService.selectMppProductList(product);
        wmsGoods.setGoodsName(mppProducts.size() == 0 ? "" : mppProducts.get(0).getProductName());
        wmsGoods.setGoodsUnit(dictValue);
        wmsGoods.setGoodsId(wmsGoods.getId());
        wmsGoods.setGoodsSpec(reqVo.getGoodsSpec());
        // 保存
        wmsGoodsMapper.insertWmsGoods(wmsGoods);

        //生成农产品货物
        WmsFinishgoods wmsFinishgoods = new WmsFinishgoods();
        wmsFinishgoods.setFinishgoodsId(wmsFinishgoods.getId());
        wmsFinishgoods.setGoodsId(wmsGoods.getGoodsId());
        wmsFinishgoods.setFinishgoodNo(noGenerator.getBuyNo());
        wmsFinishgoods.setFinishgoodCreateddate(DateUtils.dateTimeNow());
        wmsFinishgoods.setFinishgoodsType(CommonEnums.FINISH_GOODS_TYPE_PICK.getCode());
        wmsFinishgoods.setFinishgoodscode(reqVo.getProductValue());
        wmsFinishgoods.setSourceinfoId(reqVo.getSourceinfoId());
        wmsFinishgoods.setLandId(reqVo.getLandId());
        wmsFinishgoods.setLandName(reqVo.getLandName());
        wmsFinishgoods.setFinishgoodsExpense(reqVo.getFinishgoodsExpense());
        wmsFinishgoodsMapper.insertWmsFinishgoods(wmsFinishgoods);

        // 生成库存
        WmsStock wmsStock = new WmsStock();
        wmsStock.setStockAmount(reqVo.getStockAmount());
        wmsStock.setWarehouseId(reqVo.getWarehouseId());
        wmsStock.setStockId(wmsStock.getId());
        wmsStock.setGoodsId(wmsGoods.getGoodsId());
        // 保存
        wmsStockMapper.insertWmsStock(wmsStock);
        // 保存变动申请
        WmsChangeapply wmsChangeapply = generateWmsChangeApply(ChangeBizType.PICK.getCode());
        wmsChangeapplyMapper.insertWmsChangeapply(wmsChangeapply);
        // 保存变动申请物件
        WmsChangeapplyitem wmsChangeapplyitem = generateWmsChangeApplyItem(wmsGoods, wmsFinishgoods, wmsChangeapply, reqVo);
        wmsChangeapplyitemMapper.insertWmsChangeapplyitem(wmsChangeapplyitem);
        // 保存变动记录
        WmsChange wmsChange = generateWmsChange(wmsStock, wmsChangeapply);
        wmsChangeMapper.insertWmsChange(wmsChange);

//        //质检报告处理
//        MppQualitycheck mppQualitycheck = new MppQualitycheck();
//        mppQualitycheck.setQualitycheckId(mppQualitycheck.getId());
//        mppQualitycheck.setFinishgoodsId(wmsFinishgoods.getFinishgoodsId());
//        mppQualitycheckMapper.insertMppQualitycheck(mppQualitycheck);

        //生成任务
        MppTask mppTask = new MppTask();
        BeanUtils.copyProperties(reqVo, mppTask);
        mppTask.setTaskId(mppTask.getId());
        mppTask.setTaskNo(IdUtils.fastSimpleUUID());
        mppTask.setStockId(wmsStock.getStockId());
        mppTask.setTaskdetailOrg(reqVo.getSupplierId());
        mppTask.setTaskdetailNum(reqVo.getStockAmount());
        mppTask.setTaskCreator(SecurityUtils.getUserId());
        mppTask.setTaskCreateddate(DateUtils.dateTimeNow());
        mppTask.setTaskdetailCreateddate(DateUtils.dateTimeNow());
        mppTask.setTaskType("0");
        mppTaskMapper.insertMppTask(mppTask);

//        //保存图片
//        if (!StringUtils.isEmpty(reqVo.getQualityResIds())) {
//            String[] quaResIds = reqVo.getQualityResIds().split(",");
//            if (quaResIds.length > 0) {
//                sysResMapper.updateSysResByResIdes(quaResIds, mppQualitycheck.getQualitycheckId());
//            }
//        }


        //生长周期处理
//        TssSourceperiod tssSourceperiod = new TssSourceperiod();
//        tssSourceperiod.setSourceperiodId(tssSourceperiod.getId());
//        tssSourceperiod.setSourceperiodType(CommonEnums.SOURCE_PERIOD_TYPE_PERIOD.getCode());
//        tssSourceperiod.setSourceinfoId(reqVo.getSourceinfoId());
//        tssSourceperiod.setSourceperiodParentid("0");

        //保存图片
        if (!StringUtils.isEmpty(reqVo.getPeriodResIds())) {
            String[] resIds = reqVo.getPeriodResIds().split(",");
            if (resIds.length > 0) {
                sysResMapper.updateSysResByResIdes(resIds, wmsFinishgoods.getFinishgoodsId());
            }
        }

        return AjaxResult.success();
    }

    /**
     * 生成变动申请
     *
//     * @param  库存新增Vo
     * @return 变动申请
     */
    public WmsChangeapply generateWmsChangeApply(String changeBizType) {
        WmsChangeapply wmsChangeapply = new WmsChangeapply();
        wmsChangeapply.setChangeapplyId(wmsChangeapply.getId());
        wmsChangeapply.setChangeapplyWay(ChangeApplyWay.SINGLE.getCode());
        wmsChangeapply.setChangeapplyBiztype(changeBizType);
//        wmsChangeapply.setChangeapplyPricetotal();
        wmsChangeapply.setChangeapplyApplyer(SecurityUtils.getUserId());
        wmsChangeapply.setChangeapplyApplydate(DateUtils.dateTimeNow());
        wmsChangeapply.setChangeapplyAuditstatus(ChangeApplyAuditStatus.PASS.getCode());
        wmsChangeapply.setChangeapplyAuditdate(wmsChangeapply.getChangeapplyApplydate());
        wmsChangeapply.setChangeapplyAuditor(wmsChangeapply.getChangeapplyApplyer());
        wmsChangeapply.setChangeapplyRemark("采收入库");
        wmsChangeapply.setChangeapplyInoutdate(DateUtils.dateTimeNow());
        return wmsChangeapply;

    }

    /**
     * 生成变动申请物件
     *
     * @param wmsGoods         农资
     * @param wmsChangeapply   变动申请
     * @param reqVo 库存新增Vo
     * @return 变动申请物件
     */
    public WmsChangeapplyitem generateWmsChangeApplyItem(WmsGoods wmsGoods, WmsFinishgoods wmsFinishgoods, WmsChangeapply wmsChangeapply, AddAgmTaskPickReqVo reqVo) {
        WmsChangeapplyitem wmsChangeapplyitem = new WmsChangeapplyitem();
        wmsChangeapplyitem.setChangeapplyitemId(wmsChangeapplyitem.getId());
        wmsChangeapplyitem.setChangeapplyId(wmsChangeapply.getChangeapplyId());
        wmsChangeapplyitem.setGoodsId(wmsGoods.getGoodsId());
        wmsChangeapplyitem.setWarehouseId(reqVo.getWarehouseId());
        wmsChangeapplyitem.setChangeapplyitemUnit(wmsGoods.getGoodsUnit());
        wmsChangeapplyitem.setChangeapplyitemSpec(wmsGoods.getGoodsSpec());
        wmsChangeapplyitem.setChangeapplyitemType(wmsFinishgoods.getFinishgoodsType());
        if (reqVo.getStockAmount().compareTo(new BigDecimal("0")) == 0) {
            throw new BizException(ErrorCode.WMS_STOCK_CANNOT_CHANGE_ZERO);
        }
        wmsChangeapplyitem.setChangeapplyitemNum(reqVo.getStockAmount());
        wmsChangeapplyitem.setChangeapplyitemPricetotal(wmsChangeapply.getChangeapplyPricetotal());
        return wmsChangeapplyitem;
    }

    public WmsChangeapplyitem generateWmsChangeApplyItem(WmsGoods wmsGoods, WmsFinishgoods wmsFinishgoods, WmsChangeapply wmsChangeapply, AddAgmTaskPickOutReqVo reqVo) {
        WmsChangeapplyitem wmsChangeapplyitem = new WmsChangeapplyitem();
        wmsChangeapplyitem.setChangeapplyitemId(wmsChangeapplyitem.getId());
        wmsChangeapplyitem.setChangeapplyId(wmsChangeapply.getChangeapplyId());
        wmsChangeapplyitem.setGoodsId(wmsGoods.getGoodsId());
        wmsChangeapplyitem.setWarehouseId(reqVo.getWarehouseId());
        wmsChangeapplyitem.setChangeapplyitemUnit(wmsGoods.getGoodsUnit());
        wmsChangeapplyitem.setChangeapplyitemSpec(wmsGoods.getGoodsSpec());
        wmsChangeapplyitem.setChangeapplyitemType(wmsFinishgoods.getFinishgoodsType());
        if (reqVo.getStockAmount().compareTo(new BigDecimal("0")) == 0) {
            throw new BizException(ErrorCode.WMS_STOCK_CANNOT_CHANGE_ZERO);
        }
        wmsChangeapplyitem.setChangeapplyitemNum(reqVo.getStockAmount());
        wmsChangeapplyitem.setChangeapplyitemPricetotal(wmsChangeapply.getChangeapplyPricetotal());
        return wmsChangeapplyitem;
    }

    /**
     * 生产变动记录
     *
     * @param wmsStock         库存
     * @param wmsChangeapply   变动申请

     */
    public WmsChange generateWmsChange(WmsStock wmsStock, WmsChangeapply wmsChangeapply) {
        WmsChange wmsChange = new WmsChange();
        wmsChange.setChangeapplyId(wmsChangeapply.getChangeapplyId());
        wmsChange.setChangeId(wmsChange.getId());
        wmsChange.setStockId(wmsStock.getStockId());
        wmsChange.setChangeId(wmsChange.getId());
        wmsChange.setChangeBiztype(wmsChangeapply.getChangeapplyBiztype());
        wmsChange.setChangeWay(ChangeWay.IN.getCode());
        wmsChange.setChangeNum(wmsStock.getStockAmount());
        wmsChange.setChangeOldnum(new BigDecimal("0"));
        if (wmsStock.getStockAmount().compareTo(new BigDecimal("0")) == 0) {
            throw new BizException(ErrorCode.WMS_STOCK_CANNOT_CHANGE_ZERO);
        }
        wmsChange.setChangeNewnum(wmsStock.getStockAmount());
        wmsChange.setChangeAuditor(SecurityUtils.getUserId());
        wmsChange.setChangeAuditeddate(DateUtils.dateTimeNow());
//        wmsChange.setChangeRemark(reqVo.getChangeapplyRemark());
        return wmsChange;
    }

    /**
     * 查询过去的作物周期，农事任务，增加溯源信息的周期表
     * @param addList
     * @param addResList
     * @param agmTaskPickListResVo
     * @param reqVo
     */
    public void generateSourceperiod(List<TssGoodsperiodrcd> addList, List<SysRes> addResList, AgmTaskPickListResVo agmTaskPickListResVo, AddAgmTaskPickReqVo reqVo){

        //查询作物周期，农事任务记录信息
        List<FmsPeriod> fmsPeriods = fmsPeriodMapper.selectFmsPeriodByCropId(agmTaskPickListResVo.getCropId());
        if (fmsPeriods.size() == 0) {
            //如果没有生长周期，创建默认周期，查询
            TssGoodsperiodrcd tssGoodsperiodrcd = new TssGoodsperiodrcd();
            tssGoodsperiodrcd.setGoodsperiodrcdId(tssGoodsperiodrcd.getId());
            tssGoodsperiodrcd.setGoodsperiodrcdName("生长周期");
            tssGoodsperiodrcd.setGoodsperiodrcdType(CommonEnums.SOURCE_PERIOD_TYPE_PERIOD.getCode());
            tssGoodsperiodrcd.setFinishgoodPickno(agmTaskPickListResVo.getPickNo());
            tssGoodsperiodrcd.setGoodsperiodrcdParentid("0");
            String startTime = StringUtils.isEmpty(agmTaskPickListResVo.getPlanStartdate())
                    ? agmTaskPickListResVo.getPlanPlanstartdate() : agmTaskPickListResVo.getPlanStartdate();
            String endTime = StringUtils.isEmpty(agmTaskPickListResVo.getPlanEnddate())
                    ? agmTaskPickListResVo.getPlanPlanenddate() : agmTaskPickListResVo.getPlanEnddate();
            tssGoodsperiodrcd.setGoodsperiodrcdStartdate(startTime);
            tssGoodsperiodrcd.setGoodsperiodrcdEnddate(endTime);
            addList.add(tssGoodsperiodrcd);

            //查询所有的农事记录
            FmsTaskListReqVo fmsTaskListReqVo = new FmsTaskListReqVo();
            fmsTaskListReqVo.setPlanId(agmTaskPickListResVo.getPlanId());
            fmsTaskListReqVo.setTaskAuditstatus(TaskStatus.COMPLETED.getCode());
            List<FmsTaskResVo> fmsTaskResVos = fmsTaskMapper.selectTaskListAll(fmsTaskListReqVo);
            for (FmsTaskResVo fmsTaskResVo : fmsTaskResVos) {
                TssGoodsperiodrcd goodsperiodrcd = new TssGoodsperiodrcd();
                goodsperiodrcd.setGoodsperiodrcdId(goodsperiodrcd.getId());
                goodsperiodrcd.setGoodsperiodrcdType(CommonEnums.SOURCE_PERIOD_TYPE_RECORD.getCode());
                goodsperiodrcd.setFinishgoodPickno(agmTaskPickListResVo.getPickNo());
                goodsperiodrcd.setGoodsperiodrcdParentid(tssGoodsperiodrcd.getGoodsperiodrcdId());
                String startTime1 =  fmsTaskResVo.getTaskPlanstartdate();
                String endTime1 = StringUtils.isEmpty(fmsTaskResVo.getTaskCompletedate())
                        ? fmsTaskResVo.getTaskPlanenddate() : fmsTaskResVo.getTaskCompletedate();
                goodsperiodrcd.setGoodsperiodrcdStartdate(startTime1);
                goodsperiodrcd.setGoodsperiodrcdEnddate(endTime1);
                goodsperiodrcd.setGoodsperiodrcdFmstaskcreateddate(fmsTaskResVo.getTaskCreateddate());
                goodsperiodrcd.setGoodsperiodrcdFmstaskmanagername(fmsTaskResVo.getTaskManagername());
                goodsperiodrcd.setGoodsperiodrcdFmstaskremark(fmsTaskResVo.getTaskContent());
                addList.add(goodsperiodrcd);

                //图片资源处理
                buildRcdSysResList(fmsTaskResVo.getTaskId(), goodsperiodrcd.getGoodsperiodrcdId(), addResList);

            }
        } else {
            //如果存在周期，根据周期查询农事任务，进行入库
            String planPlanstartdate = StringUtils.isEmpty(agmTaskPickListResVo.getPlanStartdate())
                    ? agmTaskPickListResVo.getPlanPlanstartdate() : agmTaskPickListResVo.getPlanStartdate();
            LocalDateTime startTime = LocalDateTime.parse(planPlanstartdate, DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode()));
            for (FmsPeriod fmsPeriod : fmsPeriods) {
                String endTime = getEndTime(startTime, fmsPeriod.getPeriodDays());

                //周期数据入库
                TssGoodsperiodrcd tssGoodsperiodrcd = new TssGoodsperiodrcd();
                tssGoodsperiodrcd.setGoodsperiodrcdId(tssGoodsperiodrcd.getId());
                tssGoodsperiodrcd.setGoodsperiodrcdName(fmsPeriod.getPeriodName());
                tssGoodsperiodrcd.setGoodsperiodrcdType(CommonEnums.SOURCE_PERIOD_TYPE_PERIOD.getCode());
                tssGoodsperiodrcd.setFinishgoodPickno(agmTaskPickListResVo.getPickNo());
                tssGoodsperiodrcd.setGoodsperiodrcdParentid("0");
                tssGoodsperiodrcd.setGoodsperiodrcdStartdate(startTime.format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())));
                tssGoodsperiodrcd.setGoodsperiodrcdEnddate(endTime);
                addList.add(tssGoodsperiodrcd);

                //图片资源处理
                buildSysResList(fmsPeriod.getPeriodId(), tssGoodsperiodrcd.getGoodsperiodrcdId(), addResList);

                FmsTaskListReqVo fmsTaskListReqVo = new FmsTaskListReqVo();
                fmsTaskListReqVo.setPlanId(agmTaskPickListResVo.getPlanId());
                fmsTaskListReqVo.setTaskAuditstatus(TaskStatus.COMPLETED.getCode());
                fmsTaskListReqVo.setStartDate(startTime.format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())));
                fmsTaskListReqVo.setEndDate(endTime);
                List<FmsTaskResVo> fmsTaskResVos = fmsTaskMapper.selectTaskList(fmsTaskListReqVo);
                for (FmsTaskResVo fmsTaskResVo : fmsTaskResVos) {
                    TssGoodsperiodrcd goodsperiodrcd = new TssGoodsperiodrcd();
                    goodsperiodrcd.setGoodsperiodrcdId(goodsperiodrcd.getId());
                    goodsperiodrcd.setGoodsperiodrcdType(CommonEnums.SOURCE_PERIOD_TYPE_RECORD.getCode());
                    goodsperiodrcd.setFinishgoodPickno(agmTaskPickListResVo.getPickNo());
                    goodsperiodrcd.setGoodsperiodrcdParentid(tssGoodsperiodrcd.getGoodsperiodrcdId());
                    String startTime1 =  fmsTaskResVo.getTaskPlanstartdate();
                    String endTime1 = StringUtils.isEmpty(fmsTaskResVo.getTaskCompletedate())
                            ? fmsTaskResVo.getTaskPlanenddate() : fmsTaskResVo.getTaskCompletedate();
                    goodsperiodrcd.setGoodsperiodrcdStartdate(startTime1);
                    goodsperiodrcd.setGoodsperiodrcdEnddate(endTime1);
                    goodsperiodrcd.setGoodsperiodrcdFmstaskcreateddate(fmsTaskResVo.getTaskCreateddate());
                    goodsperiodrcd.setGoodsperiodrcdFmstaskmanagername(fmsTaskResVo.getTaskManagername());
                    goodsperiodrcd.setGoodsperiodrcdFmstaskremark(fmsTaskResVo.getTaskContent());
                    addList.add(goodsperiodrcd);

                    //图片资源处理
                    buildRcdSysResList(fmsTaskResVo.getTaskId(), goodsperiodrcd.getGoodsperiodrcdId(), addResList);
                }
                //下一周期的开始时间
                startTime = startTime.plusDays(fmsPeriod.getPeriodDays());
            }
        }


    }

    /**
     * 计算结束时间
     * @param startTime
     * @param days
     * @return
     */
    private String getEndTime(LocalDateTime startTime, int days) {
        if (startTime == null) {
            return "";
        }
        if (days == 0) {
            return startTime.format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())).substring(0, 10) + " 23:59:59";
        } else {
            LocalDateTime localDateTime = startTime.plusDays(days - 1);
            return localDateTime.format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())).substring(0, 10) + " 23:59:59";
        }
    }

    /**
     * 组装图片信息
     * @param taskId
     * @param resBusId
     * @param addResList
     */
    private void buildRcdSysResList(String taskId, String resBusId, List<SysRes> addResList){
        //图片资源处理
        FmsTaskrcdListReqVo fmsTaskrcdListReqVo = new FmsTaskrcdListReqVo();
        fmsTaskrcdListReqVo.setTaskId(taskId);
        fmsTaskrcdListReqVo.setTaskrcdAuditstatus(TaskrcdAuditStatus.PASS.getCode());
        List<FmsTaskrcdListDto> taskrcdListDtos = fmsTaskrcdMapper.selectTaskrcdList(fmsTaskrcdListReqVo);
        if (taskrcdListDtos.size() > 0) {
            FmsTaskrcdListDto rcd = taskrcdListDtos.get(0);
            List<SysRes> res = sysResMapper.selectResByBusId(rcd.getTaskrcdId(), ResConstants.BizType.TASKRCD.getKey(), ResConstants.mediaType.IMG.getValue());
            for (SysRes re : res) {
                SysRes sysRes = new SysRes();
                BeanUtils.copyProperties(re, sysRes);
                sysRes.setResId(re.getId());
                sysRes.setResBusId(resBusId);
                sysRes.setResBiztype(ResConstants.BizType.SOURCE_INFO_PERIOD.getKey());
                sysRes.setResCreateddate(DateUtils.dateTimeNow());
                addResList.add(sysRes);
            }
        }
    }

    private void buildSysResList(String oldResBusId, String resBusId, List<SysRes> addResList) {
        List<SysRes> res = sysResMapper.selectResByBusId(oldResBusId, ResConstants.BizType.PERIOD.getKey(), ResConstants.mediaType.IMG.getKey());
        for (SysRes re : res) {
            SysRes sysRes = new SysRes();
            BeanUtils.copyProperties(re, sysRes);
            sysRes.setResId(re.getId());
            sysRes.setResBusId(resBusId);
            sysRes.setResBiztype(ResConstants.BizType.SOURCE_INFO_PERIOD.getKey());
            sysRes.setResCreateddate(DateUtils.dateTimeNow());
            addResList.add(sysRes);
        }
    }
}
