package com.picc.grab.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.picc.grab.crawl.*;
import com.picc.grab.domain.Zbwt;
import com.picc.grab.entity.ZbwtVo;
import com.picc.grab.entity.common.vo.ResultVO;
import com.picc.grab.mapper.ZbwtMapper;
import com.picc.grab.service.ICarinfoService;
import com.picc.grab.service.IPiccgrabaccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 爬取中标价
 * @author adu
 * @date 2022/8/1.
 */
@Slf4j
@Component
@EnableScheduling
public class SuccessfulTask {
    @Autowired
    private IPiccgrabaccountService piccgrabaccountService;
    @Autowired
    private ZbwtMapper zbwtMapper;

    private static final String OFFER_PLATFORM_LIST_URL = "https://baojia.epicc.com.cn/api/app/bbp/info/offerPlatformList";
    private static final String BBP_DETAIL_LIST_URL = "https://baojia.epicc.com.cn/api/app/bbp/info/BbpDetailList";

    /**
     * 同步信息
     * 每十分钟同步一次
     */
    @Transactional
    @Scheduled(cron = "0 */10 * * * ?")
    public void syncInfo() throws Exception {
        //查询需要同步中标信息的车
        List<ZbwtVo> zbwtList = zbwtMapper.findByTime();
        if (CollectionUtils.isEmpty(zbwtList)){
            return;
        }
        //入参
        OfferPlatFromBody body = new OfferPlatFromBody();
        body.setAuctionStatus("02");
        body.setSelectContionsType("02");
        body.setStartTime(DateUtil.format(cn.hutool.core.date.DateUtil.lastMonth(), "yyyy-MM-dd"));
        body.setEndTime(DateUtil.format(cn.hutool.core.date.DateUtil.tomorrow(), "yyyy-MM-dd"));
        List<String> tokens = piccgrabaccountService.findTokenByLogIn();
        if (CollectionUtils.isEmpty(tokens)){
            return;
        }

        for (String token : tokens) {
            // 获取报价完成列表的车辆
            OfferPlatformBean platFromBean;
            try {
                platFromBean = getPlatFromBean(token, body);
            }catch (Exception e){
                continue;
            }
            // list转为map key为车牌号
            Map<String, OfferPlatformBean.BbpAuctionSelectVo> map = platFromBean.getData().getBbpAuctionSelectVoList()
                    .stream().collect(Collectors.toMap(OfferPlatformBean.BbpAuctionSelectVo::getCarNo, Function.identity(), (item1, item2) -> item1));
            for (ZbwtVo zbwt : zbwtList) {
                //根据车牌号获取报价完成的车辆信息
                OfferPlatformBean.BbpAuctionSelectVo auctionSelectVo = map.get(zbwt.getCph());
                if (Objects.isNull(auctionSelectVo)){
                    continue;
                }
                try {
                    //获取车辆详情
                    BbpDetailBean detailBean = getBbpDetail(token, new BbpDetailBody(auctionSelectVo.getId()));
                    if (Objects.isNull(detailBean.getData())) {
                        continue;
                    }
                    //同步中标信息
                    if (!Objects.isNull(detailBean.getData().getBbpWonBidVo())) {
                        String zbgzstatus = "3";
                        if (StringUtils.isNotBlank(detailBean.getData().getBbpWonBidVo().getBidCompanyName())
                                && detailBean.getData().getBbpWonBidVo().getBidCompanyName().contains("湖北同凯拍卖有限公司")){
                            zbgzstatus = "4";
                        }
                        zbwtMapper.updateZbwt(zbgzstatus,zbwt.getCarid()
                                ,detailBean.getData().getBbpWonBidVo().getBidCompanyName()
                                ,detailBean.getData().getBbpWonBidVo().getCreateTime()
                                ,detailBean.getData().getBbpWonBidVo().getBidPrice());
                        log.info("定时任务--同步车辆中标信息,车辆id："+zbwt.getCarid());
                    }
                }catch (Exception e){
                    continue;
                }

            }
        }
    }


    /**
     * 调用人保 获取报价完成列表的车辆
     * @param token
     * @param body
     * @return
     * @throws Exception
     */
    private OfferPlatformBean getPlatFromBean(String token, OfferPlatFromBody body) throws Exception {
        String result = HttpRequest.post(OFFER_PLATFORM_LIST_URL)
                .header("token", token).body(JSONUtil.parseObj(body, false, true).toString()).timeout(20000).execute().body();
        OfferPlatformBean bean = JSONUtil.toBean(result, OfferPlatformBean.class);
        if (!"200".equals(bean.getCode())) {
            log.error("{},token:{}", bean.getMsg(), token);
            throw new Exception(bean.getMsg());
        }
        return bean;
    }


    /**
     * 调用人保 获取车辆详情
     * @param token
     * @param bbpDetailBody
     * @return
     * @throws Exception
     */
    private BbpDetailBean getBbpDetail(String token, BbpDetailBody bbpDetailBody) throws Exception {
        String result = HttpRequest.post(BBP_DETAIL_LIST_URL)
                .header("token", token).body(JSONUtil.parseObj(bbpDetailBody, false, true).toString()).timeout(20000).execute().body();
        BbpDetailBean detailBean = JSONUtil.toBean(result, BbpDetailBean.class);
        if (!"200".equals(detailBean.getCode())) {
            log.error(bbpDetailBody.getId() + "获取详情失败：" + detailBean.getMsg());
            if ("101".equals(detailBean.getCode())) {
                throw new Exception(detailBean.getMsg());
            }
        }
        return detailBean;
    }
}
