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

import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.enums.CommonEnums;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.SecurityUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
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.TssSourceEnvironment;
import com.yunfeiyun.agmp.fms.domain.TssSourceinfo;
import com.yunfeiyun.agmp.fms.domain.TssSourceperiod;
import com.yunfeiyun.agmp.fms.mapper.TssSourceEnvironmentMapper;
import com.yunfeiyun.agmp.fms.mapper.TssSourceinfoMapper;
import com.yunfeiyun.agmp.fms.mapper.TssSourceperiodMapper;
import com.yunfeiyun.agmp.fms.domain.dto.TssSourceperiodDto;
import com.yunfeiyun.agmp.fms.domain.reqvo.AddTssSourceinfoReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.TssSourceinfoListResVo;
import com.yunfeiyun.agmp.fms.service.ITssSourceinfoService;
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 溯源信息Service业务层处理
 * 
 * @author 杨晓辉
 * @date 2023-06-25
 */
@Service
public class TssSourceinfoServiceImpl implements ITssSourceinfoService
{
    @Autowired
    private TssSourceinfoMapper tssSourceinfoMapper;
    @Autowired
    private TssSourceperiodMapper tssSourceperiodMapper;
    @Resource
    private TssSourceEnvironmentMapper tssSourceEnvironmentMapper;
    @Resource
    private SysResMapper sysResMapper;


    /**
     * 查询溯源信息
     * 
     * @param sourceinfoId 溯源信息主键
     * @return 溯源信息
     */
    @Override
    public TssSourceinfo selectTssSourceinfoBySourceinfoId(String sourceinfoId)
    {
        return tssSourceinfoMapper.selectTssSourceinfoBySourceinfoId(sourceinfoId);
    }

    /**
     * 查询溯源信息列表
     * 
     * @param tssSourceinfo 溯源信息
     * @return 溯源信息
     */
    @Override
    public List<TssSourceinfoListResVo> selectTssSourceinfoList(TssSourceinfo tssSourceinfo)
    {
        return tssSourceinfoMapper.selectTssSourceinfoList(tssSourceinfo);
    }

    /**
     * 新增溯源信息
     * 
     * @param tssSourceinfo 溯源信息
     * @return 结果
     */
    @Override
    public int insertTssSourceinfo(TssSourceinfo tssSourceinfo)
    {
        return tssSourceinfoMapper.insertTssSourceinfo(tssSourceinfo);
    }

    @Transactional
    @Override
    public AjaxResult insertTssSourceinfo(AddTssSourceinfoReqVo reqVo) {
        reqVo.setSourceinfoCode(IdUtils.fastSimpleUUID());
        TssSourceinfo tssSourceinfo = new TssSourceinfo();
        BeanUtils.copyProperties(reqVo, tssSourceinfo);
        tssSourceinfo.setSourceinfoId(tssSourceinfo.getId());
        tssSourceinfo.setSourceinfoCreator(SecurityUtils.getUserId());
        tssSourceinfo.setSourceinfoCreateddate(DateUtils.dateTimeNow());
        String sourceinfoId = tssSourceinfo.getSourceinfoId();

        //图片资源集合
        List<SysRes> sysResList = new ArrayList<>();
        /* 头像 */
        SysRes res = new SysRes();
        res.setResId(reqVo.getAvatarResIds());
        res.setResBusId(sourceinfoId);
        sysResList.add(res);

        /* 体检报告 */
        String qualityResIds = reqVo.getQualityResIds();
        if (!StringUtils.isEmpty(qualityResIds)) {
            String[] split = qualityResIds.split(",");
            for (String s : split) {
                SysRes resQuality = new SysRes();
                resQuality.setResId(s);
                resQuality.setResBusId(sourceinfoId);
                sysResList.add(resQuality);
            }
        }

        /* 崭新形象 */
        String figureResIds = reqVo.getFigureResIds();
        if (!StringUtils.isEmpty(figureResIds)) {
            String[] split = figureResIds.split(",");
            for (String s : split) {
                SysRes resFigure = new SysRes();
                resFigure.setResId(s);
                resFigure.setResBusId(sourceinfoId);
                sysResList.add(resFigure);
            }
        }

        List<TssSourceperiod> tssSourceperiods = reqVo.getTssSourceperiods();
        List<TssSourceperiod> addList = new ArrayList<>();
        for (TssSourceperiod tssSourceperiod : tssSourceperiods) {
            tssSourceperiod.setSourceperiodId(tssSourceperiod.getId());
            tssSourceperiod.setSourceinfoId(sourceinfoId);
            tssSourceperiod.setSourceperiodParentid("0");
            tssSourceperiod.setSourceperiodType(CommonEnums.SOURCE_PERIOD_TYPE_PERIOD.getCode());
            addList.add(tssSourceperiod);

            /* 插入周期的图片 */
            if (!StringUtils.isEmpty(tssSourceperiod.getPeriodResIds())) {
                String[] resIds = tssSourceperiod.getPeriodResIds().split(",");
                for (String resId : resIds) {
                    SysRes sysRes = new SysRes();
                    sysRes.setResId(resId);
                    sysRes.setResBusId(tssSourceperiod.getSourceperiodId());
                    sysResList.add(sysRes);
                }
            }

            List<TssSourceperiod> tssSourceperiods1 = tssSourceperiod.getTssSourceperiods();
            for (TssSourceperiod sourceperiod : tssSourceperiods1) {
                sourceperiod.setSourceperiodId(sourceperiod.getId());
                sourceperiod.setSourceperiodParentid(tssSourceperiod.getSourceperiodId());
                sourceperiod.setSourceinfoId(sourceinfoId);
                sourceperiod.setSourceperiodType(CommonEnums.SOURCE_PERIOD_TYPE_RECORD.getCode());
                addList.add(sourceperiod);

                /* 插入农事任务的图片 */
                if (!StringUtils.isEmpty(sourceperiod.getPeriodResIds())) {
                    String[] resIds = sourceperiod.getPeriodResIds().split(",");
                    for (String resId : resIds) {
                        SysRes sysRes = new SysRes();
                        sysRes.setResId(resId);
                        sysRes.setResBusId(sourceperiod.getSourceperiodId());
                        sysResList.add(sysRes);
                    }
                }
            }
        }

        //溯源生长环境数据处理
        List<TssSourceEnvironment> tssSourceEnvironments = reqVo.getTssSourceEnvironments();
        for (TssSourceEnvironment tssSourceEnvironment : tssSourceEnvironments){
            tssSourceEnvironment.setSourceEnvironmentId(tssSourceEnvironment.getId());
            tssSourceEnvironment.setSourceinfoId(sourceinfoId);
            /* 插入溯源生长环境的图片 */
            if (!StringUtils.isEmpty(tssSourceEnvironment.getEnvironmentResIds())) {
                String[] resIds = tssSourceEnvironment.getEnvironmentResIds().split(",");
                for (String resId : resIds) {
                    SysRes sysRes = new SysRes();
                    sysRes.setResId(resId);
                    sysRes.setResBusId(tssSourceEnvironment.getSourceEnvironmentId());
                    sysResList.add(sysRes);
                }
            }
        }

        tssSourceinfoMapper.insertTssSourceinfo(tssSourceinfo);
        if (addList.size() > 0) {
            tssSourceperiodMapper.insertTssSourceperiodBatch(addList);
        }

        //溯源生长环境数据存储
        if (tssSourceEnvironments.size() > 0) {
            tssSourceEnvironmentMapper.insertTssSourceEnvironmentBatch(tssSourceEnvironments);
        }

        for (SysRes sysRes : sysResList) {
            sysResMapper.updateSysRes(sysRes);
        }

        return AjaxResult.success();
    }

    /**
     * 修改溯源信息
     * 
     * @param tssSourceinfo 溯源信息
     * @return 结果
     */
    @Override
    public int updateTssSourceinfo(TssSourceinfo tssSourceinfo)
    {
        return tssSourceinfoMapper.updateTssSourceinfo(tssSourceinfo);
    }

    @Transactional
    @Override
    public AjaxResult updateTssSourceinfo(AddTssSourceinfoReqVo reqVo) {
        TssSourceinfo tssSourceinfo = new TssSourceinfo();
        BeanUtils.copyProperties(reqVo, tssSourceinfo);
        tssSourceinfo.setSourceinfoModifier(SecurityUtils.getUserId());
        tssSourceinfo.setSourceinfoModifieddate(DateUtils.dateTimeNow());

        String sourceinfoId = tssSourceinfo.getSourceinfoId();

        /* 处理图片 */
        List<SysRes> resList = new ArrayList<>();
        List<String> resIdsDel = new ArrayList<>();
        SysRes sysResReq = new SysRes();
        sysResReq.setResBusId(sourceinfoId);
        sysResReq.setResBiztype(ResConstants.BizType.SOURCE_INFO_AVATAR.getKey());
        List<SysRes> sysResList = sysResMapper.selectSysResList(sysResReq);
        if (!sysResList.isEmpty()) {
            if (!sysResList.get(0).getResId().equals(reqVo.getAvatarResIds())) {
                resIdsDel.add(sysResList.get(0).getResId());
                SysRes res = new SysRes();
                res.setResId(reqVo.getAvatarResIds());
                res.setResBusId(sourceinfoId);
                resList.add(res);
            }
        }else {
            SysRes res = new SysRes();
            res.setResId(reqVo.getAvatarResIds());
            res.setResBusId(sourceinfoId);
            resList.add(res);
        }

        /* 体检报告 */
        resList(reqVo.getQualityResIds(), sourceinfoId, resList, resIdsDel, ResConstants.BizType.SOURCE_INFO_QUALITY.getKey());

        /* 崭新形象 */
        resList(reqVo.getFigureResIds(), sourceinfoId, resList, resIdsDel, ResConstants.BizType.SOURCE_INFO_FIGURE.getKey());

        /*  查询原有数据，用于判断当次修改删除掉的记录  */
        List<TssSourceperiod> tssSourceperiods = reqVo.getTssSourceperiods();
        List<String> deleteListIds = new ArrayList<>();
        TssSourceperiod period = new TssSourceperiod();
        period.setSourceinfoId(sourceinfoId);
        List<TssSourceperiod> tssSourceperiods2 = tssSourceperiodMapper.selectTssSourceperiodList(period);
        for (TssSourceperiod tssSourceperiod : tssSourceperiods2) {
            boolean flag = false;
            for (TssSourceperiod sourceperiod : tssSourceperiods) {
                if (tssSourceperiod.getSourceperiodId().equals(sourceperiod.getSourceperiodId())) {
                    flag = true;
                }
                for (TssSourceperiod sourceperiodChild : sourceperiod.getTssSourceperiods()) {
                    if (tssSourceperiod.getSourceperiodId().equals(sourceperiodChild.getSourceperiodId())) {
                        flag = true;
                    }
                }
            }
            if (!flag) {
                deleteListIds.add(tssSourceperiod.getSourceperiodId());
                //删除下面的图片
                SysRes req = new SysRes();
                req.setResBusId(tssSourceperiod.getSourceperiodId());
                List<SysRes> resList1 = sysResMapper.selectSysResList(req);
                for (SysRes sysRes : resList1) {
                    resIdsDel.add(sysRes.getResId());
                }
            }
        }

        List<TssSourceperiod> addList = new ArrayList<>();
        List<TssSourceperiod> updateList = new ArrayList<>();
        for (TssSourceperiod tssSourceperiod : tssSourceperiods) {

            if (StringUtils.isEmpty(tssSourceperiod.getSourceperiodId())) {
                tssSourceperiod.setSourceperiodId(tssSourceperiod.getId());
                tssSourceperiod.setSourceinfoId(sourceinfoId);
                tssSourceperiod.setSourceperiodParentid("0");
                tssSourceperiod.setSourceperiodType(CommonEnums.SOURCE_PERIOD_TYPE_PERIOD.getCode());
                addList.add(tssSourceperiod);

                //处理图片
                resList(tssSourceperiod.getPeriodResIds(), tssSourceperiod.getSourceperiodId(), resList, resIdsDel, ResConstants.BizType.SOURCE_INFO_PERIOD.getKey());


                List<TssSourceperiod> tssSourceperiods1 = tssSourceperiod.getTssSourceperiods();
                for (TssSourceperiod sourceperiod : tssSourceperiods1) {
                    sourceperiod.setSourceperiodId(sourceperiod.getId());
                    sourceperiod.setSourceperiodParentid(tssSourceperiod.getSourceperiodId());
                    sourceperiod.setSourceinfoId(sourceinfoId);
                    sourceperiod.setSourceperiodType(CommonEnums.SOURCE_PERIOD_TYPE_RECORD.getCode());
                    addList.add(sourceperiod);

                    /* 插入农事任务的图片 */
                    if (!StringUtils.isEmpty(sourceperiod.getPeriodResIds())) {
                        String[] resIds = sourceperiod.getPeriodResIds().split(",");
                        for (String resId : resIds) {
                            SysRes sysRes = new SysRes();
                            sysRes.setResId(resId);
                            sysRes.setResBusId(sourceperiod.getSourceperiodId());
                            resList.add(sysRes);
                        }
                    }
                }
            } else {
                /* 修改 */
                updateList.add(tssSourceperiod);

                //处理图片
                resList(tssSourceperiod.getPeriodResIds(), tssSourceperiod.getSourceperiodId(), resList, resIdsDel, ResConstants.BizType.SOURCE_INFO_PERIOD.getKey());

                List<TssSourceperiod> tssSourceperiods1 = tssSourceperiod.getTssSourceperiods();
                for (TssSourceperiod sourceperiod : tssSourceperiods1) {
                    if (StringUtils.isEmpty(sourceperiod.getSourceperiodId())) {
                        sourceperiod.setSourceperiodId(sourceperiod.getId());
                        sourceperiod.setSourceperiodParentid(tssSourceperiod.getSourceperiodId());
                        sourceperiod.setSourceinfoId(sourceinfoId);
                        sourceperiod.setSourceperiodType(CommonEnums.SOURCE_PERIOD_TYPE_RECORD.getCode());
                        addList.add(sourceperiod);

                        /* 插入农事任务的图片 */
                        if (!StringUtils.isEmpty(sourceperiod.getPeriodResIds())) {
                            String[] resIds = sourceperiod.getPeriodResIds().split(",");
                            for (String resId : resIds) {
                                SysRes sysRes = new SysRes();
                                sysRes.setResId(resId);
                                sysRes.setResBusId(sourceperiod.getSourceperiodId());
                                resList.add(sysRes);
                            }
                        }
                    } else {
                        updateList.add(sourceperiod);
                        resList(sourceperiod.getPeriodResIds(), sourceperiod.getSourceperiodId(), resList, resIdsDel, ResConstants.BizType.SOURCE_INFO_PERIOD.getKey());
                    }
                }
            }
        }

        tssSourceinfoMapper.updateTssSourceinfo(tssSourceinfo);
        if (addList.size() > 0) {
            tssSourceperiodMapper.insertTssSourceperiodBatch(addList);
        }
        if (updateList.size() > 0) {
            List<TssSourceperiodDto> updateList2 = new ArrayList<>();
            for (TssSourceperiod tssSourceperiod : updateList) {
                TssSourceperiodDto dto = new TssSourceperiodDto();
                BeanUtils.copyProperties(tssSourceperiod, dto);
                updateList2.add(dto);
            }
            tssSourceperiodMapper.updateTssSourceperiodBatch(updateList2);
        }
        if (deleteListIds.size() > 0) {
            tssSourceperiodMapper.deleteTssSourceperiodBySourceperiodIds(deleteListIds.toArray(new String[deleteListIds.size()]));
        }

        //修改溯源相关信息
        List<String> resBusIds = this.updateTssSourceEnvironment(sourceinfoId,reqVo,resList,resIdsDel);

        for (SysRes sysRes : resList) {
            sysResMapper.updateSysRes(sysRes);
        }

        /*删除图片*/
        if (resIdsDel.size() > 0) {
//            List<SysRes> sysResOldList = sysResMapper.selectResByResIds(resIdsDel);
            String[] array = resIdsDel.toArray(new String[resIdsDel.size()]);
            sysResMapper.deleteSysResByResIds(array);
//            for (SysRes res : sysResOldList) {
//                String resUrl = res.getResUrl();
//                File file = new File(resUrl);
//                if (file.exists()) {
//                    file.delete();
//                }
//            }

        }

        //删除历史溯源信息资源
        sysResMapper.deleteSysResbes(resBusIds.toArray(new String[resBusIds.size()]));

        return AjaxResult.success();
    }

    /**
     * 修改溯源相关信息
     * @param sourceinfoId
     * @param reqVo
     * @param resList
     * @param resIdsDel
     */
    public List<String> updateTssSourceEnvironment(String sourceinfoId,AddTssSourceinfoReqVo reqVo,List<SysRes> resList,List<String> resIdsDel) {
        //先查询所有生长环境信息标识，然后根据标识删除资源
        TssSourceEnvironment environment = new TssSourceEnvironment();
        environment.setSourceinfoId(sourceinfoId);
        List<TssSourceEnvironment> tssSourceEnvironmentList= tssSourceEnvironmentMapper.selectTssSourceEnvironmentList(environment);
        List<String> resBusIds = new ArrayList<>();
        for (TssSourceEnvironment map: tssSourceEnvironmentList){
            resBusIds.add(map.getSourceEnvironmentId());
        }

        //删除溯源生产环境信息
        tssSourceEnvironmentMapper.deleteTssSourceEnvironmentBySourceinfoId(sourceinfoId);

        //新增溯源生长环境数据处理
        List<TssSourceEnvironment> tssSourceEnvironments = reqVo.getTssSourceEnvironments();
        for (TssSourceEnvironment tssSourceEnvironment : tssSourceEnvironments){
            //定义sourceEnvironmentId
            String sourceEnvironmentId = tssSourceEnvironment.getId();
            //传参数据中SourceEnvironmentId为空时直接新增数据
            if(StringUtils.isNotBlank(tssSourceEnvironment.getSourceEnvironmentId())){
                //根据修改前的业务id查询资源
                SysRes selectSysRes = new SysRes();
                selectSysRes.setResBusId(tssSourceEnvironment.getSourceEnvironmentId());
                List<SysRes> selectSysResList = sysResMapper.selectSysResList(selectSysRes);
                //如果查询不到数据，直接走新增
                if(selectSysResList.size() > 0) {
                    //当修改数据中redIds不为空，则修改ResBusId为最新值
                    if (StringUtils.isNotBlank(tssSourceEnvironment.getEnvironmentResIds())) {
                        for (SysRes map : selectSysResList) {
                            SysRes sysRes = new SysRes();
                            sysRes.setResId(map.getResId());
                            sysRes.setResBusId(sourceEnvironmentId);
                            resList.add(sysRes);
                        }
                    } else {
                        //删除redIds为空数据
                        for (SysRes map : selectSysResList) {
                            resIdsDel.add(map.getResId());
                        }
                    }
                }
            } else {
                /* 插入溯源生长环境的图片 */
                if (!StringUtils.isEmpty(tssSourceEnvironment.getEnvironmentResIds())) {
                    String[] resIds = tssSourceEnvironment.getEnvironmentResIds().split(",");
                    for (String resId : resIds) {
                        SysRes sysRes = new SysRes();
                        sysRes.setResId(resId);
                        sysRes.setResBusId(sourceEnvironmentId);
                        resList.add(sysRes);
                    }
                }
            }
            tssSourceEnvironment.setSourceinfoId(sourceinfoId);
            tssSourceEnvironment.setSourceEnvironmentId(sourceEnvironmentId);
        }

        //溯源生长环境数据存储
        if (tssSourceEnvironments.size() > 0) {
            tssSourceEnvironmentMapper.insertTssSourceEnvironmentBatch(tssSourceEnvironments);
        }

        return resBusIds;
    }

    /**
     * 批量删除溯源信息
     * 
     * @param sourceinfoIds 需要删除的溯源信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTssSourceinfoBySourceinfoIds(String[] sourceinfoIds)
    {
        for (String sourceinfoId : sourceinfoIds) {
            tssSourceperiodMapper.deleteTssSourceperiodBySourceinfoId(sourceinfoId);
        }
        return tssSourceinfoMapper.deleteTssSourceinfoBySourceinfoIds(sourceinfoIds);
    }

    /**
     * 删除溯源信息信息
     * 
     * @param sourceinfoId 溯源信息主键
     * @return 结果
     */
    @Override
    public int deleteTssSourceinfoBySourceinfoId(String sourceinfoId)
    {
        return tssSourceinfoMapper.deleteTssSourceinfoBySourceinfoId(sourceinfoId);
    }

    public void resList(String resIdsStr, String resBusId, List<SysRes> resList, List<String> resIdsDel, String resBiztype){
        SysRes sysRes = new SysRes();
        sysRes.setResBusId(resBusId);
        if (!StringUtils.isEmpty(resBiztype)) {
            sysRes.setResBiztype(resBiztype);
        }
        List<SysRes> sysResList2 = sysResMapper.selectSysResList(sysRes);
        List<String> resIdsOld = new ArrayList<>();
        for (SysRes res : sysResList2) {
            resIdsOld.add(res.getResId());
        }
        List<String> resIdsNew = new ArrayList<>();
        if (!StringUtils.isEmpty(resIdsStr)) {
            String[] resIds = resIdsStr.split(",");
            resIdsNew = Arrays.asList(resIds);
        }

        List<String> resIdsOld2 = new ArrayList<>();
        resIdsOld2.addAll(resIdsOld);
        List<String> resIdsNew2 = new ArrayList<>();
        resIdsNew2.addAll(resIdsNew);
        //获取删除掉的图片id
        resIdsOld2.removeAll(resIdsNew);
        //获取新增的图片id
        resIdsNew2.removeAll(resIdsOld);

        resIdsDel.addAll(resIdsOld2);
        //新增的记录标识与业务标识
        for (String s : resIdsNew2) {
            SysRes sysRes2 = new SysRes();
            sysRes2.setResId(s);
            sysRes2.setResBusId(resBusId);
            resList.add(sysRes2);
        }
    }

}
