package cn.quantgroup.xyqb.controller.middleoffice.applet;

import cn.quantgroup.xyqb.controller.middleoffice.login.ILoginModule;
import cn.quantgroup.xyqb.controller.middleoffice.login.LoginVo;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
import cn.quantgroup.xyqb.exception.DataException;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.middleoffice.applet.IAppletService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * @author ：dongjianhua
 * @date ：Created in 2020/5/27 17:24
 * @description：小程序控制器
 * @modified By：
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/middle_office/applet")
public class AppletController {

	@Value("${applet.appNames:luckii,xyqb,wuxi,yangxiaomie}")
	private String appletAppNames;
    //先这么干 多了的话建表去存
//    private static final List<String> appNames = Lists.newArrayList("luckii", "xyqb", "wuxi");
    private final IAppletService iAppletService;
    private ILoginModule loginModule;

    @Autowired
    AppletController(IAppletService iAppletService,
                     ILoginModule loginModule
    ) {
        this.iAppletService = iAppletService;
        this.loginModule = loginModule;
    }

    /**
     * @return
     */
    @PostMapping("/relevance")
    public JsonResult relevance(@Validated @RequestBody AppletParamEntry appletParamEntry) {
        if (!containsAppName(appletParamEntry.getAppName())) {
            throw new DataException("appName不合法");
        }
        Long userId = iAppletService.relevance(appletParamEntry);

        LoginVo loginVo = loginModule.loginByUserId(appletParamEntry.getChannelId(),
                appletParamEntry.getUtmSource(), userId, null);

        return JsonResult
                .buildSuccessResultGeneric(loginVo);
    }

    /**
     * @return
     */
    @Validated
    @PostMapping("/login")
    public JsonResult login(@RequestParam String appName, @RequestParam String openId, @RequestParam(required = false) Integer tenantId, String utmSource, @RequestParam(required = false) Integer appNo, @RequestParam(required = false) String unionId) {
        if (!containsAppName(appName)) {
            throw new DataException("appName不合法");
        }

        LoginVo login = iAppletService.login(appName, openId, tenantId, utmSource, unionId);
        return JsonResult.buildSuccessResultGeneric(login);
    }

	private boolean containsAppName(String appName) {
        log.info("=appName -> {}", JSON.toJSONString(appName));
        log.info("=appNameApplet -> {}", JSON.toJSONString(appletAppNames));
        return Arrays.asList(appletAppNames.split(",")).contains(appName);
	}
}
