package jlifereptileserver;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.PostorderApplication;
import com.reptileclient.jlifeapp.constant.DyLifeConstants;
import com.reptileclient.jlifeapp.dao.jz.DyLaikeAccountShopMapInfoMapper;
import com.reptileclient.jlifeapp.dao.jz.DyLaikeShopEvaltionMapper;
import com.reptileclient.jlifeapp.dao.jz.DyLaikeShopThreeRateMapper;
import com.reptileclient.jlifeapp.dao.jz.DyLaikeTokenMapper;
import com.reptileclient.jlifeapp.entity.DyLaikeShopEvaltion;
import com.reptileclient.jlifeapp.entity.jz.DyLaikeAccountShopMapInfo;
import com.reptileclient.jlifeapp.entity.jz.DyLaikeShopThreeRate;
import com.reptileclient.jlifeapp.entity.jz.DyLaikeToken;
import com.reptileclient.jlifeapp.schedule.DouyinLaikeTask;
import com.reptileclient.jlifeapp.service.DyLaikeService;
import com.reptileclient.jlifeapp.util.OkHttpUtil;
import com.reptileclient.jlifeapp.util.ThreadPoolManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PostorderApplication.class)
@ActiveProfiles("prod")
public class DyLifeTest {


    @Autowired
    private DyLaikeTokenMapper dyLaikeTokenMapper;

    @Autowired
    private DyLaikeAccountShopMapInfoMapper shopMapInfoMapper;

    @Autowired
    private DyLaikeShopEvaltionMapper shopEvaltionMapper;

    @Autowired
    private DyLaikeShopThreeRateMapper shopThreeRateMapper;

    private static final int pageSize = 200;

    private String token;


    private String accountId;

    private Integer batchId = 0;
    private Integer shopEvaltionCount = 0;

    @Before
    public void pre() {
        DyLaikeToken dyLaikeToken = dyLaikeTokenMapper.selectByPrimaryKey(1);
        token = dyLaikeToken.getToken();
        accountId = dyLaikeToken.getAccountId();
    }





    @Test
    public void getThreeRateData() {
        List<DyLaikeAccountShopMapInfo> shops = shopMapInfoMapper.selectAll();
        batchId = shopThreeRateMapper.getLastBatch();
        // 上周三
        String start_date = LocalDateTime.now().minusWeeks(1).withHour(0).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //本周二
        String end_date = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        for (DyLaikeAccountShopMapInfo shop : shops) {
            String requestUrl = DyLifeConstants.threeRateApi.replace("{this_shop_id}", shop.getShopAccountId())
                    .replace("{root_life_account_id}", accountId)
                    .replace("{start_date}", start_date)
                    .replace("{end_date}", end_date);
            processThreeRate(requestUrl, shop.getShopPoiId(), shop.getShopName());
        }

        while (true) {
              if (shopEvaltionCount == shops.size()) {
                  break;
              }
        }
        System.out.println("全部请求完毕");
    }

    private void processThreeRate(String requestUrl, String shopPoiId, String shopName) {
        ThreadPoolManager.execute(()->{
            String s = OkHttpUtil.get2Dy(requestUrl, token);
            JSONObject jsonObject = JSONObject.parseObject(s);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONObject data1 = data.getJSONObject("Data");
                BigDecimal badRadio = data1.getJSONObject("BadCommentRatio").getBigDecimal("AvgVal");
                BigDecimal complain = data1.getJSONObject("ComplaintRatio").getBigDecimal("AvgVal");
                BigDecimal refund = data1.getJSONObject("RefundRatio").getBigDecimal("AvgVal");
                DyLaikeShopThreeRate dyLaikeShopThreeRate = new DyLaikeShopThreeRate();
                dyLaikeShopThreeRate.setShopPoiId(shopPoiId);
                dyLaikeShopThreeRate.setShopName(shopName);
                dyLaikeShopThreeRate.setBadRate(badRadio);
                dyLaikeShopThreeRate.setComplaintRate(complain);
                dyLaikeShopThreeRate.setRefundRate(refund);
                dyLaikeShopThreeRate.setBatchId(batchId);
                dyLaikeShopThreeRate.setEvaUpdateTime(LocalDateTime.now().minusDays(1));
                dyLaikeShopThreeRate.setEtlTime(LocalDateTime.now());
                shopThreeRateMapper.insertSelective(dyLaikeShopThreeRate);
                shopEvaltionCount++;
            }
        });



    }

    @Test
    public void getReviewData() {
        List<DyLaikeAccountShopMapInfo> shops = shopMapInfoMapper.selectAll();

        batchId = shopEvaltionMapper.getLastBatch();
        for (DyLaikeAccountShopMapInfo shop : shops) {
            String requestUrl = DyLifeConstants.reviewApi.replace("{shop_account_id}", shop.getShopAccountId())
                    .replace("{poi_id}", shop.getShopPoiId())
                    .replace("{root_life_account_id}", accountId);
            process(requestUrl, shop.getShopPoiId(), shop.getShopName());
        }

        //等待所有线程执行完毕
        while (true) {
            if (shopEvaltionCount == shops.size()) {
                break;
            }
        }

        //更新对应的fra_id和fra_name
        shopEvaltionMapper.updateLastBatch(batchId);

    }

    private void process(String requestUrl, String shopPoiId, String shopName) {
        ThreadPoolManager.execute(() -> {
            String s = OkHttpUtil.get2Dy(requestUrl, token);
            JSONObject jsonObject = JSONObject.parseObject(s);
            JSONObject data = jsonObject.getJSONObject("data");
            DyLaikeShopEvaltion dyLaikeShopEvaltion = new DyLaikeShopEvaltion();
            dyLaikeShopEvaltion.setShopPoiId(shopPoiId);
            dyLaikeShopEvaltion.setShopName(shopName);
            dyLaikeShopEvaltion.setEvaCount(data.getInteger("comment_count"));
            dyLaikeShopEvaltion.setEvaLastMonthCount(data.getInteger("comment_cnt_last_month"));
            dyLaikeShopEvaltion.setEvaLastGoods(data.getInteger("positive_comment_cnt_last_month"));
            dyLaikeShopEvaltion.setEvaLastBad(data.getInteger("other_comment_cnt_last_month"));
            dyLaikeShopEvaltion.setScore(data.getBigDecimal("origin_score_t_1"));
            dyLaikeShopEvaltion.setBatchId(batchId);
            dyLaikeShopEvaltion.setEvaUpdateTime(LocalDateTime.ofEpochSecond(data.getLong("review_updated_time"), 0, ZoneId.systemDefault().getRules().getOffset(LocalDateTime.now())));
            dyLaikeShopEvaltion.setEtlTime(LocalDateTime.now());
            shopEvaltionMapper.insert(dyLaikeShopEvaltion);
            shopEvaltionCount++;
        });
    }


    @Autowired
    private DouyinLaikeTask task;

    @Test
    public void testService() {
        task.runTask();

    }

    @Autowired
    private DyLaikeService dyLaikeService;

    @Test
    public void testThreeRate() {
        dyLaikeService.getThreeRate();
    }

    @Test
    public void syncShopAndPoi() {
        dyLaikeService.syncShopAndPoi();
    }



}
