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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

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.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;

import org.jeecg.modules.adweb.enquiry.constant.EnquiryDistributeTypeConstant;
import org.jeecg.modules.adweb.enquiry.dto.result.EnquiryListDto;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiry;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiryBlacklist;
import org.jeecg.modules.adweb.enquiry.entity.AdwebSiteBlackEmail;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryBlacklistService;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryService;
import org.jeecg.modules.adweb.enquiry.service.IAdwebSiteBlackEmailService;

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.jeecg.modules.adweb.userCountry.service.IAdwebUserCountryService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: adweb_enquiry_blacklist
 * @Author: jeecg-boot
 * @Date: 2022-08-05
 * @Version: V1.0
 */
@Tag(name = "adweb_enquiry_blacklist")
@RestController
@RequestMapping("/enquiry/blacklist")
@Slf4j
public class AdwebEnquiryBlacklistController extends JeecgController<AdwebEnquiryBlacklist, IAdwebEnquiryBlacklistService> {
    @Resource
    private IAdwebEnquiryBlacklistService adwebEnquiryBlacklistService;

    @Resource
    private IAdwebEnquiryService adwebEnquiryService;

    @Resource
    private ISysBaseAPI sysBaseAPI;

	@Resource
	private SysAdwebApi sysAdwebApi;

    @Resource
    private IAdwebSiteService adwebSiteService;

    @Resource
    private ISiteUserPermissionService siteUserPermissionService;

    @Resource
    private IAdwebSiteBlackEmailService enquirySiteBlackEmailService;

    @Resource
    private IAdwebUserCountryService adwebUserCountryService;

    /**
     * 分页列表查询
     *
     * @param queryParam 查询参数，邮箱/姓名/国家
     */
    @GetMapping(value = "/list")
    public Result<?> queryPageList(String queryParam,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   Integer siteId) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<AdwebEnquiryBlacklist> queryWrapper = new QueryWrapper<>();
        if (siteId != null) {
            List<Integer> siteIds = adwebSiteService.getAllSiteIdByParentId(siteId);
            queryWrapper.in("site_id", siteIds);
        } else if (!sysBaseAPI.isAdmin()) {
            if (sysBaseAPI.isOem()) {
                List<String> oemGroupUids = sysBaseAPI.getOemGroupUids();

                List<String> codeList = siteUserPermissionService.getSiteCodeListByUids(oemGroupUids);
                QueryWrapper<AdwebSite> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.ne("status", 0);
                queryWrapper1.in("code", codeList);
                List<AdwebSite> siteList = adwebSiteService.list(queryWrapper1);
                List<Integer> siteIds = new ArrayList<>();
                for (AdwebSite site : siteList) {
                    siteIds.add(site.getId());
                }
                queryWrapper.in("site_id", siteIds);
            } else {
                List<Integer> siteIds = adwebSiteService.getAllSiteIdByUid(loginUser.getId());
                queryWrapper.in("site_id", siteIds);
            }
        }
        if (StringUtils.isNotBlank(queryParam)) {
            queryWrapper.and(wrapper -> wrapper.like("email", queryParam)
                    .or().like("name", queryParam)
                    .or().like("country_name", queryParam));
        }

        if (sysAdwebApi.isAdwebSubVip()) {
            AdwebSite site = adwebSiteService.getById(siteId);
            String distributeType = site.getEnquiryDistributeType();
            if (EnquiryDistributeTypeConstant.MASTER.equals(distributeType)) {
                return Result.OK(new Page<>(pageNo, pageSize));
            }
            if (EnquiryDistributeTypeConstant.REGION.equals(distributeType)) {
                List<String> countryCodes = adwebUserCountryService.getCountryCodesBySubId(loginUser.getId(), siteId);
                if (CollectionUtils.isEmpty(countryCodes)) {
                    return Result.OK(new Page<>(pageNo, pageSize));
                }
                queryWrapper.in("country_code", countryCodes);
            }
        }

        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("create_time");
        Page<AdwebEnquiryBlacklist> page = new Page<AdwebEnquiryBlacklist>(pageNo, pageSize);
        IPage<AdwebEnquiryBlacklist> pageList = adwebEnquiryBlacklistService.page(page, queryWrapper);
        
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param adwebEnquiryBlacklist
     * @return
     */
    @AutoLog(value = "adweb_enquiry_blacklist-添加")
    @Operation(summary = "adweb_enquiry_blacklist-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AdwebEnquiryBlacklist adwebEnquiryBlacklist) {
        adwebEnquiryBlacklistService.save(adwebEnquiryBlacklist);
        return Result.OK("添加成功！");
    }

    /**
     * 增加黑名单，从询盘中抽取出一个虚拟的人，同时将询盘放入黑名单
     *
     * @param adwebEnquiry 询盘
     * @return 处理结果
     */
    @PostMapping(value = "/addBlacklist")
    public Result<?> addBlacklist(@RequestBody EnquiryListDto adwebEnquiry) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();


        //判断站点询盘黑名单是否存在添加进来的黑名单
        QueryWrapper<AdwebSiteBlackEmail> enquirySiteBlackEmailQueryWrapper = new QueryWrapper<>();
        enquirySiteBlackEmailQueryWrapper.eq("site_id", adwebEnquiry.getSiteId());
        enquirySiteBlackEmailQueryWrapper.eq("status", 1);
        enquirySiteBlackEmailQueryWrapper.eq("email", adwebEnquiry.getFromEmail());
        List<AdwebSiteBlackEmail> enquirySiteBlackEmailList = enquirySiteBlackEmailService.list(enquirySiteBlackEmailQueryWrapper);

        if (CollectionUtils.isNotEmpty(enquirySiteBlackEmailList)) {
            Integer blackOrWhite = enquirySiteBlackEmailList.get(0).getBlackOrWhite();
            String blackOrWhiteStr = "";
            if (blackOrWhite == 0) {
                blackOrWhiteStr = "黑名单";
            } else {
                blackOrWhiteStr = "白名单";
            }
            return Result.error("当前拒收的邮箱黑名单已被站点询盘黑名单记录为" + blackOrWhiteStr);
        }
        AdwebEnquiryBlacklist blacklist = new AdwebEnquiryBlacklist();
        blacklist.setSiteId(adwebEnquiry.getSiteId());
        blacklist.setEnquiryId(adwebEnquiry.getId());
        blacklist.setName(adwebEnquiry.getContact());
        blacklist.setEmail(adwebEnquiry.getFromEmail());
        blacklist.setPhone(adwebEnquiry.getPhone());
        blacklist.setWhatsapp(adwebEnquiry.getWhatsApp());
        blacklist.setCountryCode(adwebEnquiry.getCountryCode());
        blacklist.setCountryName(adwebEnquiry.getCountryName());
        blacklist.setStatus(1);
        blacklist.setCreateTime(new Date());
        adwebEnquiryBlacklistService.save(blacklist);

        UpdateWrapper<AdwebEnquiry> enquiryUpdateWrapper = new UpdateWrapper<>();
        enquiryUpdateWrapper.eq("id", adwebEnquiry.getId());
        enquiryUpdateWrapper.set("status", 0);
        adwebEnquiryService.update(enquiryUpdateWrapper);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param adwebEnquiryBlacklist
     * @return
     */
    @AutoLog(value = "adweb_enquiry_blacklist-编辑")
	@Operation(summary = "adweb_enquiry_blacklist-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AdwebEnquiryBlacklist adwebEnquiryBlacklist) {
        adwebEnquiryBlacklistService.updateById(adwebEnquiryBlacklist);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adweb_enquiry_blacklist-通过id删除")
	@Operation(summary = "adweb_enquiry_blacklist-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        adwebEnquiryBlacklistService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 移出黑名单
     *
     * @param id 黑名单id
     * @return 操作结果
     */
    @GetMapping(value = "/removeBlacklist")
    public Result<?> removeBlacklist(@RequestParam(name = "id") String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        UpdateWrapper<AdwebEnquiryBlacklist> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", id.split(","));
        updateWrapper.set("status", 0);
        adwebEnquiryBlacklistService.update(updateWrapper);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "adweb_enquiry_blacklist-批量删除")
	@Operation(summary = "adweb_enquiry_blacklist-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.adwebEnquiryBlacklistService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "adweb_enquiry_blacklist-通过id查询")
	@Operation(summary = "adweb_enquiry_blacklist-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AdwebEnquiryBlacklist adwebEnquiryBlacklist = adwebEnquiryBlacklistService.getById(id);
        if (adwebEnquiryBlacklist == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(adwebEnquiryBlacklist);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adwebEnquiryBlacklist
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdwebEnquiryBlacklist adwebEnquiryBlacklist) {
        return super.exportXls(request, adwebEnquiryBlacklist, AdwebEnquiryBlacklist.class, "adweb_enquiry_blacklist");
    }

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

}
