package cn.pluss.platform.controller.merchant;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.entity.SystemConfig;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.ComUtil;
import cn.pluss.platform.vo.WxCertInfoVO;
import cn.pluss.platform.wx.WxCertService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author DJH
 */
@RequestMapping("/wxCert")
@RestController
public class WxCertController {

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private UserAppService userAppService;

    @Autowired
    private WxCertService wxCertService;

    /**
     * 获取所有微信认证信息、包含D0、D1
     * @return  微信认证信息
     */
    @GetMapping("/wxCertInfoList")
    public Result<List<WxCertInfoVO>> getWxCertInfoList() {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        List<WxCertInfoVO> result = wxCertService.wxCertInfo(tokenUa.getUserId() + "");
        return ResultGenerator.genSuccessResult(result);
    }

    /**
     * 获取所有微信认证信息、包含D0、D1
     * @return  微信认证信息
     */
    @GetMapping("/wxCertInfo")
    public Result<WxCertInfoVO> getWxCertInfo(String channelType) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        WxCertInfoVO result = wxCertService.wxCertInfo(tokenUa.getUserId() + "", channelType);
        return ResultGenerator.genSuccessResult(result);
    }

    @GetMapping("/wxCertGuide")
    public void wxCertGuide(HttpServletResponse response) {
        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setPropertyKey("wxCertGuideUrl");
        SystemConfig one = systemConfigService.getOne(new QueryWrapper<>(systemConfig).last("limit 1"));

        Result<SystemConfig> result = ResultGenerator.genSuccessResult("未配置页面", one);
        if (one == null) {
            ComUtil.responseResult(response, result);
            return;
        }

        try {
            response.sendRedirect(one.getPropertyValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
