package com.JN.demo.bizquery.controller;

import com.JN.API.qichacha.QccApiUntils;
import com.JN.common.R;
import com.JN.demo.bizquery.entity.QccInfo;
import com.JN.demo.bizquery.service.QccInfoService;
import com.JN.utils.HttpHelper;
import com.JN.utils.JSONHelper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpHead;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName BizQccController
 * @Description 业务查询中的企查查的接受请求控制类
 * @Author JN
 * @Date 2024/1/11 9:46
 * @Version 1.0
 */

@RestController
@Slf4j
@RequestMapping("/qcc")
@PropertySource("classpath:/file.properties")
public class BizQccController {

    @Autowired
    private QccInfoService qccInfoService;
    @Value("${Qcc_Key}")
    private String Qcc_Key;
    // 接口请求Key
    @Value("${Qcc_SecretKey}")
    private String Qcc_SecretKey;

    @Value("${Qcc_Url}")
    private String Qcc_Url;

    @PostMapping
    public R<Map<String, String>> queryCompanyInfo(@RequestParam("name") String name) throws JSONException {
        //创建数据库查询
        LambdaQueryWrapper<QccInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QccInfo::getName, name);
        QccInfo qccInfo = qccInfoService.getOne(queryWrapper);

        if(qccInfo == null || isExpiredOneMonth(qccInfo.getUpdateTime())) {
            String paramStr = "searchKey=";
            String status = "";
            // 判断 name 是否为空，避免拼接出现异常,将传入的
            if (name != null && !name.isEmpty()) {
                // 拼接参数字符串
                paramStr += name;
            }
            try{
                HttpHead reqHeader = new HttpHead();
                String[] autherHeader = QccApiUntils.RandomAuthentHeader(Qcc_Key, Qcc_SecretKey);
                reqHeader.setHeader("Token", autherHeader[0]);
                reqHeader.setHeader("Timespan", autherHeader[1]);
                log.info("Request query headers： {}", reqHeader);

                final String reqUri = Qcc_Url.concat("?key=").concat(Qcc_Key).concat("&").concat(paramStr);
                String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
                log.info("tokenJson: {}", tokenJson);

                //创建新增的qccInfo类用来插入数据
                QccInfo qccInfoSave = new QccInfo();
                qccInfoSave.setQccJson(tokenJson);

                if(qccInfo == null) {
                    qccInfoSave.setName(name);
                    qccInfoService.save(qccInfoSave);
                } else {
                    LambdaUpdateWrapper<QccInfo> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(QccInfo::getName, name);
                    qccInfoService.update(qccInfoSave, updateWrapper);
                }

                return R.success(insuredCountMap(tokenJson));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } else {
            return R.success(insuredCountMap(qccInfo.getQccJson()));
        }
        return null;
    }

    /**
     * @title isExpiredOneMonth
     * @description 判断传入的日期是否过期一个月
     * @author JN
     * @param: updateTime
     * @updateTime 2024/1/12 10:20
     * @return: boolean
     */
    public boolean isExpiredOneMonth(LocalDateTime updateTime) {
        LocalDateTime oneMonthLater = updateTime.plus(1, ChronoUnit.MONTHS);
        LocalDateTime now = LocalDateTime.now();

        return now.isAfter(oneMonthLater);
    }

    /**
     * @title resultMap
     * @description 传入tokenJson，返回需要返回给前端的Map
     * @author JN
     * @param: tokenJson
     * @updateTime 2024/1/12 10:52
     * @return: java.util.Map<java.lang.String,java.lang.String>
     */
    public Map<String, String> insuredCountMap(String tokenJson) throws JSONException {
        String result = JSONHelper.formartJson(tokenJson, "Result");
        String data = JSONHelper.formartJson(result, "Data");
        String insuredCount = JSONHelper.formartJson(data, "InsuredCount");

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("insuredCount", insuredCount);

        return resultMap;
    }

}
