package com.casic.missiles.controller;

import com.alibaba.fastjson.JSON;
import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.common.service.IExpandComponentService;
import com.casic.missiles.core.util.DateUtil;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.invoke.sync.ReceiveParamsBean;
import com.casic.missiles.modular.sync.service.ISyncDataService;
import com.casic.missiles.modular.system.model.User;
import com.casic.missiles.modular.system.model.UserSync;
import com.casic.missiles.modular.system.service.IUserDeviceService;
import com.casic.missiles.modular.system.service.IUserService;
import com.casic.missiles.modular.system.service.IUserSyncService;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/sys")
public class ReceiveSyncDataController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ReceiveSyncDataController.class);
    @Autowired
    private ISyncDataService syncDataService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IUserService service;

    @RequestMapping(value = "/test")
    public void test(HttpServletRequest request,String keys, String date, HttpServletResponse response) {
        List<String> keyArrays = Arrays.asList(keys.split(","));
        try {
            keyArrays.forEach(key -> {
                    //key 转日期
                    String keyStr = String.valueOf(key);
                    logger.info(String.valueOf(key));
                    if (keyStr.startsWith("syncInit")) {
                        Date keyDate = new Date(Long.valueOf(keyStr.replaceAll("syncInit", "")));
                        String keyDateStr = DateUtil.format(keyDate, "yyyy-MM-dd");
                        logger.info("同步日期:{}", keyDateStr);
                        if (date.equals(keyDateStr)) {
                            List<UserSync> personOrDeviceList = (List<UserSync>) redisTemplate.opsForValue().get(key);
                            personOrDeviceList.forEach(person -> {
                                User user = service.getByAccount(person.getIdentityCard());
                                if (ToolUtil.isEmpty(user)) {
                                    logger.info("该用户数据不存在:{}", JSON.toJSONString(person));
                                }
                            });
                        }
                    }
                });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/receiveSyncData")
    public void receiveSyncData(HttpServletRequest request, HttpServletResponse response) {
        String redisKey = "";
        try {
            request.setCharacterEncoding("UTF-8");
            String dcod = null;
            InputStream i = request.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(i));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            dcod = buffer.toString();
            /***这里是业务逻辑处理***/

            OutputStream ooo = response.getOutputStream();
            Map<String, Object> map = new HashMap<String, Object>();
            String result = "fail";

            if (dcod != null && dcod != "") {
                logger.info("基础数据接收数据:{}", dcod);
                //如果成功  必须返回“”success“”字符串，其余返回标识基础库不予以确认。
                ReceiveParamsBean requestBaseBean = JSON.parseObject(dcod, ReceiveParamsBean.class);
                redisKey = "syncInit" + System.currentTimeMillis();
                //接收同步数据保存至redis
                redisTemplate.opsForValue().set(redisKey, requestBaseBean.getPersonOrDeviceList(), 30, TimeUnit.DAYS);

                try {
                    map.put("result", "success");
                    ooo.write(JSON.toJSONString(map).getBytes());
                    ooo.flush();
                    ooo.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    logger.error("返回处理结果异常", e1);
                    return;
                }

                List<UserSync> objs = (List<UserSync>) redisTemplate.opsForValue().get("test");
                System.out.println("数据" + JSON.toJSONString(objs));
                switch (requestBaseBean.getDataType()) {
                    case "3"://人员设备增量推送数据
                    case "4"://组织机构增量推送数据
                        syncDataService.processIncreData(requestBaseBean);
                        break;
                    case "1":
                        //初始化数据推送或者强制推送(接收数据存库 并返回)
                        syncDataService.saveSyncData(requestBaseBean);
                        try {
                            syncDataService.processIncreData(requestBaseBean);
                        } catch (Exception e) {
                            logger.error("推送数据失败", e);
                        }
                        return;
                }

                //解析基础数据其他
                result = "success";
            }
            map.put("result", result);
            result = JSON.toJSONString(map);
            //返回相应信息
            ooo.write(result.getBytes());
            ooo.flush();
            ooo.close();
            return;

        } catch (Exception e) {
            logger.error(redisKey + "推送数据异常:", e);
            try {
                OutputStream ooo = response.getOutputStream();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("result", "fail");
                ooo.write(JSON.toJSONString(map).getBytes());
                ooo.flush();
                ooo.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
        return;
    }
}
