package com.zswl.cloud.springBtach.server.core.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.github.microservice.auth.client.content.ResultContent;
import com.github.microservice.auth.client.content.ResultState;
import com.github.microservice.auth.security.helper.AuthHelper;
import com.zhongshu.payment.client.model.order.AdminSeachOrderModel;
import com.zhongshu.payment.client.model.order.UserSeachOrderModel;
import com.zhongshu.payment.client.model.order.v2.*;
import com.zhongshu.payment.client.service.v2.OrderService2;
import com.zhongshu.payment.client.type.ErrorCode;
import com.zhongshu.payment.client.type.JobFlowMap;
import com.zhongshu.payment.client.type.JobFlowType;
import com.zhongshu.payment.client.type.OrderType;
import com.zswl.cloud.shop.client.service.ShopService;
import com.zswl.cloud.shop.client.vo.life.EmployeeDetailVo;
import com.zswl.cloud.shop.client.vo.life.ShopDetailVo;
import com.zswl.cloud.springBatch.client.service.OrderService;
import com.zswl.cloud.springBtach.server.core.helper.RedisHelper;
import com.zswl.cloud.springBtach.server.core.job.standard.StandarVerificationJob;
import com.zswl.cloud.springBtach.server.core.job.standard.StandarOrderJob;
import lombok.SneakyThrows;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class OrderServiceImp implements OrderService {

    @Autowired
    private StandarOrderJob standardOrderJob;

    @Autowired
    private StandarVerificationJob standarVerificationJob;

    @Resource
    private JobLauncher jobLauncher;

    @Resource
    private JobExplorer jobExplorer;


    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    OrderService2 orderService2;


    @Autowired
    RedisHelper redisHelper;

    @Autowired
    AuthHelper authHelper;


    @Autowired
    ShopService shopService;


    private final String redisKey = "use_";


    @Override
    @SneakyThrows
    public ResultContent creat(CreateOrder2Model createOrderModel) {

        CreateOrder2Model.Goods goods = createOrderModel.getGoodsList().get(0);

        JobFlowMap jobFlowMap = goods.getJobFlowMap();
        String jobName = jobFlowMap.getJobMapping().get(JobFlowType.CrateOrder);
        ThreadLocal<CreateOrder2Model> parameter = standardOrderJob.getParameter();
        parameter.set(createOrderModel);
        Job job = (Job) applicationContext.getBean(jobName);
        JobParameters parameters = new JobParametersBuilder(jobExplorer)
                .getNextJobParameters(job)
                .toJobParameters();
        jobLauncher.run(job, parameters).getExitStatus();
        return standardOrderJob.getResultContent().get();
    }


    public ResultContent qrCode(String id) {
        String userId = authHelper.getCurrentUser().getUserId();
        ResultContent<GoodsResultModel> resultContent = orderService2.goodsDetail(userId, id);
        if (resultContent.getState().equals(ResultState.Success)) {
            OrderType goodsState = resultContent.getContent().getGoodsState();
            switch (goodsState) {
                case WAIT_USE:
                    String removeKey = redisKey + id;
                    redisHelper.removeKeys(removeKey);
                    long timeMillis = System.currentTimeMillis();
                    String token = String.valueOf(id) + timeMillis;
                    String cache = redisKey + token;
                    redisHelper.cacheValue(cache, id, 60);
                    return ResultContent.buildContent(token);
                case USED:
                    return ResultContent.build(ResultState.Fail, ErrorCode.ORDER_USED.getMess());

            }
            return ResultContent.build(ResultState.Fail, ErrorCode.ORDER_UNUSABLE.getMess());

        }

        return resultContent;
    }

    @SneakyThrows
    public ResultContent verification(String token) {


        Object id = redisHelper.getValue(redisKey + token);
        if (ObjectUtil.isEmpty(id)) {
            return ResultContent.build(ResultState.Fail, ErrorCode.CQ_TIME_OUTE.getMess());
        }

        String enterPriseId = authHelper.getEnterPriseId();

        VerificationModel verificationModel = new VerificationModel();

        // todo 构建核销的商家信息
        JSONObject entries = new JSONObject();


        com.zswl.cloud.shop.client.ret.ResultContent<EmployeeDetailVo> employee = shopService.getEmployee(authHelper.getCurrentUser().getUserId());
        EmployeeDetailVo employeeContent = employee.getContent();
        com.zswl.cloud.shop.client.ret.ResultContent<ShopDetailVo> detail = shopService.detail(enterPriseId);
        ShopDetailVo shopDetailVo = detail.getContent();
        entries.set("shopName", shopDetailVo.getShopName());
        entries.set("employeeName", employeeContent.getEmployeeName());

        verificationModel.setVerification(entries);
        verificationModel.setId((String) id);
        verificationModel.setShopId(enterPriseId);

        ResultContent<GoodsResultModel> goodsResultModelResultContent = orderService2.qrGoods(String.valueOf(id));
        if (!goodsResultModelResultContent.getState().equals(ResultState.Success)) {

            return goodsResultModelResultContent;

        }
        GoodsResultModel content = goodsResultModelResultContent.getContent();

        JobFlowMap jobFlowMap = content.getJobFlowMap();
        String jobName = jobFlowMap.getJobMapping().get(JobFlowType.Verification);
        ThreadLocal<VerificationModel> parameter = standarVerificationJob.getParameter();
        parameter.set(verificationModel);
        Job job = (Job) applicationContext.getBean(jobName);
        JobParameters parameters = new JobParametersBuilder(jobExplorer)
                .getNextJobParameters(job)
                .toJobParameters();
        jobLauncher.run(job, parameters);
        return standarVerificationJob.getResultContent().get();


    }


    public ResultContent userSearch(UserSeachOrderModel userSeachOrderModel) {
        String userId = authHelper.getCurrentUser().getUserId();
        UserSeachOrder2Model userSeachOrder2Model = new UserSeachOrder2Model();
        BeanUtils.copyProperties(userSeachOrderModel, userSeachOrder2Model);
        userSeachOrder2Model.setUserId(userId);

        return orderService2.userSearch(userSeachOrder2Model);
    }

    public ResultContent goodsDetail(String id) {
        String userId = authHelper.getCurrentUser().getUserId();

        return orderService2.goodsDetail(userId, id);
    }

    public ResultContent orderDetails(String orderNo) {
        String userId = authHelper.getCurrentUser().getUserId();

        return orderService2.orderDetail(userId, orderNo);
    }

    public ResultContent<Page<OrderResult2Model>> shopSearch(AdminSeachOrderModel adminSeachOrderModel) {
        adminSeachOrderModel.setShopId(authHelper.getEnterPriseId());
        return orderService2.adminSearch(adminSeachOrderModel);
    }

    public ResultContent<Page<OrderResult2Model>> shopOrderDetail(String orderNo) {
        return orderService2.shopOrderDetail(authHelper.getEnterPriseId(), orderNo);
    }

    public ResultContent adminSearch(AdminSeachOrderModel adminSeachOrderModel) {
        return orderService2.adminSearch(adminSeachOrderModel);
    }

    public ResultContent adminOrderDetail(String orderNo) {
        return orderService2.adminOrderDetail(orderNo);
    }


}
