package com.tofly.watermeter.custom.service.websb.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.tofly.common.core.util.StringUtil;
import com.tofly.watermeter.custom.entity.webserverbean.*;
import com.tofly.watermeter.custom.service.websb.WebSBservice;
import com.tofly.watermeter.custom.util.NullAwareBeanUtilsBean;
import com.tofly.watermeter.custom.vo.QfkhjbxxMeiCunVO;
import com.tofly.watermeter.entity.Qfkhjbxx;
import com.tofly.watermeter.mapper.QfkhjbxxMapper;
import com.tofly.watermeter.util.CallAPIUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author FlashWJL
 * @date 2021/5/28 11:11
 */
@Service
@Slf4j
@AllArgsConstructor
public class WebSBserviceImpl implements WebSBservice {

    @Override
    public List<Qfkhjbxx> getKH(KhInfo khInfo) {
        try {
            Map map = CallAPIUtil.callAPIUtil(khInfo, "api/Business/GetCustomerData");
            if (StringUtil.isNotNull(map)) {
                Object info = map.get("data");
                log.info("获取同步原数据为：" + info.toString());
                List<Qfkhjbxx> mapList = JSONObject.parseArray(JSONObject.toJSONString(info), Qfkhjbxx.class);
                if (StringUtil.isNotNull(mapList) && mapList.size() > 0) {
                    log.info("获取同步数据转换为：" + mapList.toString());
                    return mapList;
                }
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Qfkhjbxx> getUpdateAndInsert(CustomerAddorUpdate customerAddorUpdate) {
        try {
            Map map = CallAPIUtil.callAPIUtil(customerAddorUpdate, "api/Business/CustomerAddorUpdate");
            if (StringUtil.isNotNull(map)) {
                Object info = map.get("data");
                List<Qfkhjbxx> mapList = JSONObject.parseArray(JSONObject.toJSONString(info), Qfkhjbxx.class);
                if (StringUtil.isNotNull(mapList) && mapList.size() > 0) {
                    return mapList;
                }
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<ReadAreas> getReadAreas(CbParamInfo cbParamInfo) {
        try {
            Object info = CallAPIUtil.callAPIUtil(cbParamInfo, IpAddress.ReadAndAreas.getIpAddress()).get("data");
            if (StringUtil.isNotNull(info)) {
                List<ReadAreas> mapList = JSONObject.parseArray(JSONObject.toJSONString(info), ReadAreas.class);
                if (StringUtil.isNotNull(mapList) && mapList.size() > 0) {
                    return mapList;
                }
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map newInstall(NewInstall newInstall) {
        try {
            Map map = CallAPIUtil.callAPIUtil(newInstall, "api/Business/newWater");
            return map;
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map exchangeSB(ExchangeSB exchangeSB) {
        try {
            Map map = CallAPIUtil.callAPIUtil(exchangeSB, "api/Business/WaterReplace");
            return map;
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }


    private Map requestUpdateAndInsert(Integer pageNum, Integer pageSize) {
        Map requestMap = new HashMap();
        requestMap.put("PAGE_NUM", pageNum);
        requestMap.put("PAGE_SIZE", pageSize);
        try {
            Map map = CallAPIUtil.callAPIUtil(requestMap, "/api/Business/CustomerAddorUpdate");
            return map;
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

    private final QfkhjbxxMapper qfkhjbxxMapper;

    @Override
    public QfkhjbxxMeiCunVO getUpdateAndInsertMeiCun(Integer pageNum, Integer pageSize) {
        Map requestMap = requestUpdateAndInsert(pageNum, pageSize);
        if (StringUtil.isNotNull(requestMap)) {
            String jsonData = new Gson().toJson(requestMap.get("data"));
            log.error("当前请求第{}页", pageNum);
            Map<String, Object> dataMap = new Gson().fromJson(jsonData, Map.class);
            Integer pages = (int) Double.parseDouble(dataMap.get("pages").toString());
            boolean hasNextPage = (boolean) dataMap.get("hasNextPage");
            Integer nextPage = (int) Double.parseDouble(dataMap.get("nextPage").toString());

            //解析json并插入到数据库中去
            Object info = dataMap.get("list");
            List<Qfkhjbxx> mapList = JSONObject.parseArray(JSONObject.toJSONString(info), Qfkhjbxx.class);
            NullAwareBeanUtilsBean nullAwareBeanUtilsBean = new NullAwareBeanUtilsBean();

            for (Qfkhjbxx index : mapList) {
                try {
                    Qfkhjbxx existIndex = qfkhjbxxMapper.getKhInfoByJbbh(index.getYhbh());
                    if (existIndex == null) {
                        qfkhjbxxMapper.insert(index);
                    } else {
                        nullAwareBeanUtilsBean.copyProperties(index, existIndex);
                        qfkhjbxxMapper.updateById(existIndex);
                    }
                } catch ( Exception exception ) {
                    log.error("数据库操作错误={}", exception.getMessage());
                }
            }

            log.info("一共{}页,下一页={}", pages, nextPage);
            if (hasNextPage) {
                getUpdateAndInsertMeiCun(nextPage, pageSize);
            }
        }
        return null;
    }
}
