package cn.wisenergy.service.app.impl;

import cn.wisenergy.mapper.OrderMapper;
import cn.wisenergy.model.app.OrderInfo;
import cn.wisenergy.service.app.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.youzan.cloud.open.sdk.common.exception.SDKException;
import com.youzan.cloud.open.sdk.core.client.auth.Token;
import com.youzan.cloud.open.sdk.core.client.core.DefaultYZClient;
import com.youzan.cloud.open.sdk.core.oauth.model.OAuthToken;
import com.youzan.cloud.open.sdk.core.oauth.token.TokenParameter;
import com.youzan.cloud.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetResult;
import com.youzan.cloud.open.sdk.gen.v4_0_1.api.YouzanTradesSoldGet;
import com.youzan.cloud.open.sdk.gen.v4_0_1.model.YouzanTradesSoldGetParams;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zw
 * @ Description: 定期获取有赞订单数据及更新订单状态
 * @ Author     : zw
 * @ Date       : 2021/2/22 17:06
 */

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    //有赞客户端
    DefaultYZClient yzClient = new DefaultYZClient();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Date startCreatedDate = null;
    Date endCreatedDate = null;
    Date startUpdateDate = null;
    Date endUpdateDate = null;
    Date date = new Date();
    /**
     * 根据订单的创建时间获取有赞的订单数据 插入本地数据库
     *
     * @return
     * @throws SDKException
     */
    @XxlJob(value = "YouZanOrdersjobhandler")
    @Override
    public void getYouZanOrdersForCreateTime() throws SDKException {
        Token token = youzanToken();
        YouzanTradesSoldGet youzanTradesSoldGet = new YouzanTradesSoldGet();
        //创建参数对象,并设置参数
        YouzanTradesSoldGetParams youzanTradesSoldGetParams = new YouzanTradesSoldGetParams();
        OrderInfo orderInfo = new OrderInfo();
        try {
//            startCreatedDate = sdf.parse("2021-01-28 11:04:01");
//            endCreatedDate = sdf.parse("2021-03-1 16:39:59");
            //当前时间的前1分钟
            startCreatedDate = sdf.parse(sdf.format(new Date(date.getTime()-(long) 80*24*60*60*1000)));
            log.info("订单创建开始时间"+sdf.format(startCreatedDate));
            endCreatedDate = sdf.parse(sdf.format(date));
            log.info("订单创建结束时间"+sdf.format(endCreatedDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //设置查询条件 --> 根据订单创建时间获取
        youzanTradesSoldGetParams.setStartCreated(startCreatedDate);
        youzanTradesSoldGetParams.setEndCreated(endCreatedDate);
        youzanTradesSoldGet.setAPIParams(youzanTradesSoldGetParams);
        //执行查询
        YouzanTradesSoldGetResult result = yzClient.invoke(youzanTradesSoldGet, token, YouzanTradesSoldGetResult.class);
        List<YouzanTradesSoldGetResult.YouzanTradesSoldGetResultFullorderinfolist> fullOrderInfoList = result.getData().getFullOrderInfoList();
        //遍历订单数据
        for (YouzanTradesSoldGetResult.YouzanTradesSoldGetResultFullorderinfolist youzanTradesSoldGetResultFullorderinfolist : fullOrderInfoList) {

            YouzanTradesSoldGetResult.YouzanTradesSoldGetResultBuyerinfo buyerInfo = youzanTradesSoldGetResultFullorderinfolist.getFullOrderInfo().getBuyerInfo();
            List<YouzanTradesSoldGetResult.YouzanTradesSoldGetResultOrders> orders = youzanTradesSoldGetResultFullorderinfolist.getFullOrderInfo().getOrders();
            YouzanTradesSoldGetResult.YouzanTradesSoldGetResultOrderinfo youzanOrderInfo = youzanTradesSoldGetResultFullorderinfolist.getFullOrderInfo().getOrderInfo();
            YouzanTradesSoldGetResult.YouzanTradesSoldGetResultPayinfo payInfo = youzanTradesSoldGetResultFullorderinfolist.getFullOrderInfo().getPayInfo();

            //item_id 字段 处理
            List<String> itemList = new ArrayList<>();
            for (YouzanTradesSoldGetResult.YouzanTradesSoldGetResultOrders order : orders) {
                String itemId = order.getItemId().toString();
                itemList.add(itemId);
            }

            orderInfo.setItemId(itemList.toString());
            //有赞的outer_user_id
            orderInfo.setBuyerId(buyerInfo.getOuterUserId());
            //支付方式
            orderInfo.setPayType(youzanOrderInfo.getPayType().toString());
            //有赞update_time
            orderInfo.setYouzanUpdateTime(youzanOrderInfo.getUpdateTime());
            //tid
            orderInfo.setTid(youzanOrderInfo.getTid());
            //created 订单创建时间
            orderInfo.setCreated(youzanOrderInfo.getCreated());
            //team_type  店铺类型
            orderInfo.setTeamType(youzanOrderInfo.getTeamType());
            //pay_time
            orderInfo.setPayTime(youzanOrderInfo.getPayTime());
            //pay_type_str 支付渠道
            orderInfo.setPayTypeStr(youzanOrderInfo.getPayTypeStr());
            //close_type
            orderInfo.setCloseType(youzanOrderInfo.getCloseType().intValue());
            //refund_state 退款状态
            orderInfo.setRefundState(youzanOrderInfo.getRefundState());
            //success_time
            orderInfo.setSuccessTime(youzanOrderInfo.getSuccessTime());
            //payment
            orderInfo.setPayment(new BigDecimal(payInfo.getPayment()));
            //rebate_status  返佣状态
            orderInfo.setRebateStatus(0);
            //month_order_status  //当月订单处理状态
            orderInfo.setMonthOrderStatus(0);
            //monthly_task_status  //月度任务处理状态
            orderInfo.setMonthlyTaskStatus(0);
            log.info("根据创建时间获取有赞订单号："+youzanOrderInfo.getTid());
            orderMapper.insertYouZanOrders(orderInfo);
        }
    }

    /**
     * 根据订单的修改时间获取有赞的订单数据 修改本地数据库的相关订单数据
     *
     * @return
     * @throws SDKException
     */
    @Override
    public void getYouZanOrdersForUpdateTime() throws SDKException {
        Token token = youzanToken();
        YouzanTradesSoldGet youzanTradesSoldGet = new YouzanTradesSoldGet();
        //创建参数对象,并设置参数
        YouzanTradesSoldGetParams youzanTradesSoldGetParams = new YouzanTradesSoldGetParams();
        OrderInfo orderInfo = new OrderInfo();
        try {
//            startUpdateDate = sdf.parse("2021-02-28 11:04:01");
//            endUpdateDate = sdf.parse("2021-03-2 16:39:59");
            startUpdateDate = sdf.parse(sdf.format(new Date(date.getTime()-(long) 80*24*60*60*1000)));
            log.info("订单修改开始时间"+sdf.format(startUpdateDate));
            endUpdateDate = sdf.parse(sdf.format(date));
            log.info("订单修改结束时间"+sdf.format(endUpdateDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //设置查询条件 --> 根据订单修改时间获取
        youzanTradesSoldGetParams.setStartUpdate(startUpdateDate);
        youzanTradesSoldGetParams.setEndUpdate(endUpdateDate);
        youzanTradesSoldGet.setAPIParams(youzanTradesSoldGetParams);
        //调用有赞客户端进行查询
        YouzanTradesSoldGetResult result = yzClient.invoke(youzanTradesSoldGet, token, YouzanTradesSoldGetResult.class);
        List<YouzanTradesSoldGetResult.YouzanTradesSoldGetResultFullorderinfolist> fullOrderInfoList = result.getData().getFullOrderInfoList();
        //遍历订单数据
        for (YouzanTradesSoldGetResult.YouzanTradesSoldGetResultFullorderinfolist youzanTradesSoldGetResultFullorderinfolist : fullOrderInfoList) {
            YouzanTradesSoldGetResult.YouzanTradesSoldGetResultOrderinfo youzanOrderInfo = youzanTradesSoldGetResultFullorderinfolist.getFullOrderInfo().getOrderInfo();
            YouzanTradesSoldGetResult.YouzanTradesSoldGetResultPayinfo payInfo = youzanTradesSoldGetResultFullorderinfolist.getFullOrderInfo().getPayInfo();

            //根据修改时间获取到的有赞订单数据的Tid
            String tid = youzanOrderInfo.getTid();
            OrderInfo orderByTid = orderMapper.getByTid(tid);

            //确保是同一笔订单且订单的success_time=null是进行订单success_time状态修改
            if (orderByTid != null && orderByTid.getSuccessTime() == null){
                //支付方式
                orderInfo.setPayType(youzanOrderInfo.getPayType().toString());
                //有赞update_time
                orderInfo.setYouzanUpdateTime(youzanOrderInfo.getUpdateTime());
                //tid
                orderInfo.setTid(youzanOrderInfo.getTid());
                //pay_time
                orderInfo.setPayTime(youzanOrderInfo.getPayTime());
                //pay_type_str 支付渠道
                orderInfo.setPayTypeStr(youzanOrderInfo.getPayTypeStr());
                //close_type
                orderInfo.setCloseType(youzanOrderInfo.getCloseType().intValue());
                //refund_state 退款状态
                orderInfo.setRefundState(youzanOrderInfo.getRefundState());
                //success_time
                orderInfo.setSuccessTime(youzanOrderInfo.getSuccessTime());
                //payment
                orderInfo.setPayment(new BigDecimal(payInfo.getPayment()));

                log.info("根据修改时间获取有赞订单号："+youzanOrderInfo.getTid());
                //修改订单数据
                orderMapper.updateById(orderInfo);
            }
        }
    }

    /**
     * 有赞token获取
     *
     * @return
     * @throws SDKException
     */
    public static Token youzanToken() throws SDKException {
        DefaultYZClient yzClient = new DefaultYZClient();
        TokenParameter tokenParameter = TokenParameter.self()
                .clientId("92bc1c500ce7c248f3")
                .clientSecret("3d65e88f5106e8ee78dbc5cf5ff45526")
                .grantId("92488799")
                .refresh(true)
                .build();
        OAuthToken oAuthToken = yzClient.getOAuthToken(tokenParameter);
        String accessToken = oAuthToken.getAccessToken();
        log.info(accessToken);

        Token youzanToken = new Token(accessToken);
        return youzanToken;
    }

}
