package com.mortals.xhx.module.one.service.impl;

import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.busiz.oneProblemlist.OneProblemInfo;
import com.mortals.xhx.busiz.question.*;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.matter.model.*;
import com.mortals.xhx.module.matter.service.*;
import com.mortals.xhx.module.one.model.*;
import com.mortals.xhx.module.one.service.OneClassifyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.one.dao.OneClassifyTopicalDao;
import com.mortals.xhx.module.one.service.OneClassifyTopicalService;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Title: 分类引导主题中间表</p>
 * <p>Description: OneClassifyTopicalService service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 *
 * @version 1.0.0
 */
@Service("oneClassifyTopicalService")
public class OneClassifyTopicalServiceImpl extends AbstractCRUDServiceImpl<OneClassifyTopicalDao, OneClassifyTopicalEntity, Long> implements OneClassifyTopicalService {

    @Autowired
    private OneClassifyService oneClassifyService;
    @Autowired
    private MatterService matterService;
    @Autowired
    private MatterDatumService matterDatumService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private MatterDatumFileService matterDatumFileService;
    @Autowired
    private MatterFlowlimitService matterFlowlimitService;
    @Autowired
    private MatterQuestionService matterQuestionService;
    @Autowired
    private MatterAcceptService matterAcceptService;


    @Override
    protected void saveBefore(OneClassifyTopicalEntity entity, Context context) throws AppException {
        int max = this.find(new OneClassifyTopicalQuery()).stream().mapToInt(OneClassifyTopicalEntity::getClassifyRank).max().orElseGet(() -> 0);
        entity.setClassifyRank(max + 1);
        super.saveBefore(entity, context);
    }

    @Override
    protected void logicDeleteAfter(OneClassifyTopicalEntity entity, Context context) throws AppException {
        //逻辑级联删除
        List<OneClassifyEntity> oneClassifyEntities = oneClassifyService.find(new OneClassifyQuery().deleted(YesNoEnum.NO.getValue()).parentId(entity.getClassifyId()));
        if (!ObjectUtils.isEmpty(oneClassifyEntities)) {
            oneClassifyEntities.stream().peek(item -> oneClassifyService.logicDelete(item, context)).count();
        }
        super.logicDeleteAfter(entity, context);
    }

    @Override
    public void upOrDownTopicList(Long id, Integer type) {

        OneClassifyTopicalQuery query = new OneClassifyTopicalQuery().deleted(YesNoEnum.NO.getValue());
        query.setOrderColList(Arrays.asList(new OrderCol("classify_rank")));
        query.setOrderKind(OrderCol.ASCENDING);
        List<OneClassifyTopicalEntity> list = this.find(query);
        OneClassifyTopicalEntity preEntity = null;
        OneClassifyTopicalEntity curEntity = null;
        if (type == YesNoEnum.NO.getValue()) {
            //up
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId() == id && i > 0) {
                    curEntity = list.get(i);
                    preEntity = list.get(i - 1);
                    break;
                }
            }

        } else {
            //down
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId() == id && i + 1 < list.size()) {
                    curEntity = list.get(i);
                    preEntity = list.get(i + 1);
                    break;
                }
            }
        }

        if (preEntity != null && curEntity != null) {
            //交换
            int temp = preEntity.getClassifyRank();
            preEntity.setClassifyRank(curEntity.getClassifyRank());
            curEntity.setClassifyRank(temp);

            this.update(preEntity);
            this.update(curEntity);
        }


    }

    @Override
    public OneProblemInfo findAllQuestion(Long id) {
        //获取根节点，递归获取所有树节点

        OneProblemInfo info = new OneProblemInfo();

        OneClassifyEntity rootClassify = oneClassifyService.get(id);
        if (!ObjectUtils.isEmpty(rootClassify)) {

            info.setId(rootClassify.getId());
            info.setIsLeaf(rootClassify.getIsLeaf());
            info.setLevel(rootClassify.getClassifyLevel());
            info.setMatterIds(rootClassify.getMatterIds());
            info.setName(rootClassify.getClassifyName());
            info.setParentId(rootClassify.getParentId());
            info.setRemark(rootClassify.getSortRemarks());
            info.setIsAns(rootClassify.getIsAns());
            List<OneProblemInfo> collect = getOneClassifyEntities(rootClassify);
            if (!ObjectUtils.isEmpty(collect)) {
                info.setChildren(collect);
            }
        }
        return info;

    }

    private List<OneProblemInfo> getOneClassifyEntities(OneClassifyEntity rootClassify) {
        List<OneProblemInfo> collect = oneClassifyService.find(new OneClassifyQuery().parentId(rootClassify.getId()).deleted(YesNoEnum.NO.getValue()))
                .stream().map(item -> {
                    OneProblemInfo info = new OneProblemInfo();
                    info.setId(item.getId());
                    info.setIsLeaf(item.getIsLeaf());
                    info.setLevel(item.getClassifyLevel());
                    info.setMatterIds(item.getMatterIds());
                    info.setName(item.getClassifyName());
                    info.setParentId(item.getParentId());
                    info.setRemark(item.getSortRemarks());
                    info.setIsAns(item.getIsAns());

                    List<OneProblemInfo> oneClassifyEntities = this.getOneClassifyEntities(item);

                    if (!ObjectUtils.isEmpty(oneClassifyEntities)) {
                        info.setChildren(oneClassifyEntities);
                    }
                    return info;
                }).collect(Collectors.toList());
        return collect;
    }


    @Override
    public QuestionInfo getMattersByAnswers(AnswerReq req) {

        QuestionInfo questionInfo = new QuestionInfo();
        Map<String, String> materialPropertyMap = paramService.getParamByFirstOrganize(Constant.Param_materialProperty);
        Map<String, String> materialTypeMap = paramService.getParamByFirstOrganize(Constant.Param_materialType);
        Map<String, String> electronicgsMap = paramService.getParamByFirstOrganize(Constant.Param_electronicgs);
        Map<String, String> materialSourceMap = paramService.getParamByFirstOrganize(Constant.Param_materialSource);
        //Map<String, String> paperGgMap = paramService.getParamByFirstOrganize(Constant.Param_paperGg);
        Map<String, String> jianmMsMap = paramService.getParamByFirstOrganize(Constant.Param_jianmMs);
        //Map<String, String> sealWayMap = paramService.getParamByFirstOrganize(Constant.Param_sealWay);
        Map<String, String> isMustMap = paramService.getParamByFirstOrganize(Constant.Param_isMust);


        //获取关联的所有事项
        List<Long> matterIdsList = oneClassifyService.find(new OneClassifyQuery().idList(req.getOptionIds()))
                .stream().flatMap(item ->
                        Arrays.asList(item.getMatterIds().split(",")).stream()
                ).map(Long::valueOf).distinct().collect(Collectors.toList());
        //根据事项获取所有材料
        List<MatterEntity> matterList = matterService.find(new MatterQuery().idList(matterIdsList));

        List<MatterInfo> matterEntityList = matterList.stream().map(item -> {
            MatterInfo matterinfo = new MatterInfo();
            matterinfo.setId(item.getId());
            matterinfo.setMatterName(item.getMatterName());
            return matterinfo;
        }).collect(Collectors.toList());
        questionInfo.setMatterInfoList(matterEntityList);

        List<DatumInfo> datumInfoList = matterDatumService.find(new MatterDatumQuery().matterIdList(matterIdsList))
                .stream().distinct().map(item -> {
                    DatumInfo datumInfo = new DatumInfo();
                    BeanUtils.copyProperties(item, datumInfo, BeanUtil.getNullPropertyNames(item));
                    datumInfo.setId(item.getId());
                    datumInfo.setJianmMs(jianmMsMap.getOrDefault(item.getJianmMs().toString(), ""));
                    datumInfo.setIsMust(isMustMap.getOrDefault(item.getIsMust().toString(), ""));
                    datumInfo.setMaterialProperty(materialPropertyMap.getOrDefault(item.getMaterialProperty().toString(), ""));
                    datumInfo.setMaterialSource(materialSourceMap.getOrDefault(item.getMaterialSource().toString(), ""));
                    datumInfo.setMaterialSourceSm(item.getMaterialSourceSm());
                    datumInfo.setElectronicgs(electronicgsMap.getOrDefault(item.getElectronicgs().toString(), ""));
                    datumInfo.setMaterialType(materialTypeMap.getOrDefault(item.getMaterialType().toString(), ""));
                    datumInfo.setIsLack(YesNoEnum.getByValue(item.getIsLack()).getDesc());
                    datumInfo.setIsjianm(YesNoEnum.getByValue(item.getIsjianm()).getDesc());

                    datumInfo.setSealWay(item.getSealWayText());
                    datumInfo.setPaperGg(item.getPaperGgText());

                    List<DatumDownloadInfo> downloadInfoList = matterDatumFileService.find(new MatterDatumFileQuery().datumid(item.getId())).stream().map(file -> {
                        DatumDownloadInfo datumDownloadInfo = new DatumDownloadInfo();
                        BeanUtils.copyProperties(file, datumDownloadInfo, BeanUtil.getNullPropertyNames(file));
                        return datumDownloadInfo;
                    }).collect(Collectors.toList());
                    datumInfo.setAttachList(downloadInfoList);

                    return datumInfo;
                }).collect(Collectors.toList());
        questionInfo.setDatumInfoList(datumInfoList);

        //根据事项获取所有申请条件
        List<AcceptInfo> acceptInfoList = matterAcceptService.find(new MatterAcceptQuery().matterIdList(matterIdsList)).stream().map(item -> {
            AcceptInfo acceptInfo = new AcceptInfo();
            acceptInfo.setTitle(item.getTitle());
            acceptInfo.setContent(item.getContent());
            acceptInfo.setMatterId(item.getMatterId());
            return acceptInfo;
        }).collect(Collectors.toList());
        questionInfo.setAcceptInfoList(acceptInfoList);

        //根据事项获取所有办理流程

        List<FlowLimitInfo> flowLimitInfoList = matterFlowlimitService.find(new MatterFlowlimitQuery().matterIdList(matterIdsList)).stream().map(item -> {
            FlowLimitInfo flowLimitInfo = new FlowLimitInfo();
            BeanUtils.copyProperties(item, flowLimitInfo, BeanUtil.getNullPropertyNames(item));
            return flowLimitInfo;
        }).collect(Collectors.toList());
        questionInfo.setFlowLimitInfoList(flowLimitInfoList);

        //根据事项获取所有常见问题
        List<QAndAInfo> qAndAInfoList = matterQuestionService.find(new MatterQuestionQuery().matterIdList(matterIdsList)).stream().map(item -> {
            QAndAInfo info = new QAndAInfo();
            info.setQuestion(item.getTitle());
            info.setAnswer(item.getContent());
            info.setMatterId(item.getMatterId());
            return info;
        }).collect(Collectors.toList());
        questionInfo.setQAndAInfoList(qAndAInfoList);

        return questionInfo;
    }
}