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

import java.util.Arrays;

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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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 lombok.extern.slf4j.Slf4j;

/**
 * @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, defaultValue = "defualt") String tenantId, String utmSource) {
        if (!containsAppName(appName)) {
            throw new DataException("appName不合法");
        }

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

	private boolean containsAppName(String appName) {
		return Arrays.asList(appletAppNames.split(",")).contains(appName);
	}
}
