package com.jeequan.jeepay.mch.ctrl.merchant;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.MchVideoCacheEntity;
import com.jeequan.jeepay.service.impl.MchVideoCacheService;
import com.jeequan.jeepay.thirdparty.service.wxchannel.WechatChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/mchVideo")
public class MchVideoController extends AbstractCtrl {

    @Autowired
    private WechatChannelService wechatChannelService;

    @Autowired
    private MchVideoCacheService mchVideoCacheService;

    @PostMapping("/authTask")
    public ApiRes auth() {
        String mchNo = getValStringRequired("mchNo");
        JSONObject task = wechatChannelService.createTask(mchNo);

        return ApiRes.ok(task);
    }

    @GetMapping("/authTask")
    public ApiRes taskResult() {
        String taskId = getValStringRequired("taskId");
        JSONObject taskResult = wechatChannelService.queryTask(taskId);

        return ApiRes.ok(taskResult);
    }

    @GetMapping("/dataList")
    public ApiRes cacheList() {
        Page<MchVideoCacheEntity> iPage = getIPage();

        MchVideoCacheEntity mchInfo = getObject(MchVideoCacheEntity.class);
        LambdaQueryWrapper<MchVideoCacheEntity> wrapper = Wrappers.lambdaQuery(mchInfo);

        Page<MchVideoCacheEntity> page = mchVideoCacheService.page(iPage, wrapper);
        return ApiRes.ok(page);
    }

    @GetMapping("/randomOne")
    public ApiRes randomOne() {
        String mchNo = getValStringRequired("mchNo");

        MchVideoCacheEntity result = mchVideoCacheService.getRandomOne(mchNo);

        return ApiRes.ok(result);
    }

    @DeleteMapping("/{id}")
    public ApiRes remove(@PathVariable("id") Long id) {
        mchVideoCacheService.removeById(id);

        return ApiRes.ok();
    }

    @PostMapping("/choiceFlag/{id}")
    public ApiRes choiceFlag(@PathVariable("id") Long id) {
        String choiceFlag = getValStringRequired("choiceFlag");
        mchVideoCacheService.lambdaUpdate()
                .eq(MchVideoCacheEntity::getId, id)
                .set(MchVideoCacheEntity::getChoiceFlag, choiceFlag)
                .update();

        return ApiRes.ok();
    }
}
