package com.sdtool.common.base;

import com.sdtool.common.api.LoginUserService;
import com.sdtool.common.api.PermissionService;
import com.sdtool.common.datas.ERPHeader;
import com.sdtool.common.datas.HttpCode;
import com.sdtool.common.entity.site.ERPTokenUser;
import com.sdtool.common.entity.system.LoginUser;
import com.dySweetFishPlugin.sql.RMapUtils;
import com.sweetfish.net.WorkThread;
import com.sweetfish.net.http.HttpRequest;
import com.sweetfish.net.http.HttpResponse;
import com.sweetfish.net.http.HttpUserType;
import com.sweetfish.util.AutoLoad;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;

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

/**
 * Created by jlutt on 2020-07-28
 * ERP后台使用的servlet基类
 * 管理权限
 *
 * @author jlutt
 */
@AutoLoad(false)
@HttpUserType(ERPTokenUser.class)
@ERPServlet(writeLog = true)
public class PCERPAdminHttpServlet extends BaseHttpServlet {

    @Resource
    LoginUserService userService;

    @Resource
    PermissionService permissionService;

    @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 {
            LoginUser loginUser = userService.getRedisLoginUser(info.getId(), supplierCode);

            if (loginUser == null) {
                response.finishJson(RMapUtils.error(HttpCode.FORBIDDEN.value(), "未登录"));
                return;
            }

            if (loginUser.getStatus() == 1) {
                response.finishJson(RMapUtils.error(HttpCode.FORBIDDEN.value(), "未登录"));
                return;
            }

            if (StringUtils.isNotEmpty(request.getPerms())) {
                int perm = permissionService.ifPermission(info, request.getPerms(), null, dataSourceId, supplierCode);
                if (perm != 1) {
                    if ("/xdoc/index".equalsIgnoreCase(request.getRequestURI())) {
                        File api = new File(webRoot, "apilogin.html");
                        response.finishFile(api, null);
                    } else {
                        response.finishJson(RMapUtils.error(HttpCode.FORBIDDEN.value(), "无操作权限"));
                    }
                    return;
                }
            } else if (request.getModuleid() > 0L) {
                if (!permissionService.checkUserAuth(info,
                        request.getModuleid(),
                        request.getActionid(),
                        dataSourceId,
                        supplierCode)) {
                    //通过moduleid和actionid判断权限
                    if ("/xdoc/index".equalsIgnoreCase(request.getRequestURI())) {
                        File api = new File(webRoot, "apilogin.html");
                        response.finishFile(api, null);
                    } else {
                        response.finishJson(RMapUtils.error(HttpCode.FORBIDDEN.value(), "无操作权限"));
                    }
                    return;
                }
            }
        }
        //验证通过调用执行方法
        response.nextEvent();
    }

    /**
     * 异步执行任务
     *
     * @param runner 异步操作
     */
    protected void submit(Runnable runner) {
        Thread thread = Thread.currentThread();
        if (thread instanceof WorkThread) {
            ((WorkThread) thread).runAsync(runner);
        } else {
            ForkJoinPool.commonPool().execute(runner);
        }
    }

    protected ExecutorService getExecutor() {
        Thread thread = Thread.currentThread();
        if (thread instanceof WorkThread) {
            return ((WorkThread) thread).getExecutor();
        }
        return ForkJoinPool.commonPool();
    }
}
