package com.hzs.third.job.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hzs.bonus.settle.IMemberSettleBonusApi;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.member.account.IMemberJobServiceApi;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.base.dto.AreaDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 定时任务测试控制器
 */
@Slf4j
@RestController
@RequestMapping("/job-test")
public class JobTestController {

    @DubboReference
    IAreaServiceApi iAreaServiceApi;

    @DubboReference
    IMemberJobServiceApi iMemberJobServiceApi;
    @DubboReference
    IMemberSettleBonusApi iMemberSettleBonusApi;


    @GetMapping("/test-settle")
    public AjaxResult testSettle() {
        Date startDate = DateUtils.beforeDate(1, ChronoUnit.DAYS, DateUtils.currentDate());
        iMemberSettleBonusApi.autoCalculateBonus(startDate);
        return AjaxResult.success();
    }

    /**
     * 测试行政区划更新
     *
     * @return
     */
    @GetMapping("/test-area")
    public AjaxResult testArea() {
        // 行政区划列表
        List<AreaDTO> provinceList = new ArrayList<>();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("ak", "B97a236f0422d856f521ad7f7dcda88a");
        paramMap.put("keyword", "全国");
        paramMap.put("extensions_code", "1");
        paramMap.put("sub_admin", "3");

        String resultStr = HttpUtil.get("https://api.map.baidu.com/api_region_search/v1/", paramMap);
//        log.info("resultStr: {}", resultStr);

        JSONObject resultObject = JSONUtil.parseObj(resultStr);
        if (resultObject.getInt("status") == 0) {
            // 全国一级
            JSONObject countryObject = resultObject.getJSONArray("districts").getJSONObject(0);
            // 省列表
            JSONArray provinceArray = countryObject.getJSONArray("districts");
            if (!provinceArray.isEmpty()) {
                for (int i = 0; i < provinceArray.size(); i++) {
                    JSONObject provinceObject = provinceArray.getJSONObject(i);
                    if ("4".equals(provinceObject.getStr("level")) || "990000".equals(provinceObject.getStr("code"))) {
                        // 第4级行政区划（街道）和990000这个地区不需要
                        continue;
                    }
                    log.info("省编码：{}， 省名称：{}", provinceObject.getStr("code"), provinceObject.getStr("name"));
                    // 市列表
                    List<AreaDTO> cityList = new ArrayList<>();
                    // 省列表中添加省数据
                    provinceList.add(AreaDTO.builder()
                            .code(provinceObject.getStr("code"))
                            .name(provinceObject.getStr("name"))
                            .childList(cityList)
                            .build());


                    // 市列表
                    JSONArray cityArray = provinceObject.getJSONArray("districts");
                    if (!cityArray.isEmpty()) {
                        for (int j = 0; j < cityArray.size(); j++) {
                            JSONObject cityArrayObject = cityArray.getJSONObject(j);
                            if ("4".equals(cityArrayObject.getStr("level"))) {
                                // 第4级行政区划（街道）不需要
                                continue;
                            }
                            log.info("市编码：{}， 市名称：{}", cityArrayObject.getStr("code"), cityArrayObject.getStr("name"));
                            // 区列表
                            List<AreaDTO> countyList = new ArrayList<>();
                            // 市列表中添加市数据
                            cityList.add(AreaDTO.builder()
                                    .code(cityArrayObject.getStr("code"))
                                    .name(cityArrayObject.getStr("name"))
                                    .childList(countyList)
                                    .build());

                            // 区列表
                            JSONArray countyArray = cityArrayObject.getJSONArray("districts");
                            if (!countyArray.isEmpty()) {
                                for (int k = 0; k < countyArray.size(); k++) {
                                    JSONObject countyArrayObject = countyArray.getJSONObject(k);
                                    if ("4".equals(countyArrayObject.getStr("level"))) {
                                        // 第4级行政区划（街道）不需要
                                        continue;
                                    }
                                    log.info("区编码：{}， 区名称：{}", countyArrayObject.getStr("code"), countyArrayObject.getStr("name"));
                                    // 区列表中添加区数据
                                    countyList.add(AreaDTO.builder()
                                            .code(countyArrayObject.getStr("code"))
                                            .name(countyArrayObject.getStr("name"))
                                            .build());
                                }
                            }
                        }
                    }
                }
            }
        }

        Collections.sort(provinceList, Comparator.comparing(AreaDTO::getCode));

        R resultR = iAreaServiceApi.updateArea(provinceList);
        if (resultR.isSuccess()) {
            return AjaxResult.success(provinceList);
        }
        return AjaxResult.error("处理失败：" + resultR.getMsg());
    }


    @GetMapping("/autoDeleteGarbageData")
    public AjaxResult autoDeleteGarbageData() {
        iMemberJobServiceApi.autoDeleteGarbageData();
        return AjaxResult.success();
    }
}
