package com.sdtool.common.base;

import com.sdtool.common.api.LoginService;
import com.sdtool.common.api.mall.MallFrontService;
import com.sdtool.common.datas.ERPHeader;
import com.sdtool.common.datas.HttpCode;
import com.sdtool.common.entity.base.BaseEntity;
import com.sdtool.common.entity.site.ERPTokenUser;
import com.dySweetFishPlugin.sql.RMapUtils;
import com.sweetfish.net.http.HttpRequest;
import com.sweetfish.net.http.HttpResponse;
import com.sweetfish.net.http.HttpUserType;
import com.sweetfish.service.RetResult;
import com.sweetfish.util.AutoLoad;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

import static com.sweetfish.net.Server.RESNAME_SERVER_ROOT;

@AutoLoad(false)
@HttpUserType(ERPTokenUser.class)
@ERPServlet(writeLog = false)
public class PCMallFrontHttpServlet extends BaseHttpServlet {

    @Resource
    MallFrontService mallFrontService;

    @Resource
    LoginService loginService;

    @Resource(name = RESNAME_SERVER_ROOT)
    File webRoot;

    @Override
    protected void authenticate(HttpRequest request, HttpResponse response) throws IOException {
        ERPTokenUser info = request.currentUser();
        long supplierCode = request.getLongHeader(ERPHeader.HTTPHEADER_SUPPLIER, 0);
        String dataSourceId = request.getHeader(ERPHeader.HTTPHEADER_DATASOURCE, "");

        if (info == null) {
            //判断是否登录
            if ("/xdoc/index".equalsIgnoreCase(request.getRequestURI())) {
                File api = new File(webRoot, "apilogin.html");
                response.finishFile(api, null);
            } else {
                response.finishJson(RMapUtils.error(HttpCode.UNAUTHORIZED.value(), "未登录"));
            }
            return;
        } else {
            RetResult<BaseEntity> checkResult = loginService.checkUser(info);
            if (!checkResult.isSuccess()) {
                response.finishJson(RMapUtils.error(HttpCode.UNAUTHORIZED.value(), "未登录"));
                return;
            }
        }
        //验证通过调用执行方法
        response.nextEvent();
    }
}
