package org.jeecg.modules.adweb.site.controller;

import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.config.security.utils.SecureUtil;
import org.jeecg.modules.adweb.common.mapper.CommonMapper;
import org.jeecg.modules.adweb.common.util.DateUtil;
import org.jeecg.modules.adweb.site.dto.WordPressConfig;
import org.jeecg.modules.adweb.site.dto.result.SiteBasicInfo;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.entity.Sohoeb2bOrder;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.site.service.ISiteUserPermissionService;
import org.jeecg.modules.adweb.site.service.SiteManageService;
import org.jeecg.modules.adweb.site.service.Sohoeb2bOrderService;
import org.jeecg.modules.adweb.system.service.SysAdwebApi;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserTenant;
import org.jeecg.modules.system.service.ISysUserTenantService;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: adweb_site
 * @Author: jeecg-boot
 * @Date: 2020-12-24
 * @Version: V1.0
 */
@Tag(name = "adweb站点配置表单")
@RestController
@RequestMapping("/adweb/adwebSiteManage")
@Slf4j
public class AdwebSiteManageController extends JeecgController<AdwebSite, IAdwebSiteService> {

    @Lazy @Resource private IAdwebSiteService adwebSiteManageService;

    @Resource private CommonMapper commonMapper;

    @Resource private SiteManageService siteManageService;

    @Resource private SysAdwebApi sysAdwebApi;

    @Resource private ISysUserTenantService sysUserTenantService;

    @Resource private ISiteUserPermissionService siteUserPermissionService;

    @Resource private Sohoeb2bOrderService sohoeb2bOrderService;

    /**
     * 查询wordpress站点配置
     *
     * @param wordPressConfig
     * @return
     */
    @PostMapping(value = "/queryWordPressConfig")
    public Result<?> queryWordPressConfig(@RequestBody WordPressConfig wordPressConfig) {
        // 嵌入站点访问之前先验证是否具有访问权限
        if (!validateSiteCode(wordPressConfig.getSiteCode())) {
            return Result.noauth("您没有权限访问该站点");
        }

        WordPressConfig config =
                this.adwebSiteManageService.queryWordPressConfig(wordPressConfig.getSiteCode());
        return Result.OK(config);
    }

    @GetMapping(value = "/getAdwebVip")
    public Result<?> getAdwebVip() {
        List<SysUser> userList = commonMapper.getAdwebVip();

        // 对于非管理员进行租户隔离
        if (!sysAdwebApi.isAdmin()) {
            LoginUser user = SecureUtil.currentUser();
            // 如果是渠道管理员，则返回渠道下所有adwebVIP用户
            // 而对于普通adwebVIP用户，只返回该用户自己
            if (sysAdwebApi.isChannelAdmin()) {
                LambdaUpdateWrapper<SysUserTenant> queryWrapper = new LambdaUpdateWrapper<>();
                queryWrapper.in(SysUserTenant::getTenantId, user.getRelTenantIds());

                // 查询出和登录用户具有相同租户的userID
                List<SysUserTenant> sysUserTenants =
                        sysUserTenantService.getBaseMapper().selectList(queryWrapper);
                List<String> userIds;

                if (sysUserTenants != null) {
                    userIds = sysUserTenants.stream().map(SysUserTenant::getUserId).toList();
                } else {
                    userIds = new ArrayList<>();
                }

                // 对查出的adwebVIP 用户进行租户过滤, 并将自己加入到返回结果中
                List<SysUser> filterUserList = new ArrayList<>();
                filterUserList =
                        userList.stream()
                                .filter(sysUser -> userIds.contains(sysUser.getId()))
                                .collect(Collectors.toList());
                SysUser currentUser = new SysUser();
                BeanUtil.copyProperties(user, currentUser);
                filterUserList.add(currentUser);

                return Result.ok(filterUserList);
            } else {
                // 对查出的 adwebVIP 用户进行租户过滤
                return Result.ok(
                        userList.stream()
                                .filter(sysUser -> sysUser.getId().equals(user.getId()))
                                .collect(Collectors.toList()));
            }
        }

        return Result.OK(userList);
    }

    /** 获得综合统计信息 */
    @AutoLog(value = "首页仪表盘综合统计信息")
    @GetMapping(value = "/siteBasicInfo")
    public Result<?> getSiteBasicInfo(String siteCode) {
        if (siteCode == null) {
            log.info("缺少用户siteCode参数");
            return Result.error("lack parameter : siteCode");
        }
        SiteBasicInfo basicInfo = siteManageService.getSiteBasicInfo(siteCode);
        return Result.OK(basicInfo);
    }

    @PostMapping(value = "/setEnquiryEmailListBySiteCode")
    public Result<?> setEnquiryEmailListBySiteCode(
            String siteCode, String companyName, @RequestParam List<String> emailList) {

        if (StringUtils.isBlank(siteCode)) {
            return Result.error("参数错误");
        }

        // 判断emailList是否存在重复
        if (emailList.size() != new HashSet<>(emailList).size()) {
            return Result.error("邮箱列表存在重复");
        }

        // 去除邮箱前后空格
        emailList.replaceAll(String::trim);

        int count =
                (int)
                        adwebSiteManageService.count(
                                new LambdaQueryWrapper<AdwebSite>()
                                        .eq(AdwebSite::getCode, siteCode));
        if (count == 0) {
            return Result.error("站点不存在");
        }

        log.info("设置站点询盘邮箱列表，站点code：{}，邮箱列表：{}", siteCode, emailList);

        boolean update =
                adwebSiteManageService.update(
                        new LambdaUpdateWrapper<AdwebSite>()
                                .set(AdwebSite::getCompanyName, companyName)
                                .set(
                                        AdwebSite::getEnquiryEmailList,
                                        CollectionUtils.isEmpty(emailList)
                                                ? null
                                                : JSON.toJSONString(emailList))
                                .eq(AdwebSite::getCode, siteCode));

        return update ? Result.OK("设置成功") : Result.error("设置失败");
    }

    /**
     * 设置订单url
     *
     * @param sohoeb2bOrder
     * @return
     */
    @PostMapping(value = "/set/order/url")
    public Result<?> setOrderUrl(@RequestBody Sohoeb2bOrder sohoeb2bOrder) {

        if (StringUtils.isBlank(sohoeb2bOrder.getOrderUrl())
                || StringUtils.isBlank(sohoeb2bOrder.getDomainName())
                || StringUtils.isBlank(sohoeb2bOrder.getSiteCode())) {
            return Result.error("参数不完整，请重试！");
        }

        String newDomainName =
                sohoeb2bOrder.getDomainName().replace("http://", "").replace("https://", "");
        sohoeb2bOrder.setDomainName(newDomainName);
        if (sohoeb2bOrder.getId() != null) {
            sohoeb2bOrderService.update(sohoeb2bOrder);
        } else {
            sohoeb2bOrderService.insert(sohoeb2bOrder);
        }
        return Result.OK("操作成功！");
    }

    /**
     * 订单数据配置及站点信息
     *
     * @param siteCode
     * @return
     */
    @GetMapping(value = "/getSiteOrderInfo")
    public Result<?> getSiteOrderInfo(String siteCode) {
        log.info("siteCode:{}", siteCode);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        log.info("loginUser:{}", loginUser);

        Map<String, Object> resultMap = new HashMap<>();
        Sohoeb2bOrder siteOrderPost = sohoeb2bOrderService.getBySiteCode(siteCode);
        log.info("siteOrderPost:{}", siteOrderPost);
        if (siteOrderPost != null) {
            resultMap.put(
                    "orderUrl",
                    siteOrderPost.getOrderUrl()
                            + "&master="
                            + (adwebSiteManageService.hasSub(loginUser) ? 1 : 0)
                            + "&username="
                            + loginUser.getUsername()
                            + "&time="
                            + DateUtil.getDate().getTime());
            resultMap.put("orderInitUrl", siteOrderPost.getOrderUrl());
            resultMap.put("orderID", siteOrderPost.getId());
            return Result.OK(resultMap);
        }

        return Result.error("站点订单Url未设置！");
    }

    private Boolean validateSiteCode(String code) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        if (sysAdwebApi == null) {
            throw new IllegalStateException("sysAdwebApi is not initialized");
        }

        if (sysAdwebApi.isAdmin()) {
            return true;
        } else if (sysAdwebApi.isChannelAdmin()) {
            List<String> channelGroupUids = sysAdwebApi.getChannelGroupUids();
            if (channelGroupUids == null || channelGroupUids.isEmpty()) {
                return false;
            }

            List<String> codeList =
                    siteUserPermissionService.getSiteCodeListByUids(channelGroupUids);
            if (codeList == null) {
                return false;
            }

            return codeList.contains(code);
        } else {
            List<String> codeList = siteUserPermissionService.getSiteCodeList(sysUser.getId());
            if (codeList == null) {
                return false;
            }

            return codeList.contains(code);
        }
    }
}
