package com.ruoyi.web.controller.grid;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.qcc.EsearchJsonRecord;
import com.ruoyi.system.domain.qcc.EsearchLog;
import com.ruoyi.system.domain.qcc.EsearchRecord;
import com.ruoyi.system.domain.qcc.enums.EsearchTypeEnum;
import com.ruoyi.system.domain.qcc.enums.EsearchWayEnum;
import com.ruoyi.system.domain.qcc.ext.EsearchRecordExt;
import com.ruoyi.system.domain.qcc.ext.EsearchResult;
import com.ruoyi.system.domain.qcc.factory.EsearchFactory;
import com.ruoyi.system.domain.qcc.util.FinalCostHttpHelper;
import com.ruoyi.system.service.grid.qcc.impl.EsearchJsonRecordService;
import com.ruoyi.system.service.grid.qcc.impl.EsearchLogService;
import com.ruoyi.system.service.grid.qcc.impl.EsearchRecordService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 企查查 查公司详情
 * * Author: brenda
 * * 2024/9/3
 **/
@Api(tags = "企业管理-一企一档")
@RestController
@RequestMapping("/api/grid/company/qcc")
public class CompanyQccController {

    @Autowired
    private EsearchJsonRecordService esearchJsonRecordService;

    @Autowired
    private EsearchFactory searchFactory;

    @Autowired
    private EsearchLogService logService;

    @Autowired
    private EsearchRecordService recordService;

    @Value("${app.qcc.appKey}")
    private String appKey;

    @Value("${app.qcc.secKey}")
    private String secKey;

    //名称模糊搜索
    @Value("${app.qcc.searchName}")
    private String searchName;

    //根据公司完整名称 查询详细信息 搜索关键字（公司名、注册号、统一社会信用代码或KeyNo）
    @Value("${app.qcc.searchInfo}")
    private String searchInfo;

    //据公司完整名称查询纳税人识别号&开户行
    @Value("${app.qcc.searchCode}")
    private String searchCode;

    @GetMapping("getQccCompanyInfo")
    public AjaxResult getQccCompanyInfo(@RequestParam("keyword")String keyword){
        if(StringUtils.isBlank(keyword)){
            throw new ServiceException("参数错误");
        }
        //本地数据已存在
        EsearchJsonRecord existRecord = esearchJsonRecordService.getOne(new LambdaQueryWrapper<EsearchJsonRecord>().eq(EsearchJsonRecord::getCreditCode, keyword));
        if(existRecord != null){
            EsearchRecordExt esearchRecordExt = new EsearchRecordExt();
            BeanUtils.copyProperties(existRecord, esearchRecordExt);
            setOriginalNameStr(esearchRecordExt);
            return AjaxResult.success(esearchRecordExt);
        }
        String paramStr = "keyword=" + keyword;
        String reqUri = searchInfo.concat("?key=").concat(appKey).concat("&").concat(paramStr);
        EsearchResult qccResult = searchFactory.getHandler(EsearchTypeEnum.qcc)
                .searchByUrl(reqUri, appKey, secKey);
        String status = qccResult.getStatus();
        EsearchJsonRecord qccRecord = qccResult.getRecord();
        if (FinalCostHttpHelper.isNormalRequest(status)) {
            saveLog(reqUri);
        }
        if (FinalCostHttpHelper.isSuccessResult(status) && qccRecord != null) {
            saveInfo(qccRecord, keyword,EsearchWayEnum.precise, reqUri);
            EsearchRecordExt esearchRecordExt = new EsearchRecordExt();
            BeanUtils.copyProperties(qccRecord, esearchRecordExt);
            setOriginalNameStr(esearchRecordExt);
            return AjaxResult.success(esearchRecordExt);
        }
        return AjaxResult.error("查询失败, 无此企业");
    }

    private void setOriginalNameStr(EsearchRecordExt record){
        if(StringUtils.isNotBlank(record.getOriginalName()) && record.getOriginalName().contains("Name")){
            JSONArray jsonArray = JSONArray.parseArray(record.getOriginalName());
            List<String> nameList = new ArrayList<>();
            for(int i = 0; i < jsonArray.size(); i++){
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                String name = jsonObject.getString("Name");
                if(StringUtils.isNotBlank(name)){
                    nameList.add(name);
                }
            }
            if(!CollectionUtils.isEmpty(nameList)){
                record.setOriginalNameStr(StringUtils.join(nameList,","));
            }
        }
    }

    private void saveLog(String url) {
        EsearchLog log = new EsearchLog();
        log.setCtime(System.currentTimeMillis());
        log.setUrl(url);
        logService.save(log);
    }

    private void saveInfo(EsearchJsonRecord result,String keyWord, EsearchWayEnum way, String url) {
        EsearchRecord bean = new EsearchRecord();
        bean.setId(UUID.randomUUID().toString());
        bean.setUrl(url);
        bean.setKeyWord(keyWord);
        bean.setWay(way.getMode());
        bean.setCtime(System.currentTimeMillis());
        bean.setTokenJson(JSON.toJSONString(result));
        recordService.save(bean);
        if (ObjectUtil.isNotEmpty(result)) {
            esearchJsonRecordService.save(result);
        }
    }
}
