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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
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.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.adweb.common.constant.AdwebConstant;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.site.service.ISiteUserPermissionService;
import org.jeecg.modules.adweb.system.service.SysAdwebApi;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * @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> {

    @Autowired
    private IAdwebSiteService adwebSiteService;

    @Autowired
    private SysAdwebApi sysAdwebApi;

	@Autowired
	private ISiteUserPermissionService siteUserPermissionService;


    /**
     * 分页列表查询
     *
     * @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);
        IPage<AdwebSite> pageList = adwebSiteService.page(page, queryWrapper);
        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) {
        adwebSiteService.removeById(id);
        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() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
        if (sysAdwebApi.isAdmin()) {

        } else if (sysAdwebApi.isOem()) {
            List<String> oemGroupUids = sysAdwebApi.getOemGroupUids();
            List<String> codeList = siteUserPermissionService.getSiteCodeListByUids(oemGroupUids);
            queryWrapper.in("code", codeList);
        } else {
            List<String> codeList = siteUserPermissionService.getSiteCodeList(sysUser.getId());
            queryWrapper.in("code", codeList);
        }
        queryWrapper.eq("site_type", AdwebConstant.SITE);
        queryWrapper.ne("status", AdwebConstant.SITE_DEL).isNull("parent_group_code");
        queryWrapper.select("id", "name", "code", "domain", "domain_dev", "status");
        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);
    }

}
