package com.bcxin.sync.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import com.bcxin.sync.common.emus.AuthType;
import com.bcxin.sync.common.emus.PageType;
import com.bcxin.sync.common.exception.GetResponseException;
import com.bcxin.sync.common.utils.HttpUtil;
import com.bcxin.sync.common.utils.TokenUtils;
import com.bcxin.sync.configs.SyncConfig;
import com.bcxin.sync.entity.datasync.ThirdPageSettingEntity;
import com.bcxin.sync.entity.tenant.ExternalMembersEntity;
import com.bcxin.sync.entity.tenant.TenantEmployeesEntity;
import com.bcxin.sync.entity.tenant.TlkEventProjectEntity;
import com.bcxin.sync.service.datasync.ThirdPageSettingService;
import com.bcxin.sync.service.tenant.ExternalMembersService;
import com.bcxin.sync.service.tenant.TenantEmployeesService;
import com.bcxin.sync.service.tenant.TlkEventManagerService;
import com.bcxin.sync.service.tenant.TlkEventProjectService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * description：第三方资源访问控制器
 * author：linchunpeng
 * date：2025/4/8
 */
@Slf4j
@Controller
public class ThirdResourceController {

    @Autowired
    private ExternalMembersService externalMembersService;
    @Autowired
    private TenantEmployeesService tenantEmployeesService;
    @Autowired
    private TlkEventProjectService tlkEventProjectService;
    @Autowired
    private TlkEventManagerService tlkEventManagerService;
    @Autowired
    private ThirdPageSettingService thirdPageSettingService;
    @Autowired
    private SyncConfig syncConfig;


    @GetMapping("/api/third/page/project/{pageId}/{pageType}")
    public String projectPage(@PathVariable("pageId") String pageId, @PathVariable("pageType") Integer pageType,
                              Integer download, HttpServletRequest request){
        log.info("访问第三方页面，页面id：{}", pageId);
        Object empIdObject = request.getAttribute("empId");
        if (empIdObject == null) {
            throw new GetResponseException(401, "页面未授权.");
        }
        String employeeId = empIdObject.toString();
        Object orgIdObject = request.getAttribute("orgId");
        if (orgIdObject == null) {
            throw new GetResponseException(401, "页面未授权..");
        }
        String orgId = orgIdObject.toString();
        log.info("职员id：{}， 组织id：{}", employeeId, orgId);

        ThirdPageSettingEntity thirdPageSetting = thirdPageSettingService.getByPageIdAndPageType(pageId, pageType);
        if (thirdPageSetting == null) {
            throw new GetResponseException(404, "页面不存在.");
        }
        if (thirdPageSetting.getStatus() == 0) {
            throw new GetResponseException(403, "页面禁止访问.");
        }
        boolean isAuth = false;
        //判断是不是活动承办方的组织管理员
        TlkEventProjectEntity project = tlkEventProjectService.getById(pageId);
        if (project == null) {
            throw new GetResponseException(404, "页面不存在..");
        }
        if (tenantEmployeesService.isAdminByOrgIdAndEmployeeId(project.getItemDomainId(), employeeId)) {
            isAuth = true;
        }
        if (!isAuth && externalMembersService.isAdminByOrgIdAndEmployeeId(project.getItemDomainId(), employeeId)) {
            isAuth = true;
        }
        //判断是不是项目的负责人
        if (!isAuth && tlkEventManagerService.isManagerByProjectIdAndEmployeeId(pageId, employeeId)) {
            isAuth = true;
        }
        if (!isAuth) {
            //最后再来查询指定授权
            if (thirdPageSetting.getAuthType() == AuthType.PUBLICITY.getCode()) {
                //公开访问
                isAuth = true;
            } else if (thirdPageSetting.getAuthType() == AuthType.ORG.getCode()) {
                //指定公司
                if (StringUtils.isNotBlank(thirdPageSetting.getAuthOrgIds()) && thirdPageSetting.getAuthOrgIds().contains(orgId)) {
                    isAuth = true;
                }
            } else if (thirdPageSetting.getAuthType() == AuthType.EMP.getCode()) {
                //指定职员
                if (StringUtils.isNotBlank(thirdPageSetting.getAuthEmpIds()) && thirdPageSetting.getAuthEmpIds().contains(employeeId)) {
                    isAuth = true;
                }
            } else if (thirdPageSetting.getAuthType() == AuthType.ORG_EMP.getCode()) {
                //指定公司和职员
                if (StringUtils.isNotBlank(thirdPageSetting.getAuthOrgIds()) && thirdPageSetting.getAuthOrgIds().contains(orgId)) {
                    isAuth = true;
                } else if (StringUtils.isNotBlank(thirdPageSetting.getAuthEmpIds()) && thirdPageSetting.getAuthEmpIds().contains(employeeId)) {
                    isAuth = true;
                }
            }
        }
        if (!isAuth) {
            throw new GetResponseException(403, "页面禁止访问..");
        }
        String url = "";
        try {
            url = "redirect:" + syncConfig.getApiHost().getSelf()
                    .concat("/api/third/page/").concat(URLEncoder.encode(thirdPageSetting.getEncodeId(), StandardCharsets.UTF_8.toString()))
                    .concat("?Accesstoken=").concat(TokenUtils.getBcxToken(request))
                    .concat("&pageId=").concat(pageId);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (download != null) {
            url = url.concat("&download=").concat(download.toString());
        }
        return url;
    }

    @ResponseBody
    @GetMapping("/api/third/page/{encodeId}")
    public ResponseEntity page(@PathVariable("encodeId") String encodeId, String pageId, Integer download, HttpServletRequest request){
        log.info("访问第三方页面，页面加密id：{}", encodeId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        try {
            Object empIdObject = request.getAttribute("empId");
            if (empIdObject == null) {
                throw new GetResponseException(401, "页面未授权.");
            }
            String employeeId = empIdObject.toString();
            Object orgIdObject = request.getAttribute("orgId");
            if (orgIdObject == null) {
                throw new GetResponseException(401, "页面未授权..");
            }
            String orgId = orgIdObject.toString();
            log.info("职员id：{}， 组织id：{}", employeeId, orgId);

            ThirdPageSettingEntity thirdPageSetting = thirdPageSettingService.getByPageIdAndEncodeId(pageId, encodeId);
            if (thirdPageSetting == null) {
                throw new GetResponseException(404, "页面不存在.");
            }
            if (thirdPageSetting.getStatus() == 0) {
                throw new GetResponseException(403, "页面禁止访问.");
            }
            boolean isAuth = false;
            //判断是不是活动承办方的组织管理员
            TlkEventProjectEntity project = tlkEventProjectService.getById(thirdPageSetting.getPageId());
            if (project == null) {
                throw new GetResponseException(404, "页面不存在..");
            }
            if (tenantEmployeesService.isAdminByOrgIdAndEmployeeId(project.getItemDomainId(), employeeId)) {
                isAuth = true;
            }
            if (!isAuth && externalMembersService.isAdminByOrgIdAndEmployeeId(project.getItemDomainId(), employeeId)) {
                isAuth = true;
            }
            //判断是不是项目的负责人
            if (!isAuth && tlkEventManagerService.isManagerByProjectIdAndEmployeeId(thirdPageSetting.getPageId(), employeeId)) {
                isAuth = true;
            }
            if (!isAuth) {
                //最后再来查询指定授权
                if (thirdPageSetting.getAuthType() == AuthType.PUBLICITY.getCode()) {
                    //公开访问
                    isAuth = true;
                } else if (thirdPageSetting.getAuthType() == AuthType.ORG.getCode()) {
                    //指定公司
                    if (StringUtils.isNotBlank(thirdPageSetting.getAuthOrgIds()) && thirdPageSetting.getAuthOrgIds().contains(orgId)) {
                        isAuth = true;
                    }
                } else if (thirdPageSetting.getAuthType() == AuthType.EMP.getCode()) {
                    //指定职员
                    if (StringUtils.isNotBlank(thirdPageSetting.getAuthEmpIds()) && thirdPageSetting.getAuthEmpIds().contains(employeeId)) {
                        isAuth = true;
                    }
                } else if (thirdPageSetting.getAuthType() == AuthType.ORG_EMP.getCode()) {
                    //指定公司和职员
                    if (StringUtils.isNotBlank(thirdPageSetting.getAuthOrgIds()) && thirdPageSetting.getAuthOrgIds().contains(orgId)) {
                        isAuth = true;
                    } else if (StringUtils.isNotBlank(thirdPageSetting.getAuthEmpIds()) && thirdPageSetting.getAuthEmpIds().contains(employeeId)) {
                        isAuth = true;
                    }
                }
            }
            if (!isAuth) {
                throw new GetResponseException(403, "页面禁止访问..");
            }
            if (thirdPageSetting.getPageType() == PageType.SY3D.getCode()) {
                InputStream inputStream = URLUtil.getStream(new URL(thirdPageSetting.getPageOriginalUrl()));
                String content = IoUtil.read(inputStream, "UTF-8");
                content = content.replace("./", thirdPageSetting.getPageOriginalUrl().substring(0, thirdPageSetting.getPageOriginalUrl().lastIndexOf("/")+1));
                inputStream.close();
                headers.setContentType(MediaType.TEXT_HTML);
                return new ResponseEntity<>(content, headers, HttpStatus.OK);
            }
            if (thirdPageSetting.getPageType() == PageType.FPBG.getCode()) {
                String content = HttpUtil.get(syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/pdfjs/web/viewer.html", new HashMap<>(), true);
                content = content.replace("request(\"path\")", String.format("'%s'", thirdPageSetting.getPageOriginalUrl()))
                        .replace("request(\"_x\")", "'1'")
                        .replace("viewer.css", syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/pdfjs/web/viewer.css")
                        .replace("<script src=\"../../l10n.js\"></script>", "<script src=\"../../l10n.js\"></script><script src=\""+syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/pdfjs/build/pdf.worker.js\"></script>")
                        .replace("../../l10n.js", syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/l10n.js")
                        .replace("../../require.config.js", syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/require.config.js")
                        .replace("../build/pdf.js", syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/pdfjs/build/pdf.js")
                        .replace("../../../../../good/js/word/jquery.min.js", syncConfig.getApiHost().getV5()+"/static/portal/good/js/word/jquery.min.js")
                        .replace("../../../../../good/js/word/watermark.js", syncConfig.getApiHost().getV5()+"/static/portal/good/js/word/watermark.js")
                        .replace("viewer.js", syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/pdfjs/web/viewer.js")
                        .replace("locale/locale.properties", syncConfig.getApiHost().getV5()+"/static/portal/vue/pdf/word/pdfjs/web/locale/locale.properties");
                headers.setContentType(MediaType.TEXT_HTML);
                return new ResponseEntity<>(content, headers, HttpStatus.OK);
            }
            throw new GetResponseException(404, "页面不存在...");
        } catch (GetResponseException e) {
            log.error("访问第三方页面，页面加密id：{}，报错，{}", encodeId, e.getMessage(), e);
            throw new GetResponseException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("访问第三方页面，页面加密id：{}，报错，{}", encodeId, e.getMessage(), e);
            throw new GetResponseException(500, e.getMessage());
        }
    }

}
