package com.zswl.cloud.springBtach.server.core.job.standard;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.github.microservice.auth.client.content.ResultContent;
import com.zhongshu.payment.client.model.order.v2.CreateOrder2Model;
import com.zhongshu.payment.client.service.v2.OrderService2;
import com.zhongshu.payment.client.type.JobFlowMap;
import com.zhongshu.payment.client.type.TransferOwner;
import com.zhongshu.payment.client.type.TransferType;
import com.zswl.cloud.shop.client.dto.life.CalculateCouponDto;
import com.zswl.cloud.shop.client.dto.life.OperateStockDto;
import com.zswl.cloud.shop.client.ret.ResultState;
import com.zswl.cloud.shop.client.service.GoodsService;
import com.zswl.cloud.shop.client.service.ShopService;
import com.zswl.cloud.shop.client.vo.life.CalculateVo;
import com.zswl.cloud.shop.client.vo.life.GoodsInfoVo;
import com.zswl.cloud.shop.client.vo.life.SharePlatformVo;
import com.zswl.cloud.shop.client.vo.life.ShopDetailVo;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;

@Data
@Configuration
@Log4j2
public class StandarOrderJob {

    ThreadLocal<ResultContent> resultContent = new ThreadLocal<>();

    ThreadLocal<CreateOrder2Model> parameter = new ThreadLocal<>();
    ThreadLocal<Boolean> stop = new ThreadLocal<>();
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Resource
    private JobBuilderFactory jobBuilderFactory;


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ShopService shopService;


    @Autowired
    OrderService2 orderService2;

    public Step checkFrom() {
        return stepBuilderFactory.get("checkFrom")
                .tasklet((contribution, chunkContext) -> {
                    stop.set(false);

                    CreateOrder2Model createOrder2Model = getParameter().get();


                    // 店铺详情
                    com.zswl.cloud.shop.client.ret.ResultContent<ShopDetailVo> detail1 = shopService.detail(createOrder2Model.getShopId());
                    log.info("店铺详情：{}", JSONUtil.toJsonStr(detail1));
                    ShopDetailVo shopDetailVo = detail1.getContent();
                    createOrder2Model.setShopInfo(JSONUtil.parseObj(shopDetailVo));
                    if (ObjectUtil.isEmpty(shopDetailVo.getAuthAccount())) {
                        resultContent.set(ResultContent.build(com.github.microservice.auth.client.content.ResultState.Fail, "分账账户未设置"));
                        stop.set(true);
                        return RepeatStatus.FINISHED;
                    }


                    for (CreateOrder2Model.Goods goods : createOrder2Model.getGoodsList()) {

                        // 商品详情
                        com.zswl.cloud.shop.client.ret.ResultContent<GoodsInfoVo> detail = goodsService.detail(goods.getGoodsId(), 1, createOrder2Model.getUserId());
                        log.info("商品详情：{}", JSONUtil.toJsonStr(detail));
                        GoodsInfoVo goodsInfoVo = detail.getContent();
                        SharePlatformVo sharePlatformVo = goodsInfoVo.getSharePlatformVo();
                        if (ObjectUtil.isEmpty(sharePlatformVo)) {
                            stop.set(true);
                            getResultContent().set(ResultContent.build(com.github.microservice.auth.client.content.ResultState.Fail, "分账规则未配置"));
                            return RepeatStatus.FINISHED;
                        }

                        OperateStockDto operateStockDto = new OperateStockDto();
                        operateStockDto.setUserId(createOrder2Model.getUserId());
                        operateStockDto.setOperate(1);// 暂用库存
                        operateStockDto.setShopId(createOrder2Model.getShopId());
                        operateStockDto.setGoodsId(goods.getGoodsId());

                        try {

                            // 暂用库存
                            com.zswl.cloud.shop.client.ret.ResultContent resultContent1 = goodsService.operateStock(operateStockDto);

                            log.info("锁定商品结果：{}", JSONUtil.toJsonStr(resultContent1));
                            if (resultContent1.getState().equals(ResultState.Success)) {

                                // 计算价格
                                CalculateCouponDto calculateCouponDto = new CalculateCouponDto();
                                calculateCouponDto.setUserId(createOrder2Model.getUserId());
                                calculateCouponDto.setShopId(createOrder2Model.getShopId());
                                calculateCouponDto.setGoodsId(goods.getGoodsId());


                                com.zswl.cloud.shop.client.ret.ResultContent<CalculateVo> calculate = goodsService.calculate(calculateCouponDto);
                                log.info("计算价格：{}", JSONUtil.toJsonStr(calculate));
                                CalculateVo calculateVo = calculate.getContent();
                                // 设置订单价格
                                createOrder2Model.setTotalAmount(calculateVo.getPrice());
                                createOrder2Model.setPayAmount(calculateVo.getPrice());
                                createOrder2Model.setDiscountAmount(calculateVo.getOffset());

                                goods.setPayAmount(calculateVo.getPrice());


                                // 设置分账账户
                                createOrder2Model.setAccesserUserId(shopDetailVo.getAuthAccount());


                                // 设置有效期
                                createOrder2Model.setValidDay(goodsInfoVo.getValidDay());


                                // 设置分账规则
                                goods.setTransferType(sharePlatformVo.getShareType() == 1 ? TransferType.RATIO : TransferType.FIXED);
                                // 平台
                                CreateOrder2Model.Owner platform = new CreateOrder2Model.Owner();
                                platform.setOwner(TransferOwner.PLATFORM);
                                platform.setValue(sharePlatformVo.getPlatformRate());

                                // 购买店铺
                                CreateOrder2Model.Owner byShop = new CreateOrder2Model.Owner();
                                byShop.setOwner(TransferOwner.BUY_SHOP);
                                byShop.setValue(sharePlatformVo.getBuyShopRate());

                                // 使用店铺
                                CreateOrder2Model.Owner useShop = new CreateOrder2Model.Owner();
                                useShop.setOwner(TransferOwner.USE_SHOP);
                                useShop.setValue(sharePlatformVo.getCheckShopRate());

                                ArrayList<CreateOrder2Model.Owner> rule = new ArrayList<>();
                                rule.add(platform);
                                rule.add(byShop);
                                rule.add(useShop);
                                goods.setTransferRrule(rule);

                                // 设置商品详情
                                goods.setGoodsInfo(JSONUtil.parseObj(goodsInfoVo));
                                return RepeatStatus.FINISHED;

                            }

                            stop.set(true);
                            resultContent.set(ResultContent.build(com.github.microservice.auth.client.content.ResultState.Fail, resultContent1.getMsg()));
                            return RepeatStatus.FINISHED;


                        } catch (Exception e) {
                            stop.set(true);
                            e.printStackTrace();
                            resultContent.set(ResultContent.build(com.github.microservice.auth.client.content.ResultState.Fail, e.getMessage()));
                            operateStockDto.setOperate(2);
                            goodsService.operateStock(operateStockDto);
                        }

                    }

                    return RepeatStatus.FINISHED;

                })
                .build();
    }

    public Step platformOrder() {
        return stepBuilderFactory.get("standardPlatformOrder")
                .tasklet((contribution, chunkContext) -> {
                    if (stop.get()) {
                        return RepeatStatus.FINISHED;
                    }

                    CreateOrder2Model createOrder2Model = getParameter().get();

                    ResultContent creat = orderService2.creat(createOrder2Model);
                    getResultContent().set(creat);

                    if (!creat.getState().equals(com.github.microservice.auth.client.content.ResultState.Success)) {
                        OperateStockDto operateStockDto = new OperateStockDto();
                        operateStockDto.setUserId(createOrder2Model.getUserId());
                        operateStockDto.setOperate(2);// 暂用库存
                        operateStockDto.setShopId(createOrder2Model.getShopId());
                        operateStockDto.setGoodsId(createOrder2Model.getGoodsList().get(0).getGoodsId());
                        goodsService.operateStock(operateStockDto);
                    }

                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public Job standardCreatOrder() {
        return getJobBuilderFactory()
                .get("standardCreatOrder")
                .start(checkFrom())
                .next(platformOrder())
                .incrementer(new RunIdIncrementer())
                .build();
    }

}
