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

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl;
import com.mortals.framework.util.DataUtil;
import com.mortals.xhx.base.framework.config.InterceptorConfig;
import com.mortals.xhx.common.code.SourceEnum;
import com.mortals.xhx.module.matter.dao.MatterDao;
import com.mortals.xhx.module.matter.model.*;
import com.mortals.xhx.module.matter.service.*;
import com.mortals.xhx.module.matters.model.MattersDetailEntity;
import com.mortals.xhx.module.matters.model.MattersDetailQuery;
import com.mortals.xhx.module.matters.model.MattersEntity;
import com.mortals.xhx.module.matters.model.MattersQuery;
import com.mortals.xhx.module.matters.service.MattersAreaService;
import com.mortals.xhx.module.matters.service.MattersDetailService;
import com.mortals.xhx.module.matters.service.MattersService;
import com.mortals.xhx.module.site.model.SiteEntity;
import com.mortals.xhx.module.site.model.SiteMatterEntity;
import com.mortals.xhx.module.site.model.SiteMatterQuery;
import com.mortals.xhx.module.site.service.SiteMatterService;
import com.mortals.xhx.module.site.service.SiteService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * MatterService
 * 基础事项 service实现
 *
 * @author zxfei
 * @date 2022-01-12
 */
@Service("matterService")
public class MatterServiceImpl extends AbstractCRUDCacheServiceImpl<MatterDao, MatterEntity, Long> implements MatterService {
    @Autowired
    private SiteMatterService siteMatterService;
    @Autowired
    private SiteService siteService;
    @Autowired
    private MattersService mattersService;
    @Autowired
    private InterceptorConfig interceptorConfig;

    @Autowired
    private MattersAreaService mattersAreaService;
    @Autowired
    private MattersDetailService mattersDetailService;
    @Autowired
    private MatterFlowlimitService matterFlowlimitService;
    @Autowired
    private MatterAcceptService matterAcceptService;
    @Autowired
    private MatterSetbaseService matterSetbaseService;
    @Autowired
    private MatterQuestionService matterQuestionService;
    @Autowired
    private MatterIntermediaryService matterIntermediaryService;
    @Autowired
    private MatterDatumService matterDatumService;
    @Autowired
    private MatterDatumFileService matterDatumFileService;
    @Autowired
    private MatterChargesService matterChargesService;


    @Override
    protected void saveBefore(MatterEntity entity, Context context) throws AppException {

        super.saveBefore(entity, context);
    }

    @Override
    protected void updateBefore(MatterEntity entity, Context context) throws AppException {

        super.updateBefore(entity, context);
    }


    @Override
    protected void updateAfter(MatterEntity entity, Context context) throws AppException {
        //同步更新所有站点
        List<SiteMatterEntity> collect = siteMatterService.find(new SiteMatterQuery().matterId(entity.getId())).stream()
                .map(item -> {
                    item.setMatterName(entity.getMatterName());
                    return item;
                }).collect(Collectors.toList());
        siteMatterService.update(collect, context);
        super.updateAfter(entity, context);
    }


    @Override
    protected void removeBefore(Long[] ids, Context context) throws AppException {
        //有子节点 禁止删除
        super.removeBefore(ids, context);
    }

    @Override
    public void addMatterToSite(String matterIds, Long siteId, Context context) {
        if (ObjectUtils.isEmpty(siteId)) {
            throw new AppException("请选择对应站点");
        }
        List<Long> matterIdList = Arrays.asList(matterIds.split(",")).stream().map(Long::parseLong).collect(Collectors.toList());
        MatterQuery matterQuery = new MatterQuery();
        matterQuery.setIdList(matterIdList);
        this.find(matterQuery).stream()
                .peek(item -> updateOrSave(item, siteId, context)).count();
    }

    private void updateOrSave(MatterEntity item, Long siteId, Context context) {
        SiteMatterEntity siteMatterEntity = siteMatterService.selectOne(new SiteMatterQuery().siteId(siteId).matterId(item.getId()));
        if (!ObjectUtils.isEmpty(siteMatterEntity)) {
            BeanUtils.copyProperties(item, siteMatterEntity, new String[]{"id"});

            siteMatterEntity.setMatterName(item.getMatterName());
            siteMatterEntity.setUpdateTime(new Date());
            siteMatterService.update(siteMatterEntity, context);
        } else {
            siteMatterEntity = new SiteMatterEntity();
            SiteEntity siteEntity = siteService.get(siteId);
            siteMatterEntity.setSiteId(siteEntity.getId());
            siteMatterEntity.setSiteName(siteEntity.getSiteName());
            siteMatterEntity.setMatterId(item.getId());
            siteMatterEntity.setMatterName(item.getMatterName());
            siteMatterEntity.setCreateUserId(context.getUser().getId());
            siteMatterEntity.setCreateTime(new Date());
            siteMatterService.save(siteMatterEntity, context);
        }
    }


    @Override
    public void syncMatter(Context context) {
        List<MatterEntity> list = this.find(new MatterQuery().source(SourceEnum.政务网.getValue()));
        if (!ObjectUtils.isEmpty(list)) {
            // TODO: 2022/3/30  查询本地数据，进行交叉更新对比
        } else {
            //读取区域数据
            //mattersAreaService.find()
            //读取事项基础数据
            List<MattersEntity> mattersEntities = mattersService.find(new MattersQuery());
            for (MattersEntity item : mattersEntities) {
                if ("true".equals(item.getHaveGetMatterInfo())) {
                    MattersDetailEntity itemDetail = mattersDetailService.selectOne(new MattersDetailQuery().matterCode(item.getMatterCode()));
                    if (!ObjectUtils.isEmpty(itemDetail)) {
                        //解析事项详细数据
                        MatterEntity matterEntity = new MatterEntity();
                        matterEntity.initAttrValue();
                        matterEntity.setMatterNo(item.getMatterCode());
                        matterEntity.setTcode(item.getMatterCode());
                        matterEntity.setMatterName(item.getName());
                        matterEntity.setTname(item.getName());
                        matterEntity.setSource(SourceEnum.政务网.getValue());
                        matterEntity.setCreateTime(new Date());
                        matterEntity.setCreateUserName("system");
                        String basicinfoJbxx = itemDetail.getBasicinfoJbxx();
                        //解析基础数据
                        //todo 设置基础值
                        //基本信息属性与字段映射表
                        Setting baseInfoSetting = interceptorConfig.getBaseInfoSetting();
                        Setting sqclInfoSetting = interceptorConfig.getSqclInfoSetting();
                        createBaseMatterJson(basicinfoJbxx, baseInfoSetting, matterEntity);
                        this.save(matterEntity);
                        //todo 材料
                        String sqclJson = itemDetail.getMaterialsSqcl();
                        if (!ObjectUtils.isEmpty(sqclJson) || !"{}".equals(sqclJson)) {
                            createSqclJson(sqclJson, sqclInfoSetting, matterEntity);
                        }
                        //todo 受理条件
                        String sltjJson = itemDetail.getConditionsSltj();
                        if (!ObjectUtils.isEmpty(sltjJson) || !"{}".equals(sltjJson)) {
                            createSltjJson(sltjJson, matterEntity);
                        }

                        //todo 收费标准
                        String sfbzJson = itemDetail.getChargingSfbz();
                        if (!ObjectUtils.isEmpty(sfbzJson) || !"{}".equals(sfbzJson)) {
                            createSfbzJson(sfbzJson, matterEntity);
                        }
                        //todo 办理流程
                        String bllcJson = itemDetail.getProcessBllc();
                        if (!ObjectUtils.isEmpty(bllcJson) || !"{}".equals(bllcJson)) {
                            createBllcJson(bllcJson, matterEntity);
                        }
                        //todo 常见问题
                        String cjwtJson = itemDetail.getQuestionCjwt();
                        if (!ObjectUtils.isEmpty(cjwtJson) || !"{}".equals(cjwtJson)) {
                            createCjwtJson(cjwtJson, matterEntity);
                        }
                        //todo 设定依据
                        String sdyjJson = itemDetail.getBasisSdyj();
                        if (!ObjectUtils.isEmpty(sdyjJson) || !"{}".equals(sdyjJson)) {
                            createSdyjJson(cjwtJson, matterEntity);
                        }
                        //todo 中介服务
                        String zjfwJson = itemDetail.getIntermediaryZjfw();
                        if (!ObjectUtils.isEmpty(zjfwJson) || !"{}".equals(zjfwJson)) {
                            createZjfwJson(zjfwJson, matterEntity);
                        }
                    }
                }
            }
            //根据事项查询事项详细等，并更新
        }
    }

    public void createBaseMatterJson(String baseJson, Setting baseInfoSetting, MatterEntity matterEntity) {
        JSONObject root = JSON.parseObject(baseJson);
        JSONArray jsonArray = root.getJSONArray("基本信息");
        if (!ObjectUtils.isEmpty(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray subArray = jsonArray.getJSONArray(i);
                if (!ObjectUtils.isEmpty(subArray)) {
                    for (int j = 0; j < subArray.size(); j++) {
                        subArray.getJSONObject(j).entrySet().stream()
                                .peek(m -> {
                                    String value = baseInfoSetting.getOrDefault(m.getKey(), "");
                                    if (!ObjectUtils.isEmpty(value) && !"无".equals(value)) {
                                        //value 为对象配置的属性值，反射设置属性值
                                        try {
                                            ReflectUtil.setFieldValue(matterEntity, value, m.getValue().toString().replaceAll("、", ","));
                                        } catch (Exception e) {
                                            log.error(String.format("设置值异常！key:%s,value:%s", value, m.getValue()));
                                        }
                                    }
                                }).count();
                    }
                }
            }

        }


        //反射设置事项属性
    }

    public void createSqclJson(String sqclJson, Setting sqclInfoSetting, MatterEntity matterEntity) {
        JSONObject root = null;
        try {
            root = JSON.parseObject(sqclJson);
        } catch (Exception e) {
            sqclJson = sqclJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(sqclJson);
            } catch (Exception e1) {
                //log.error("error json:" + sqclJson);
                return;
            }
        }

        if (root.isEmpty()) {
            //log.info("root is null");
            return;
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = root.getJSONArray("申请材料");
        } catch (Exception e) {
            log.error("error 无申请材料");
        }

        if (ObjectUtils.isEmpty(jsonArray)) {
            log.info("申请材料 is null");
            return;
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject secondJsonObject = jsonArray.getJSONObject(i);
            MatterDatumEntity datumEntity = new MatterDatumEntity();
            datumEntity.setMatterId(matterEntity.getId());
            datumEntity.setMaterialName(matterEntity.getMatterName());
            datumEntity.setSource(SourceEnum.政务网.getValue());
            datumEntity.setCreateTime(new Date());
            datumEntity.setCreateUser("system");

            //材料详情
            JSONArray jsonArrayThree = secondJsonObject.getJSONArray("材料详情");
            if (!ObjectUtils.isEmpty(jsonArrayThree)) {
                for (int j = 0; j < jsonArrayThree.size(); j++) {
                    jsonArrayThree.getJSONObject(j).entrySet().stream().peek(m -> {
                        String value = sqclInfoSetting.getOrDefault(m.getKey(), "");
                        if (!ObjectUtils.isEmpty(value)) {
                            //value 为对象配置的属性值，反射设置属性值
                            try {
                                ReflectUtil.setFieldValue(datumEntity, value, m.getValue().toString().replaceAll("、", ","));
                            } catch (Exception e) {
                                log.error(String.format("设置值异常！key:%s,value:%s", value, m.getValue()));
                            }
                        }
                    }).count();
                }
            }
            matterDatumService.save(datumEntity);
            //示例样表
            JSONArray jsonArrayone = secondJsonObject.getJSONArray("示例样表");
            if (!ObjectUtils.isEmpty(jsonArrayone)) {
                ArrayList<MatterDatumFileEntity> fileArrayList = new ArrayList<>();
                for (int j = 0; j < jsonArrayone.size(); j++) {
                    MatterDatumFileEntity fileEntity = new MatterDatumFileEntity();
                    fileEntity.setCreateTime(new Date());
                    fileEntity.setCreateUser("system");
                    fileEntity.setDatumId(datumEntity.getId());
                    fileEntity.setMaterialName(datumEntity.getMaterialName());
                    fileEntity.setSource(SourceEnum.政务网.getValue());
                    fileEntity.setFiletype(1);
                    jsonArrayone.getJSONObject(j).entrySet().stream().peek(m -> {
                        fileEntity.setFileName(m.getKey());
                        fileEntity.setFileUrl(m.getValue().toString());
                    }).count();
                    fileArrayList.add(fileEntity);
                }
                matterDatumFileService.save(fileArrayList);

            }
            //空白表格
            JSONArray jsonArraytwo = secondJsonObject.getJSONArray("空白表格");
            if (!ObjectUtils.isEmpty(jsonArraytwo)) {
                ArrayList<MatterDatumFileEntity> fileArrayList = new ArrayList<>();
                for (int j = 0; j < jsonArraytwo.size(); j++) {
                    MatterDatumFileEntity fileEntity = new MatterDatumFileEntity();
                    fileEntity.setCreateTime(new Date());
                    fileEntity.setCreateUser("system");
                    fileEntity.setDatumId(datumEntity.getId());
                    fileEntity.setMaterialName(datumEntity.getMaterialName());
                    fileEntity.setSource(SourceEnum.政务网.getValue());
                    fileEntity.setFiletype(2);
                    jsonArraytwo.getJSONObject(j).entrySet().stream().peek(m -> {
                        fileEntity.setFileName(m.getKey());
                        fileEntity.setFileUrl(m.getValue().toString());
                    }).count();
                    fileArrayList.add(fileEntity);
                }
                matterDatumFileService.save(fileArrayList);
            }
        }

    }

    public void createSltjJson(String sltjJson, MatterEntity matterEntity) {
        if (ObjectUtils.isEmpty(sltjJson) || "{}".equals(sltjJson)) {
            return;
        }
        JSONObject root = null;
        try {
            root = JSON.parseObject(sltjJson);
        } catch (Exception e) {
            sltjJson = sltjJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(sltjJson);
            } catch (Exception e1) {
               // log.error("error json:" + sltjJson);
                return;
            }
        }

        if (root.isEmpty()) {
            //log.info("root is null");
            return;
        }

        String value = null;
        try {
            value = root.getString("受理条件");
            MatterAcceptEntity matterAcceptEntity = new MatterAcceptEntity();
            matterAcceptEntity.initAttrValue();
            matterAcceptEntity.setContent(value);
            matterAcceptEntity.setMatterId(matterEntity.getId());
            matterAcceptEntity.setMatterName(matterEntity.getMatterName());
            matterAcceptEntity.setSource(SourceEnum.政务网.getValue());
            matterAcceptEntity.setCreateTime(new Date());
            matterAcceptEntity.setCreateUser("system");
            matterAcceptService.save(matterAcceptEntity);
        } catch (Exception e) {
            log.error("error 受理条件", e);
        }
    }

    public void createSfbzJson(String sfbzJson, MatterEntity matterEntity) {
        if (ObjectUtils.isEmpty(sfbzJson) || "{}".equals(sfbzJson)) {
            return;
        }
        JSONObject root = null;
        try {
            root = JSON.parseObject(sfbzJson);
        } catch (Exception e) {
            sfbzJson = sfbzJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(sfbzJson);
            } catch (Exception e1) {
                //log.error("error json:" + sfbzJson);
                return;
            }
        }

        if (root.isEmpty()) {
            //log.info("root is null");
            return;
        }

        String value = null;
        try {
            value = root.getString("收费标准");
            MatterChargesEntity matterChargesEntity = new MatterChargesEntity();
            matterChargesEntity.initAttrValue();
            matterChargesEntity.setContent(value);
            matterChargesEntity.setMatterId(matterEntity.getId());
            matterChargesEntity.setMatterName(matterEntity.getMatterName());
            matterChargesEntity.setSource(SourceEnum.政务网.getValue());
            matterChargesEntity.setCreateTime(new Date());
            matterChargesEntity.setCreateUser("system");
            matterChargesService.save(matterChargesEntity);
        } catch (Exception e) {
            log.error("error 收费标准", e);
        }
    }

    public void createCjwtJson(String cjwtJson, MatterEntity matterEntity) {
        if (ObjectUtils.isEmpty(cjwtJson) || "{}".equals(cjwtJson)) {
            //log.info("json:" + cjwtJson);
            return;
        }
        JSONObject root = null;
        try {
            root = JSON.parseObject(cjwtJson);
        } catch (Exception e) {
            cjwtJson = cjwtJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(cjwtJson);
            } catch (Exception e1) {
                //log.error("error json:" + cjwtJson);
                return;
            }
        }

        if (root.isEmpty()) {
            //log.info("root is null");
            return;
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = root.getJSONArray("常见问题");
        } catch (Exception e) {
            //log.error("error 无常见问题");
        }

        if (ObjectUtils.isEmpty(jsonArray)) {
            //log.info("常见问题 is null");
            return;
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            List<MatterQuestionEntity> questionEntityList = jsonObject.entrySet().stream().map(question -> {
                MatterQuestionEntity questionEntity = new MatterQuestionEntity();
                questionEntity.setQuestion(question.getKey());
                questionEntity.setAnswer(question.getValue().toString());
                questionEntity.setMatterId(matterEntity.getId());
                questionEntity.setMatterName(matterEntity.getMatterName());
                questionEntity.setSource(SourceEnum.政务网.getValue());
                questionEntity.setCreateTime(new Date());
                questionEntity.setCreateUser("system");
                return questionEntity;
            }).collect(Collectors.toList());
            matterQuestionService.save(questionEntityList);
        }
    }

    public void createBllcJson(String bllcJson, MatterEntity matterEntity) {
        if (ObjectUtils.isEmpty(bllcJson) || "{}".equals(bllcJson)) {
            //log.info("json:" + cjwtJson);
            return;
        }
        JSONObject root = null;
        try {
            root = JSON.parseObject(bllcJson);
        } catch (Exception e) {
            bllcJson = bllcJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(bllcJson);
            } catch (Exception e1) {
                log.error("error json:" + bllcJson);
                return;
            }
        }

        if (root==null||root.isEmpty()) {
            //log.info("root is null");
            return;
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = root.getJSONArray("办理流程");
        } catch (Exception e) {
            log.error("error 无办理流程");
        }

        if (ObjectUtils.isEmpty(jsonArray)) {
            log.info("办理流程 is null");
            return;
        }

        List<MatterFlowlimitEntity> flowlimitEntityArrayList = new ArrayList<>();

        for (int i = 0; i < jsonArray.size(); i++) {
            MatterFlowlimitEntity matterFlowlimitEntity = new MatterFlowlimitEntity();
            matterFlowlimitEntity.setMatterId(matterEntity.getId());
            matterFlowlimitEntity.setMatterName(matterEntity.getMatterName());
            matterFlowlimitEntity.setSource(SourceEnum.政务网.getValue());
            matterFlowlimitEntity.setCreateTime(new Date());
            matterFlowlimitEntity.setCreateUser("system");
            JSONArray innerJsonArray = jsonArray.getJSONArray(i);
            for (int j = 0; j < innerJsonArray.size(); j++) {
                innerJsonArray.getJSONObject(j).entrySet().stream().peek(m -> {
                    Boolean bool = false;
                    if ("办理流程".equals(m.getKey().trim())) {
                        matterFlowlimitEntity.setFlowName(m.getValue().toString());
                        bool = true;
                    }

                    if ("办理时长".equals(m.getKey().trim())) {
                        matterFlowlimitEntity.setFlowTime(m.getValue().toString());
                        bool = true;
                    }

                    if ("转外时限".equals(m.getKey().trim())) {
                        matterFlowlimitEntity.setFlowLimit(m.getValue().toString());
                        bool = true;
                    }

                    if ("办理流程说明".equals(m.getKey().trim())) {
                        matterFlowlimitEntity.setFlowDesc(m.getValue().toString());
                        bool = true;
                    }

//                    if(!bool){
//                        System.out.println("name:" + m.getKey());
//                        System.out.print(" value:" + m.getValue());
//                    }
                }).count();
            }
            flowlimitEntityArrayList.add(matterFlowlimitEntity);
        }
        matterFlowlimitService.save(flowlimitEntityArrayList);

    }

    public void createSdyjJson(String sdyjJson, MatterEntity matterEntity) {
        if (ObjectUtils.isEmpty(sdyjJson) || "{}".equals(sdyjJson)) {
            //log.info("json:" + cjwtJson);
            return;
        }
        JSONObject root = null;
        try {
            root = JSON.parseObject(sdyjJson);
        } catch (Exception e) {
            sdyjJson = sdyjJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(sdyjJson);
            } catch (Exception e1) {
                log.error("error json:" + sdyjJson);
                return;
            }
        }

        if (root.isEmpty()) {
            log.info("root is null");
            return;
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = root.getJSONArray("设定依据");
        } catch (Exception e) {
            log.error("error 无设定依据");
        }

        if (ObjectUtils.isEmpty(jsonArray)) {
            log.info("设定依据 is null");
            return;
        }

        List<MatterSetbaseEntity> setbaseEntityArrayList = new ArrayList<>();

        for (int i = 0; i < jsonArray.size(); i++) {
            MatterSetbaseEntity matterSetbaseEntity = new MatterSetbaseEntity();
            matterSetbaseEntity.setMatterId(matterEntity.getId());
            matterSetbaseEntity.setMatterName(matterEntity.getMatterName());
            matterSetbaseEntity.setSource(SourceEnum.政务网.getValue());
            matterSetbaseEntity.setCreateTime(new Date());
            matterSetbaseEntity.setCreateUser("system");
            JSONArray innerJsonArray = jsonArray.getJSONArray(i);
            for (int j = 0; j < innerJsonArray.size(); j++) {
                innerJsonArray.getJSONObject(j).entrySet().stream().peek(m -> {
                    if ("法律法规名称".equals(m.getKey().trim())) {
                        matterSetbaseEntity.setPolicyName(m.getValue().toString());
                    }
                    if ("法规类型".equals(m.getKey().trim())) {
                        matterSetbaseEntity.setPolicyType(m.getValue().toString());
                    }

                    if ("条例".equals(m.getKey().trim())) {
                        matterSetbaseEntity.setPolicyitem(m.getValue().toString());
                    }

                    if ("条款内容".equals(m.getKey().trim())) {
                        matterSetbaseEntity.setContent(m.getValue().toString());
                    }

                }).count();
            }
            setbaseEntityArrayList.add(matterSetbaseEntity);
        }
        matterSetbaseService.save(setbaseEntityArrayList);

    }

    public void createZjfwJson(String zjfwJson, MatterEntity matterEntity) {
        if (ObjectUtils.isEmpty(zjfwJson) || "{}".equals(zjfwJson)) {
            return;
        }
        JSONObject root = null;
        try {
            root = JSON.parseObject(zjfwJson);
        } catch (Exception e) {
            zjfwJson = zjfwJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(zjfwJson);
            } catch (Exception e1) {
                log.error("error json:" + zjfwJson);
                return;
            }
        }

        if (root.isEmpty()) {
            log.info("root is null");
            return;
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = root.getJSONArray("中介服务");
        } catch (Exception e) {
            log.error("error 中介服务");
        }

        if (ObjectUtils.isEmpty(jsonArray)) {
            log.info("中介服务 is null");
            return;
        }

        List<MatterIntermediaryEntity> intermediaryEntityArrayList = new ArrayList<>();



        for (int i = 0; i < jsonArray.size(); i++) {
            MatterIntermediaryEntity matterIntermediaryEntity = new MatterIntermediaryEntity();
            matterIntermediaryEntity.setMatterId(matterEntity.getId());
            matterIntermediaryEntity.setMatterName(matterEntity.getMatterName());
            matterIntermediaryEntity.setSource(SourceEnum.政务网.getValue());
            matterIntermediaryEntity.setCreateTime(new Date());
            matterIntermediaryEntity.setCreateUser("system");
            jsonArray.getJSONObject(i).entrySet().stream().peek(m -> {
                    if ("中介服务事项名称".equals(m.getKey().trim())) {
                        matterIntermediaryEntity.setTitle(m.getValue().toString());
                    }
                    if ("中介服务实施机构及资质资格要求".equals(m.getKey().trim())) {
                        matterIntermediaryEntity.setIntermediaryRequest(m.getValue().toString());
                    }

                    if ("服务时限".equals(m.getKey().trim())) {
                        matterIntermediaryEntity.setIntermediaryRequestTime(m.getValue().toString());
                    }

                    if ("备注".equals(m.getKey().trim())) {
                        matterIntermediaryEntity.setRemark(m.getValue().toString());
                    }

                }).count();

            intermediaryEntityArrayList.add(matterIntermediaryEntity);
        }
        matterIntermediaryService.save(intermediaryEntityArrayList);

    }

    @Override
    public Map<String, String> getBaseInfoMap(Context context) {
        Map<String, String> baseInfoMap = new HashMap<>();
        List<MattersDetailEntity> mattersDetailEntities = mattersDetailService.find(new MattersDetailQuery());
        for (MattersDetailEntity itemDetail : mattersDetailEntities) {
            buildBaseJson(itemDetail.getBasicinfoJbxx(), baseInfoMap);
        }
        return baseInfoMap;
    }

    @Override
    public Map<String, String> getSqclInfoMap(Context context) {
        Map<String, String> sqclInfoMap = new HashMap<>();
        List<MattersDetailEntity> mattersDetailEntities = mattersDetailService.find(new MattersDetailQuery());
        for (MattersDetailEntity itemDetail : mattersDetailEntities) {
            buildSqclJson(itemDetail.getMaterialsSqcl(), sqclInfoMap);
        }
        return sqclInfoMap;
    }


    public void buildBaseJson(String json, Map<String, String> model) {
        //将基本信息转成map集合返回
        JSONObject root = JSON.parseObject(json);
        JSONArray jsonArray = root.getJSONArray("基本信息");
        if (!ObjectUtils.isEmpty(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray subArray = jsonArray.getJSONArray(i);
                if (!ObjectUtils.isEmpty(subArray)) {
                    for (int j = 0; j < subArray.size(); j++) {
                        subArray.getJSONObject(j).entrySet().stream()
                                .filter(f -> f.getKey().length() < 12)
                                .filter(f -> f.getKey().indexOf("许可证") == -1)
                                .filter(f -> f.getKey().indexOf("《") == -1)
                                .filter(f -> f.getKey().indexOf("x") == -1)
                                .filter(f -> f.getKey().indexOf("X") == -1)
                                .filter(f -> f.getKey().indexOf("*") == -1)
                                .filter(f -> f.getKey().indexOf("关于") == -1)
                                .filter(f -> f.getKey().indexOf(".") == -1)
                                .filter(f -> DataUtil.converStr2Int(f.getKey(), 0) == 0)
                                .filter(f -> !"下载".equals(f.getValue().toString().trim()))
                                .filter(f -> !"查看".equals(f.getValue().toString().trim()))
                                .peek(m -> {
                                    // model.put(m.getKey(), m.getValue().toString());
                                    model.put(m.getKey(), "");
                                }).count();
                    }
                }
            }

        }
    }


    public void buildSqclJson(String sqclJson, Map<String, String> model) {
        //将基本信息转成map集合返回
        JSONObject root = null;
        try {
            root = JSON.parseObject(sqclJson);
        } catch (Exception e) {
            sqclJson = sqclJson.replaceAll("\\\\", "\\\\\\\\");
            try {
                root = JSON.parseObject(sqclJson);
            } catch (Exception e1) {
                log.error("error json:" + sqclJson);
                return;
            }
        }

        if (root.isEmpty()) {
            log.info("root is null");
            return;
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = root.getJSONArray("申请材料");
        } catch (Exception e) {
            log.error("error 无申请材料");
        }

        if (ObjectUtils.isEmpty(jsonArray)) {
            log.info("申请材料 is null");
            return;
        }
        if (!ObjectUtils.isEmpty(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                try {
                    JSONObject subObject = jsonArray.getJSONObject(i);
                    if (!ObjectUtils.isEmpty(subObject)) {
                        JSONArray subsArray = subObject.getJSONArray("材料详情");
                        if (!ObjectUtils.isEmpty(subsArray)) {
                            for (int j = 0; j < subsArray.size(); j++) {
                                subsArray.getJSONObject(j).entrySet().stream()
                                        .peek(m -> {
                                            if ("要求提供材料的依据".equals(m.getKey())
                                                    || "备注".equals(m.getKey())
                                                    || "来源渠道说明".equals(m.getKey())
                                                    || "材料名称".equals(m.getKey())
                                                    || "受理标准".equals(m.getKey())
                                                    || "填报须知".equals(m.getKey())
                                                    || "来源渠道".equals(m.getKey())) {
                                                model.put(m.getKey(), "");
                                            } else {
                                                if (model.containsKey(m.getKey())) {
                                                    String value = model.get(m.getKey());
                                                    Set<String> valueSet = Arrays.asList(value.split(",")).stream().collect(Collectors.toSet());
                                                    if (!valueSet.contains(m.getValue().toString())) {
                                                        valueSet.add(m.getValue().toString());
                                                    }
                                                    model.put(m.getKey(), valueSet.stream().collect(Collectors.joining(",")));
                                                } else {
                                                    model.put(m.getKey(), m.getValue().toString());
                                                }
                                            }
                                            //log.info(String.format("model:%s", JSON.toJSONString(model)));
                                            // model.put(m.getKey(), m.getValue().toString());
                                            //model.put(m.getKey(), "");
                                        }).count();
                            }
                        }

                    }


                } catch (Exception e) {
                    log.error("异常:" + sqclJson);
                }
            }

        }
    }

}