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

import com.alibaba.fastjson2.JSONObject;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.framework.manager.ResManager;
import com.yunfeiyun.agmp.common.framework.web.service.PolicyService;
import com.yunfeiyun.agmp.common.utils.img.enums.BusType;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.fms.domain.*;
import com.yunfeiyun.agmp.fms.mapper.*;
import com.yunfeiyun.agmp.fms.domain.reqvo.SelectCountOfScreenReqVo;
import com.yunfeiyun.agmp.fms.domain.reqvo.TssTracecodeapplyReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.TssTraceCodeApplyResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.TssTracecodeapplyManagerListResVo;
import com.yunfeiyun.agmp.fms.service.ITssTracecodeapplyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 溯源码生成单Service业务层处理
 * 
 * @author 杨晓辉
 * @date 2023-07-04
 */
@Service
public class TssTracecodeapplyServiceImpl implements ITssTracecodeapplyService
{
    @Autowired
    private TssTracecodeapplyMapper tssTracecodeapplyMapper;

    @Resource
    private TssSourceinfoMapper tssSourceinfoMapper;

    @Resource
    private ResManager resManager;

    @Resource
    private WmsFinishgoodsMapper wmsFinishgoodsMapper;

    @Resource
    private MppQualitycheckMapper mppQualitycheckMapper;

    @Resource
    private FmsLandMapper fmsLandMapper;

    @Resource
    private TssSourceperiodMapper tssSourceperiodMapper;

    @Resource
    private TssGoodsperiodrcdMapper tssGoodsperiodrcdMapper;

    @Resource
    private TssTracecodetplparamMapper tssTracecodetplparamMapper;

    @Resource
    private MppTaskMapper mppTaskMapper;

    @Resource
    private TssSourceEnvironmentMapper tssSourceEnvironmentMapper;

    /**
     * 查询溯源码生成单
     * 
     * @param tarcecodeapplyId 溯源码生成单主键
     * @return 溯源码生成单
     */
    @Override
    public TssTracecodeapply selectTssTracecodeapplyByTarcecodeapplyId(String tarcecodeapplyId)
    {
        return tssTracecodeapplyMapper.selectTssTracecodeapplyByTarcecodeapplyId(tarcecodeapplyId);
    }

    /**
     * 查询溯源码生成单列表
     * 
     * @param tssTracecodeapply 溯源码生成单
     * @return 溯源码生成单
     */
    @Override
    public List<TssTracecodeapply> selectTssTracecodeapplyList(TssTracecodeapply tssTracecodeapply)
    {
        return tssTracecodeapplyMapper.selectTssTracecodeapplyList(tssTracecodeapply);
    }

    @Override
    public Integer selectCountOfTssTracecodeapply(SelectCountOfScreenReqVo reqVo) {
        return tssTracecodeapplyMapper.selectCountOfTssTracecodeapply(reqVo);
    }

    /**
     * 新增溯源码生成单
     * 
     * @param tssTracecodeapply 溯源码生成单
     * @return 结果
     */
    @Override
    public int insertTssTracecodeapply(TssTracecodeapply tssTracecodeapply)
    {
        return tssTracecodeapplyMapper.insertTssTracecodeapply(tssTracecodeapply);
    }

    /**
     * 修改溯源码生成单
     * 
     * @param tssTracecodeapply 溯源码生成单
     * @return 结果
     */
    @Override
    public int updateTssTracecodeapply(TssTracecodeapply tssTracecodeapply)
    {
        return tssTracecodeapplyMapper.updateTssTracecodeapply(tssTracecodeapply);
    }

    /**
     * 批量删除溯源码生成单
     * 
     * @param tarcecodeapplyIds 需要删除的溯源码生成单主键
     * @return 结果
     */
    @Override
    public int deleteTssTracecodeapplyByTarcecodeapplyIds(String[] tarcecodeapplyIds)
    {
        return tssTracecodeapplyMapper.deleteTssTracecodeapplyByTarcecodeapplyIds(tarcecodeapplyIds);
    }

    /**
     * 删除溯源码生成单信息
     * 
     * @param tarcecodeapplyId 溯源码生成单主键
     * @return 结果
     */
    @Override
    public int deleteTssTracecodeapplyByTarcecodeapplyId(String tarcecodeapplyId)
    {
        return tssTracecodeapplyMapper.deleteTssTracecodeapplyByTarcecodeapplyId(tarcecodeapplyId);
    }

    @Override
    public List<TssTracecodeapplyManagerListResVo> selectTssTracecodeapplyManagerListResVoList(TssTracecodeapplyReqVo tssTracecodeapply) {
        return tssTracecodeapplyMapper.selectTssTracecodeapplyManagerListResVoList(tssTracecodeapply);
    }

    @Override
    public List<TssTraceCodeApplyResVo> selectTssTraceCodeApplyResVoList(TssTracecodeapply tssTracecodeapply) {
        List<TssTraceCodeApplyResVo> resVoList = tssTracecodeapplyMapper.selectTssTraceCodeApplyResVoList(tssTracecodeapply);
        if(resVoList.isEmpty()){
            return new ArrayList<>();
        }
        TssTracecodetplparam tssTracecodetplparam = new TssTracecodetplparam();
        tssTracecodetplparam.setTracecodetplId(resVoList.get(0).getTracecodetplId());
        List<TssTracecodetplparam> tssTracecodetplparams = tssTracecodetplparamMapper.selectTssTracecodetplparamList(tssTracecodetplparam);
        Map<String,TssTracecodetplparam> paramMap = tssTracecodetplparams.stream().collect(Collectors.toMap(TssTracecodetplparam::getTplparamBustype,item->item));
        for(TssTraceCodeApplyResVo tssTraceCodeApplyResVo : resVoList){
//            tssTraceCodeApplyResVo.setQRCodeUrl(paramMap.get(BusType.TRACING_QR_CODE.name()).getTplparamData() + "?tarcecodeapplyno="+paramMap.get(BusType.TRACING_NO.name()).getTplparamData() );
            tssTraceCodeApplyResVo.setQRCodeUrl(paramMap.get(BusType.TRACING_QR_CODE.name()).getTplparamData() + "?tarcecodeapplyno=" + tssTraceCodeApplyResVo.getTarcecodeapplyno());
        }
        return resVoList;
    }

    @Override
    public JSONObject appQuerySource(String tarcecodeapplyno) {
        JSONObject result = new JSONObject();
        result.put("tarcecodeapplyno",tarcecodeapplyno);
        // 查询溯源码生成单
        List<TssTracecodeapply> tssTracecodeapply = tssTracecodeapplyMapper.selectTssTracecodeapplyListByTarcecodeapplynos(new String[]{tarcecodeapplyno});
        if(tssTracecodeapply.isEmpty()){
            throw new BizException(ErrorCode.TSS_TRACE_APPLY_NOT_EXIST);
        }
        // 查询农产品信息
        WmsFinishgoods wmsFinishgoods = wmsFinishgoodsMapper.selectWmsFinishgoodsStockResVoByStockId(tssTracecodeapply.get(0).getStockId());

        // 写入入库时间
        result.put("finishgoodCreateddate",wmsFinishgoods.getFinishgoodCreateddate());
        // 查询溯源信息
        TssSourceinfo tssSourceinfo = tssSourceinfoMapper.selectTssSourceinfoByTarcecodeapplyno(tarcecodeapplyno);
        result.put("sourceInfoName",tssSourceinfo.getSourceinfoName());
        // 查询农产品头像
        List<SysRes> goodsImg = resManager.queryRes(tssSourceinfo.getSourceinfoId(),ResConstants.BizType.SOURCE_INFO_AVATAR.getKey());
        if(!goodsImg.isEmpty()){
            // 写入农产品头像
            result.put("goodsImg",goodsImg.get(0).getResUrl());
        }

        if(tssSourceinfo.getSourceinfoFiguretatus().equals("1")){
            List<SysRes> figureRes = resManager.queryRes(tssSourceinfo.getSourceinfoId(),ResConstants.BizType.SOURCE_INFO_FIGURE.getKey());
            packageFigureObject(result,figureRes);
        }else {
            MppTask mppTaskQuery = new MppTask();
            mppTaskQuery.setStockId(tssTracecodeapply.get(0).getStockId());
            List<MppTask> mppTaskList = mppTaskMapper.selectMppTaskList(mppTaskQuery);
            if(!mppTaskList.isEmpty()){
                List<SysRes> figureRes = resManager.queryRes(mppTaskList.get(0).getTaskId(),ResConstants.BizType.FINISH_GOODS_PERIOD.getKey());
                packageFigureObject(result,figureRes);
            }
        }
        String qualityBizId ;
        List<SysRes>  sysRes;
        // 查询质检记录
        if(tssSourceinfo.getSourceinfoQualitystatus().equals("1")){
            qualityBizId = tssSourceinfo.getSourceinfoId();
            sysRes = resManager.queryRes(qualityBizId,ResConstants.BizType.SOURCE_INFO_QUALITY.getKey());
        }else {
            MppQualitycheck mppQualitycheckQuery = new MppQualitycheck();
            mppQualitycheckQuery.setFinishgoodsId(wmsFinishgoods.getFinishgoodsId());
            List<MppQualitycheck> mppQualitycheckList = mppQualitycheckMapper.selectMppQualitycheckList(mppQualitycheckQuery);
            if (mppQualitycheckList.isEmpty()){
                throw new BizException(ErrorCode.MPP_QUALITY_CHECK_NOT_EXIST);
            }
            qualityBizId = mppQualitycheckList.get(0).getQualitycheckId();
            sysRes = resManager.queryRes(qualityBizId,ResConstants.BizType.MPPQUALITYCHECK.getKey());
        }
        List<String> qualityCheckUrls = sysRes.stream().map(SysRes::getResUrl).collect(Collectors.toList());
        JSONObject qualityCheckInfo = new JSONObject();
        qualityCheckInfo.put("qualityCheckUrls",qualityCheckUrls);
        qualityCheckInfo.put("qualityCheckName",tssSourceinfo.getSourceinfoName() + "质检报告");
        qualityCheckInfo.put("qualityCheckRemark",tssSourceinfo.getSourceinfoQualityremark());
        // 写入质检记录
        result.put("qualityCheckInfo",qualityCheckInfo);
        FmsLand fmsLand;
        if(StringUtils.isNotBlank(wmsFinishgoods.getFinishgoodPickno())){
            fmsLand= fmsLandMapper.selectFmsLandByTarcecodeapplyno(wmsFinishgoods.getFinishgoodPickno());
        }else {
            fmsLand = fmsLandMapper.selectFmsLandList(null).get(0);
        }
        // 写入基地信息
        result.put("landInfo",fmsLand);
        if(tssSourceinfo.getSourceinfoGrowstatus().equals("1")){
            // 查询
            TssSourceperiod tssSourceperiodQuery = new TssSourceperiod();
            tssSourceperiodQuery.setSourceinfoId(tssSourceinfo.getSourceinfoId());
            tssSourceperiodQuery.setSourceperiodParentid("0");
            List<TssSourceperiod> tssSourceperiodList = tssSourceperiodMapper.selectTssSourceperiodWithResList(tssSourceperiodQuery, PolicyService.enabledOssCloudPolicy());
            packageSourcePeriod(result,tssSourceperiodList);

        }else {
            TssGoodsperiodrcd tssGoodsperiodrcd = new TssGoodsperiodrcd();
            tssGoodsperiodrcd.setFinishgoodPickno(wmsFinishgoods.getFinishgoodPickno());
            tssGoodsperiodrcd.setGoodsperiodrcdType("0");
            List<TssGoodsperiodrcd> tssGoodsperiodrcds = tssGoodsperiodrcdMapper.selectTssGoodsperiodrcdWithResList(tssGoodsperiodrcd,PolicyService.enabledOssCloudPolicy());
            packageGoodsPeriod(result,tssGoodsperiodrcds);
        }

        //溯源页面返回生长环境
        TssSourceEnvironment tssSourceEnvironment = new TssSourceEnvironment();
        tssSourceEnvironment.setSourceinfoId(tssSourceinfo.getSourceinfoId());
        List<TssSourceEnvironment> tssSourceEnvironments = tssSourceEnvironmentMapper.selectTssSourceEnvironmentList(tssSourceEnvironment);
        for(TssSourceEnvironment tssSourceEnvironment1 : tssSourceEnvironments){
            List<SysRes> environmentRes = resManager.queryRes(tssSourceEnvironment1.getSourceEnvironmentId(),ResConstants.BizType.SOURCE_INFO_ENVIRONMENT.getKey());
            if(environmentRes.size() > 0){
                tssSourceEnvironment1.setEnvironmentResIds(environmentRes.get(0).getResId());
                tssSourceEnvironment1.setEnvironmentPreviews(environmentRes.get(0).getResUrl());
            }
        }
        result.put("tssSourceEnvironments",tssSourceEnvironments);

        return result;
    }

    @Override
    public JSONObject appQuerySourceInfo(String tarcecodeapplyno, String tssSourceperiodId) {
        JSONObject result = new JSONObject();
        // 查询溯源码生成单
        List<TssTracecodeapply> tssTracecodeapply = tssTracecodeapplyMapper.selectTssTracecodeapplyListByTarcecodeapplynos(new String[]{tarcecodeapplyno});
        if(tssTracecodeapply.isEmpty()){
            throw new BizException(ErrorCode.TSS_TRACE_APPLY_NOT_EXIST);
        }
        // 查询溯源信息
        TssSourceinfo tssSourceinfo = tssSourceinfoMapper.selectTssSourceinfoByTarcecodeapplyno(tarcecodeapplyno);
        if(tssSourceinfo.getSourceinfoGrowstatus().equals("1")){
            // 查询
            TssSourceperiod tssSourceperiodQuery = new TssSourceperiod();
            tssSourceperiodQuery.setSourceperiodParentid(tssSourceperiodId);
            List<TssSourceperiod> tssSourceperiodList = tssSourceperiodMapper.selectTssSourceperiodList(tssSourceperiodQuery);
            packageSourcePeriodInfo(result,tssSourceperiodList);

        }else {
            TssGoodsperiodrcd tssGoodsperiodrcd = new TssGoodsperiodrcd();
            tssGoodsperiodrcd.setGoodsperiodrcdParentid(tssSourceperiodId);
            List<TssGoodsperiodrcd> tssGoodsperiodrcds = tssGoodsperiodrcdMapper.selectTssGoodsperiodrcdList(tssGoodsperiodrcd);
            packageGoodsPeriodInfo(result,tssGoodsperiodrcds);
        }

        return result;
    }

    public static void packageFigureObject(JSONObject result,List<SysRes> sysResList){
        boolean enableOss = PolicyService.enabledOssCloudPolicy();
        List<JSONObject> goodsNewFace = sysResList.stream().map(item->{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url",enableOss?item.getResOssUrl():item.getResUrl());
            return jsonObject;
        }).collect(Collectors.toList());
        result.put("goodsNewFace",goodsNewFace);
    }
    public void packageSourcePeriod(JSONObject result,List<TssSourceperiod> periods){
        List<JSONObject> tssSourceperiodList = periods.stream().sorted(Comparator.comparing(TssSourceperiod::getSourceperiodStartdate)).map(item->{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",item.getSourceperiodId());
            jsonObject.put("startDate",item.getSourceperiodStartdate());
            jsonObject.put("endDate",item.getSourceperiodEnddate());
            jsonObject.put("periodName",item.getSourceperiodName());
            jsonObject.put("url",item.getPeriodPreview());
            return jsonObject;
        }).collect(Collectors.toList());
        result.put("tssSourceperiod",tssSourceperiodList);
    }
    public void packageGoodsPeriod(JSONObject result,List<TssGoodsperiodrcd> periods){
        List<JSONObject> tssSourceperiodList = periods.stream().sorted(Comparator.comparing(TssGoodsperiodrcd::getGoodsperiodrcdEnddate)).map(item->{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",item.getGoodsperiodrcdId());
            jsonObject.put("startDate",item.getGoodsperiodrcdStartdate());
            jsonObject.put("endDate",item.getGoodsperiodrcdEnddate());
            jsonObject.put("periodName",item.getGoodsperiodrcdName());
            jsonObject.put("url",item.getPeriodPreview());
            return jsonObject;
        }).collect(Collectors.toList());
        result.put("tssSourceperiod",tssSourceperiodList);
    }
    public  void packageSourcePeriodInfo(JSONObject result,List<TssSourceperiod> periods){
        List<JSONObject> tssSourceperiodList = periods.stream().sorted(Comparator.comparing(TssSourceperiod::getSourceperiodFmstaskrcdcreateddate)).map(item->{
            List<SysRes> sysResList = resManager.queryRes(item.getSourceperiodId(),null);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",item.getSourceperiodId());
            jsonObject.put("date",item.getSourceperiodFmstaskrcdcreateddate());
            jsonObject.put("remark",item.getSourceperiodFmstaskrcdremark());
            jsonObject.put("managerName",item.getSourceperiodFmstaskrcdmanagername());
            jsonObject.put("urls",sysResList.stream().map(SysRes::getResUrl).collect(Collectors.toList()));
            return jsonObject;
        }).collect(Collectors.toList());
        result.put("tssSourceperiod",tssSourceperiodList);
    }
    public  void packageGoodsPeriodInfo(JSONObject result,List<TssGoodsperiodrcd> periods){
        List<JSONObject> tssSourceperiodList = periods.stream().sorted(Comparator.comparing(TssGoodsperiodrcd::getGoodsperiodrcdFmstaskcreateddate)).map(item->{
            List<SysRes> sysResList = resManager.queryRes(item.getGoodsperiodrcdId(),null);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",item.getGoodsperiodrcdId());
            jsonObject.put("date",item.getGoodsperiodrcdFmstaskcreateddate());
            jsonObject.put("remark",item.getGoodsperiodrcdFmstaskremark());
            jsonObject.put("managerName",item.getGoodsperiodrcdFmstaskmanagername());
            jsonObject.put("urls",sysResList.stream().map(SysRes::getResUrl).collect(Collectors.toList()));
            return jsonObject;
        }).collect(Collectors.toList());
        result.put("tssSourceperiod",tssSourceperiodList);
    }
}
