package com.scpyun.platform.jilinsscgsdp.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.platform.jilinsscgsdp.bean.vo.ReqEventAttachInsertVo;
import com.scpyun.platform.jilinsscgsdp.constant.NotesConstant;
import com.scpyun.platform.jilinsscgsdp.constant.NumberConstant;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.base.utils.UUIDUtil;
import com.scpyun.platform.jilinsscgsdp.constant.Constant;

import javax.validation.Valid;

@Api(value = "APP公告")
@Service("noticeService")
@Slf4j
public class NoticeServiceImpl {

    @Autowired
    private CommonService commonService;

    private final  String nameSpace="com.scpyun.platform.standard.jilinsscgsdp.sys.";
    
    @ApiOperation(value = "新增")
    public String insertData(Map<String,Object> map) {
        String uuid=UUIDUtil.getUUID();
		map.put("uuid", uuid);
		map.put("context", HtmlUtils.htmlEscapeHex((String) map.get("context")));
        if(map.get("urlList")!=null && JSONArray.parseArray(map.get("urlList").toString()).size()>0){
            List<Map<String,Object>> urlList = (List<Map<String, Object>>) map.get("urlList");
            for (Map<String, Object> item : urlList) {
                item.put("notice_id",uuid);
                commonService.insert(Constant.NAMESPACE_NOTICE + "insertNoticeAttach", item);
            }
        }
        map.put("json", JSON.toJSONString(map.get("areaList"), SerializerFeature.PrettyFormat));
        List<Map<String,Object>> areaList = (List<Map<String, Object>>) map.get("areaList");
        // 1. 创建一个临时列表，用于存放所有需要新增的元素
        List<HashMap<String, Object>> newAreaIterms = new ArrayList<>();
        commonService.delete(Constant.NAMESPACE_NOTICE +"deleteNoticeArea",map);
// 2. 遍历原始的 areaList
        areaList.forEach(v -> {
            v.put("noticeId", uuid);
            String isAll = String.valueOf(v.get("isAll"));
            switch (isAll) {
                case "0":
                    v.put("areaId", v.get("id"));
                    String isValue = String.valueOf(v.get("isValue"));
                    if (isValue.equals("1")) {
                        List<HashMap<String, Object>> ret = commonService.findList(nameSpace + "findOffieNode", v.get("id"));
                        ret.forEach(m -> {
                            m.put("noticeId", uuid);
                            m.put("officeId", m.get("id"));
                            m.put("userId", map.get("userId"));
                            m.put("parentIds", m.get("parentIds"));
                            m.put("isAll", 1);
                            m.put("isValue", 0);
                            m.put("type", v.get("type"));

                            // 3. 将新元素添加到临时列表中，而不是原始列表
                            newAreaIterms.add(m);
                        });
                    }
                    break;
                case "1":
                    v.put("officeId", v.get("id"));
                    break;
                default:
                    throw new CustomException("参数异常");
            }
        });

// 4. 循环结束后，将临时列表中的所有元素一次性添加到原始的 areaList
        if (!newAreaIterms.isEmpty()) {
            areaList.addAll(newAreaIterms);
        }
        commonService.insertBatch(Constant.NAMESPACE_NOTICE+"insertNoticeArea",areaList);
        int insert = commonService.insert(Constant.NAMESPACE_NOTICE + "insertData", map);
        return insert > 0 ? "操作成功" : "操作失败";
    }

    @ApiOperation(value = "删除")
    public String updateDelData(Map<String,Object> map) {
        commonService.delete(Constant.NAMESPACE_NOTICE +"deleteNoticeArea",map);
        int delete = commonService.delete(Constant.NAMESPACE_NOTICE + "removeData", map);
        return delete > 0 ? "操作成功" : "操作失败";
    }

    @ApiOperation(value = "更新")
    public String updateData(Map<String,Object> map) {
    	int update = 0;
		if(map.get("context") != null) {
			map.put("context", HtmlUtils.htmlEscapeHex((String) map.get("context")));
		}
		if(map.get("publish_status")==null) {
			map.put("publish_status","0");
		}
        map.put("json", JSON.toJSONString(map.get("areaList"), SerializerFeature.PrettyFormat));
		update = commonService.update(Constant.NAMESPACE_NOTICE + "updateData", map);
        // 先清除附件
        commonService.update(Constant.NAMESPACE_NOTICE +"clearNoticeAttach",map);
        if(map.get("urlList")!=null && JSONArray.parseArray(map.get("urlList").toString()).size()>0){
            List<Map<String,Object>> urlList = (List<Map<String, Object>>) map.get("urlList");
            for (Map<String, Object> item : urlList) {
                item.put("notice_id",map.get("id"));
                commonService.insert(Constant.NAMESPACE_NOTICE + "insertNoticeAttach", item);
            }
        }
        commonService.delete(Constant.NAMESPACE_NOTICE +"deleteNoticeArea",map);
        List<Map<String,Object>> areaList = (List<Map<String, Object>>) map.get("areaList");
        // 1. 创建一个临时列表，用于存放所有需要新增的元素
        List<HashMap<String, Object>> newAreaIterms = new ArrayList<>();

// 2. 遍历原始的 areaList
        areaList.forEach(v -> {
            v.put("noticeId", map.get("id"));
            String isAll = String.valueOf(v.get("isAll"));
            switch (isAll) {
                case "0":
                    v.put("areaId", v.get("id"));
                    String isValue = String.valueOf(v.get("isValue"));
                    if (isValue.equals("1")) {
                        List<HashMap<String, Object>> ret = commonService.findList(nameSpace + "findOffieNode", v.get("id"));
                        ret.forEach(m -> {
                            m.put("noticeId", map.get("id"));
                            m.put("officeId", m.get("id"));
                            m.put("userId", map.get("userId"));
                            m.put("parentIds", m.get("parentIds"));
                            m.put("isAll", 1);
                            m.put("isValue", 0);
                            m.put("type", v.get("type"));

                            // 3. 将新元素添加到临时列表中，而不是原始列表
                            newAreaIterms.add(m);
                        });
                    }
                    break;
                case "1":
                    v.put("officeId", v.get("id"));
                    break;
                default:
                    throw new CustomException("参数异常");
            }
        });

// 4. 循环结束后，将临时列表中的所有元素一次性添加到原始的 areaList
        if (!newAreaIterms.isEmpty()) {
            areaList.addAll(newAreaIterms);
        }
        commonService.insertBatch(Constant.NAMESPACE_NOTICE+"insertNoticeArea",areaList);
        return update > 0 ? "操作成功" : "操作失败";
    }

    @ApiOperation(value = "查询详情")
    public Map<String, Object> getObject(Map<String,Object> map) {
    	Map<String, Object> obj = commonService.getObject(Constant.NAMESPACE_NOTICE + "getObject", map);
//        List<Map<String, Object>> areaList = commonService.findList(Constant.NAMESPACE_NOTICE + "getOffieObject", map);
//        log.error(JSONUtil.toJsonStr(areaList));
//        areaList.forEach(v->{
//            String isAll = String.valueOf(v.get("isAll"));
//            switch (isAll){
//                case "0":
//                    v.put("id",v.get("areaId"));
//                    break;
//                case "1":
//                    v.put("id",v.get("officeId"));
//                    break;
//                default:
//                    throw new CustomException("参数异常");
//
//            }
//        });
    	obj.put("context", HtmlUtils.htmlUnescape((String) obj.get("context")));
//    	obj.put("areaList",areaList);
        return obj;
    }

    @ApiOperation(value = "查询分页列表")
    public Page<Map<String, Object>> selectListPage(Page<Map<String, Object>> mapPage) {
        Integer flag = (Integer)mapPage.getParams().get("flag");
        Page<Map<String, Object>> ret = new Page<Map<String, Object>>();
        if (flag.equals(1)) {
            String parentIds = String.valueOf(mapPage.getParams().get("parent_ids"));
            if (StringUtils.isNotEmpty(parentIds)) {
                String companyGrade = String.valueOf(mapPage.getParams().get("company_grade"));
                String[] parentIdArray = parentIds.split(",");
                switch (companyGrade){
                    case "0":
                        break;
                    case "1":
                        break;
                    case "2":
                        break;
                    case "3":
                        break;
                    case "4":
                        mapPage.getParams().put("cityId", parentIdArray[2]);
                        break;
                    case "5":
                        mapPage.getParams().put("cityId", parentIdArray[2]);
                        mapPage.getParams().put("areaId", parentIdArray[3]);
                        break;
                    case "6":
                        mapPage.getParams().put("cityId", parentIdArray[2]);
                        mapPage.getParams().put("areaId", parentIdArray[3]);
                        mapPage.getParams().put("streetId", parentIdArray[4]);
                        break;
                    case"7":
                        mapPage.getParams().put("cityId", parentIdArray[2]);
                        mapPage.getParams().put("areaId", parentIdArray[3]);
                        mapPage.getParams().put("streetId", parentIdArray[4]);
                        break;
                    default:
                        throw new CustomException("当前层级问题");
                }
            }
            String officeId = commonService.getObject(nameSpace+"findOfficeId",mapPage.getParams().get("userId"));
            if (StringUtils.isNotEmpty(officeId)) {
                mapPage.getParams().put("officeId",officeId);
            }
            ret=commonService.findPage(Constant.NAMESPACE_NOTICE + "selectListPage", mapPage);
        }else {
            ret=commonService.findPage(Constant.NAMESPACE_NOTICE + "selectOneListPage", mapPage);
        }

    	List<Map<String, Object>> result = ret.getResults();
    	if(result.size() > 0) {
    		for (Map<String, Object> map : result) {
    			map.put("context", HtmlUtils.htmlUnescape((String) map.get("context")));
    		}
    	}
        return ret;
    }
    
    @ApiOperation(value = "查询列表")
    public List<Map<String, Object>> selectList(Map<String,Object> map) {
    	List<Map<String, Object>> ret = new ArrayList<>();
    	ret = commonService.findList(Constant.NAMESPACE_NOTICE + "selectList", map);
    	ret.stream().forEach(m->{
    		if(m.get("context") != null) {
    			m.put("context", HtmlUtils.htmlEscapeHex((String) m.get("context")));
    		}
    	});
        return ret;
    }

    @ApiOperation(value = "区域化树",nologin = true)
    public List<Map<String, Object>> findNodes(Map<String,Object> map) {
        List<Map<String, Object>> ret = new ArrayList<>();
        String isValue = String.valueOf(map.get("isValue"));
        switch (isValue){
            case "0":
                ret = commonService.findList(nameSpace + "findAreaNode", map.get("id"));
                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                String level = String.valueOf(map.get("type"));
                switch (level) {
                    case "1":
                        break;
                    case "2":
                        objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("name", "省本级");
                        objectObjectHashMap.put("id", map.get("id"));
                        objectObjectHashMap.put("type", 1);
                        objectObjectHashMap.put("isAll", "0");
                        objectObjectHashMap.put("isValue","1");
                        objectObjectHashMap.put("parentIds",map.get("parentIds"));
                        ret.add(0, objectObjectHashMap);
                        break;
                    case "3":
                        objectObjectHashMap.put("name", "市本级");
                        objectObjectHashMap.put("id", map.get("id"));
                        objectObjectHashMap.put("type", 2);
                        objectObjectHashMap.put("isAll", "0");
                        objectObjectHashMap.put("isValue","1");
                        objectObjectHashMap.put("parentIds",map.get("parentIds"));
                        ret.add(0, objectObjectHashMap);
                        break;
                    case "4":
                        objectObjectHashMap.put("name", "区本级");
                        objectObjectHashMap.put("id", map.get("id"));
                        objectObjectHashMap.put("type", 3);
                        objectObjectHashMap.put("isAll", "0");
                        objectObjectHashMap.put("isValue","1");
                        objectObjectHashMap.put("parentIds",map.get("parentIds"));
                        ret.add(0, objectObjectHashMap);
                        break;
                    case "5":
                        objectObjectHashMap.put("name", "街道本级");
                        objectObjectHashMap.put("id", map.get("id"));
                        objectObjectHashMap.put("type", 4);
                        objectObjectHashMap.put("isAll", "0");
                        objectObjectHashMap.put("isValue","1");
                        objectObjectHashMap.put("parentIds",map.get("parentIds"));
                        ret.add(0, objectObjectHashMap);
                        break;
                    case "6":
                        objectObjectHashMap.put("name", "社区本级");
                        objectObjectHashMap.put("id", map.get("id"));
                        objectObjectHashMap.put("type", 5);
                        objectObjectHashMap.put("isAll", "0");
                        objectObjectHashMap.put("isValue","1");
                        objectObjectHashMap.put("parentIds",map.get("parentIds"));
                        ret.add(0, objectObjectHashMap);
                        break;
                    default:
                        throw new CustomException("参数异常");

                }
                break;
            case "1":
                ret = commonService.findList(nameSpace + "findOffieNode", map.get("id"));
                break;
            default:
                throw new CustomException("参数异常");
        }
        return ret;
    }
    @ApiOperation(value = "发布等接口",nologin = true)
    public String updateStatus(HashMap<String,String> map){
        commonService.update(Constant.NAMESPACE_NOTICE + "updateData", map);
        return "修改成功";
    }


    @ApiOperation(value = "发布等接口",nologin = true)
    public String logDemo(HashMap<String,String> map){
        log.info("我是测试info");
        log.debug("我是测试debug");
        log.warn("我是测试warn");
        log.error("我是测试error");
        Object demo = null;
        log.info(demo.toString());
        return "修改成功";
    }
}
