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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.netty.util.internal.StringUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

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.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.config.security.utils.SecureUtil;
import org.jeecg.modules.adweb.common.constant.AdwebConstant;
import org.jeecg.modules.adweb.seo.mapper.SeoPlanSubscriptionMapper;
import org.jeecg.modules.adweb.site.dto.param.SiteStepDTO;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.entity.AdwebSitePermission;
import org.jeecg.modules.adweb.site.entity.Sohoeb2bOrder;
import org.jeecg.modules.adweb.site.service.*;
import org.jeecg.modules.adweb.system.service.SysAdwebApi;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: adweb站点配置表单
 * @Author: jeecg-boot
 * @Date: 2024-09-29
 * @Version: V1.0
 */
@Tag(name = "adweb站点配置表单")
@RestController
@RequestMapping("/adweb/adwebSite")
@Slf4j
public class AdwebSiteController extends JeecgController<AdwebSite, IAdwebSiteService> {

    @Resource private IAdwebSiteService adwebSiteService;

    @Resource private SysAdwebApi sysAdwebApi;

    @Resource private ISiteUserPermissionService siteUserPermissionService;

    @Resource private ISitePermissionService sitePermissionService;

    @Resource private SeoPlanSubscriptionMapper seoPlanSubscriptionMapper;

    @Resource private SelfWebSiteService selfWebSiteService;

    @Resource private BaseCommonService baseCommonService;

    @Resource private Sohoeb2bOrderService sohoeb2bOrderService;

    /**
     * 分页列表查询
     *
     * @param adwebSite
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    // @AutoLog(value = "adweb站点配置表单-分页列表查询")
    @Operation(summary = "adweb站点配置表单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<AdwebSite>> queryPageList(
            AdwebSite adwebSite,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        QueryWrapper<AdwebSite> queryWrapper =
                QueryGenerator.initQueryWrapper(adwebSite, req.getParameterMap());

        Page<AdwebSite> page = new Page<AdwebSite>(pageNo, pageSize);

        // 处理多租户过滤站点列表
        processTenantFilter(queryWrapper.lambda());

        IPage<AdwebSite> pageList = adwebSiteService.page(page, queryWrapper);

        // 给站点增加营销计划信息
        List<AdwebSite> siteList = pageList.getRecords();
        for (AdwebSite site : siteList) {
            Map<String, String> marketPlan =
                    seoPlanSubscriptionMapper.getSubscribePlanBySiteId(site.getId());
            JSONObject object =
                    FastJsonUtil.parseObject(
                            FastJsonUtil.toJSONString(marketPlan), JSONObject.class);
            site.setSubscribePlan(object);

            // 设置建站进度
            if (site.getSiteFlowStatus() == null) {
                site.setCompleteProcess(0);
            } else {
                site.setCompleteProcess(site.getSiteFlowStatus() * 100 / 6);
            }

            // 处理域名，全部改为绝对路径
            String domain = site.getDomain();
            if (StringUtils.isNotBlank(domain) && !domain.startsWith("http")) {
                site.setDomain("https://" + domain);
            }

            // TODO权限验证
            Sohoeb2bOrder sohoeb2bOrder = sohoeb2bOrderService.getBySiteCode(adwebSite.getCode());
            if (sohoeb2bOrder != null) {
                adwebSite.setOrderUrl(sohoeb2bOrder.getOrderUrl());
                adwebSite.setOrderUrlID(String.valueOf(sohoeb2bOrder.getId()));
            }
        }

        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param adwebSite
     * @return
     */
    @AutoLog(value = "adweb站点配置表单-添加")
    @Operation(summary = "adweb站点配置表单-添加")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_site:add')")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody AdwebSite adwebSite) {
        adwebSiteService.save(adwebSite);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param adwebSite
     * @return
     */
    @AutoLog(value = "adweb站点配置表单-编辑")
    @Operation(summary = "adweb站点配置表单-编辑")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_site:edit')")
    @RequestMapping(
            value = "/edit",
            method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody AdwebSite adwebSite) {
        adwebSiteService.updateById(adwebSite);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adweb站点配置表单-通过id删除")
    @Operation(summary = "adweb站点配置表单-通过id删除")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_site:delete')")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        AdwebSite adwebSite = adwebSiteService.getById(id);

        // 删除站点权限
        LambdaQueryWrapper<AdwebSitePermission> queryWrapper =
                new LambdaQueryWrapper<AdwebSitePermission>();
        queryWrapper.eq(AdwebSitePermission::getSiteCode, adwebSite.getCode());
        sitePermissionService.remove(queryWrapper);

        // 远程删除并备份站点资源
        LoginUser user = SecureUtil.currentUser();
        selfWebSiteService.removeSite(user, adwebSite);

        // 删除该站点数据
        adwebSiteService.removeById(id);

        // 记录删除站点操作日志
        baseCommonService.addLog(
                "站点" + adwebSite.getDomain() + "资源已被删除，将在服务器自动备份15天，之后将自动清空:",
                CommonConstant.LOG_TYPE_2,
                3);

        return Result.ok("该站点资源已经不存在, 站点信息将从系统中删除!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "adweb站点配置表单-批量删除")
    @Operation(summary = "adweb站点配置表单-批量删除")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_site:deleteBatch')")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.adwebSiteService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    // @AutoLog(value = "adweb站点配置表单-通过id查询")
    @Operation(summary = "adweb站点配置表单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<AdwebSite> queryById(@RequestParam(name = "id", required = true) String id) {
        AdwebSite adwebSite = adwebSiteService.getById(id);
        if (adwebSite == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(adwebSite);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adwebSite
     */
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_site:exportXls')")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdwebSite adwebSite) {
        return super.exportXls(request, adwebSite, AdwebSite.class, "adweb站点配置表单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_site:importExcel')")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AdwebSite.class);
    }

    /** 根据uid获取所属一级站点信息 "id", "name", "code", "domain","domain_dev","status" */
    @GetMapping("/getSiteListByUid")
    public Result<?> getAllSites() {
        LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();
        // 处理多租户过滤站点列表
        processTenantFilter(queryWrapper);

        queryWrapper
                .ne(AdwebSite::getStatus, AdwebConstant.SITE_DEL)
                .isNull(AdwebSite::getParentGroupCode);
        queryWrapper.select(
                AdwebSite::getId,
                AdwebSite::getName,
                AdwebSite::getCode,
                AdwebSite::getDomain,
                AdwebSite::getDomainDev,
                AdwebSite::getStatus);
        List<AdwebSite> siteList = adwebSiteService.list(queryWrapper);

        // 处理域名，全部改为绝对路径
        if (CollectionUtils.isNotEmpty(siteList)) {
            for (AdwebSite site : siteList) {
                String domain = site.getDomain();
                if (StringUtil.isNullOrEmpty(domain)) {
                    continue;
                }
                if (!domain.startsWith("http")) {
                    site.setDomain("https://" + domain);
                }
            }
        }

        return Result.ok(siteList);
    }

    /**
     * 更新site表现阶段
     *
     * @param siteStepDTO @Author: 陈培庆 @Date: 2024/11/26
     */
    @RequestMapping(value = "/finishOrRollbackStep")
    public Result<?> finishOrRollbackStep(SiteStepDTO siteStepDTO) {

        // 更新流程步骤和状态
        LambdaUpdateWrapper<AdwebSite> siteUpdateWrapper = new LambdaUpdateWrapper<>();
        siteUpdateWrapper.eq(AdwebSite::getCode, siteStepDTO.getSiteCode());

        // 建站流程
        siteUpdateWrapper
                .set(AdwebSite::getSiteCurrentStep, siteStepDTO.getCurrentStep())
                .set(AdwebSite::getSiteFlowStatus, siteStepDTO.getStepFlowId());

        adwebSiteService.update(siteUpdateWrapper);
        return Result.OK();
    }

    private void processTenantFilter(LambdaQueryWrapper<AdwebSite> queryWrapper) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 对于非管理员进行租户隔离
        if (sysAdwebApi.isAdmin()) {

        } else if (sysAdwebApi.isChannelAdmin()) {
            List<String> channelGroupUids = sysAdwebApi.getChannelGroupUids();
            List<String> codeList =
                    siteUserPermissionService.getSiteCodeListByUids(channelGroupUids);
            queryWrapper.in(AdwebSite::getCode, codeList);
        } else {
            List<String> codeList = siteUserPermissionService.getSiteCodeList(sysUser.getId());
            queryWrapper.in(AdwebSite::getCode, codeList);
        }
    }
}
