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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.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.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.ibatis.annotations.Param;
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.DictModel;
import org.jeecg.common.system.vo.DictPropertyModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.adweb.common.constant.AdwebConstant;
import org.jeecg.modules.adweb.common.util.AwsTranslateUtils;
import org.jeecg.modules.adweb.common.util.DateUtil;
import org.jeecg.modules.adweb.enquiry.constant.EnquirySendStatus;
import org.jeecg.modules.adweb.enquiry.dto.param.EffectiveEnquiryParamDto;
import org.jeecg.modules.adweb.enquiry.dto.param.EnquiryListSearchDto;
import org.jeecg.modules.adweb.enquiry.dto.param.EnquirySearchDto;
import org.jeecg.modules.adweb.enquiry.dto.result.EnquiryListDto;
import org.jeecg.modules.adweb.enquiry.dto.result.EnquirySpecialFields;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiry;
import org.jeecg.modules.adweb.enquiry.entity.EnquiryEmailMessage;
import org.jeecg.modules.adweb.enquiry.mapper.AdwebEnquiryMapper;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryService;
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.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description: 询盘信息存储表单
 * @Author: jeecg-boot
 * @Date: 2024-10-12
 * @Version: V1.0
 */
@Tag(name = "询盘信息存储表单")
@RestController
@RequestMapping("/adweb/adwebEnquiry")
@Slf4j
public class AdwebEnquiryController extends JeecgController<AdwebEnquiry, IAdwebEnquiryService> {

    @Value("${enquiry.disable-admin-read:true}")
    private Boolean disableAdminRead;
    @Value("${enquiry.demoFlag:false}")
    private Boolean demoFlag;
    @Value("${jeecg.path.upload}")
    private String uploadUrl;
    @Value("${enquiry.token}")
    private String enquiryToken;

    @Resource
    private IAdwebEnquiryService adwebEnquiryService;

    @Resource
    private AdwebEnquiryMapper adwebEnquiryMapper;

    @Resource
    private SysAdwebApi sysAdwebApi;

    @Resource
    private IAdwebSiteService adwebSiteService;

    @Resource
    private ISiteUserPermissionService siteUserPermissionService;

    @Resource
    private ISysDictService sysDictService;

    @Resource
    private AwsTranslateUtils awsTranslateUtils;

    @Resource
    private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param searchDto
     * @param pageNo
     * @param pageSize
     * @param principalUid
     * @return
     */
    //@AutoLog(value = "询盘信息存储表单-分页列表查询")
    @Operation(summary = "询盘信息存储表单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(EnquiryListSearchDto searchDto,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   String principalUid) {

        if (sysAdwebApi.isNotOwnSite(searchDto.getSiteId())) {
            return Result.OK(new Page<>());
        }

        Page<EnquirySearchDto> page = new Page<> (pageNo, pageSize);
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		List<String> codeList = null;
        List<String> uidList = null;

        if (sysAdwebApi.isAdmin()) {

        } else if (sysAdwebApi.isOem()) {
            uidList = sysAdwebApi.getOemGroupUids();
        } else {
            uidList = new ArrayList<>();
            uidList.add(sysUser.getId());
        }
        List<String> siteCodeList = null;
        if (CollectionUtils.isNotEmpty(uidList)) {
            siteCodeList = siteUserPermissionService.getSiteCodeListByUids(uidList);
        }

        if (searchDto.getSiteId() != null) {
            String siteCode = adwebSiteService.getSiteCodeById(searchDto.getSiteId());
            if (StringUtils.isNotBlank(siteCode)) {
                QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", searchDto.getSiteId()).or().eq("parent_group_code", siteCode);
                queryWrapper.ne("status", 0);
                queryWrapper.in(!sysAdwebApi.isAdmin(), "code", siteCodeList);
                codeList = adwebSiteService.list(queryWrapper).stream().map(AdwebSite::getCode).collect(Collectors.toList());
            }
        } else {
            codeList = siteCodeList;
        }


		String dateType = searchDto.getDateType();
		Date start = searchDto.getStart();
		Date end = searchDto.getEnd();
		if (StringUtils.isNotBlank(dateType)) {
			Pair<Date, Date> dateRange = DateUtil.getDateRangeByType(dateType);
			start = dateRange.getLeft();
			end = dateRange.getRight();
		} else {
			if (end != null) {
				end = DateUtil.addDays(end, 1);
			}
		}
		if(CollectionUtils.isEmpty(codeList)){
			return Result.OK(page);
		}

		String selfPrincipalUid = null;
		if (sysAdwebApi.isAdwebSubVip()) {
			selfPrincipalUid = sysUser.getId();
		}

		String userEfftecive = "(" + searchDto.getUserEffective() + ")";


        IPage<EnquiryListDto> pageList = adwebEnquiryMapper.selectAdmpEnquiryList(page, codeList, userEfftecive, searchDto.getWasteEnquiryType(),
                searchDto.getSearchText(), searchDto.getSearchContent(), start, end, searchDto.getWhatsApp(), searchDto.getReadStatus(), principalUid, selfPrincipalUid);

        if (CollectionUtils.isNotEmpty(pageList.getRecords())) {
            dealInfo(pageList.getRecords());
        }
        return Result.OK(pageList);
    }

    /**
     * 处理询盘列表结果集
     * @param enquiryList
     */
    private void dealInfo(List<EnquiryListDto> enquiryList) {
        if (CollectionUtils.isEmpty(enquiryList)) {
            return;
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<DictModel> userEffectiveDict = sysDictService.queryDictItemsByCode(AdwebConstant.ENQUIRY_EFFECTIVE);
        AtomicInteger atomicInteger = new AtomicInteger();

        enquiryList.forEach(enquiry -> {
            // 来源页面如果以 / 结尾，去掉最后一个字符
            String fromPage = enquiry.getFromPage();
            if (StringUtils.isNotBlank(fromPage)) {
                if (fromPage.endsWith("/")) {
                    enquiry.setFromPage(fromPage.substring(0, fromPage.length() - 1));
                }
            }
            atomicInteger.getAndIncrement();
            enquiry.setDataIndex(atomicInteger.get());

            // 示例关键信息脱敏
            if(demoFlag){
                enquiry.setFormCompany("**********");
                enquiry.setFromEmail("**********");
                enquiry.setWhatsApp("**********");
                enquiry.setPhone("**********");
                String siteName = enquiry.getSiteName();
                enquiry.setSiteName(siteName.substring(0,2)+"**********"+siteName.substring(siteName.length()-2));
            }

            /**********************字典数据处理***********************/
            if (CollectionUtils.isNotEmpty(userEffectiveDict)) {
                userEffectiveDict.forEach(dict -> {
                    if (dict.getValue().equals(enquiry.getUserEffective() + "")) {
                        enquiry.setUserEffectiveStr(dict.getLabel());
                    }
                });
            }

            // 询盘中用户自定义的字段处理
            if(StringUtils.isNotBlank(enquiry.getSpecialField())){
                List<EnquirySpecialFields> specialFieldsList = FastJsonUtil.parseList(enquiry.getSpecialField(), EnquirySpecialFields.class);
                enquiry.setSpecialFieldList(specialFieldsList);
                enquiry.setSpecialField(null);
            }

            if(StringUtils.isNotBlank(enquiry.getContext())){
                String context = enquiry.getContext();
                Pattern CRLF = Pattern.compile("(\r\n|\r|\n|\n\r)");
                Matcher m = CRLF.matcher(context);
                if (m.find()) {
                    context = m.replaceAll("<br/>");
                }
                enquiry.setContext(context);
            }
        });
    }

    /**
     * 添加
     *
     * @param adwebEnquiry
     * @return
     */
    @AutoLog(value = "询盘信息存储表单-添加")
    @Operation(summary = "询盘信息存储表单-添加")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_enquiry:add')")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody AdwebEnquiry adwebEnquiry) {
        adwebEnquiryService.save(adwebEnquiry);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param adwebEnquiry
     * @return
     */
    @AutoLog(value = "询盘信息存储表单-编辑")
    @Operation(summary = "询盘信息存储表单-编辑")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_enquiry:edit')")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody AdwebEnquiry adwebEnquiry) {
        adwebEnquiryService.updateById(adwebEnquiry);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "询盘信息存储表单-通过id删除")
    @Operation(summary = "询盘信息存储表单-通过id删除")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_enquiry:delete')")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        adwebEnquiryService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "询盘信息存储表单-批量删除")
    @Operation(summary = "询盘信息存储表单-批量删除")
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_enquiry:deleteBatch')")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.adwebEnquiryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "询盘信息存储表单-通过id查询")
    @Operation(summary = "询盘信息存储表单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<AdwebEnquiry> queryById(@RequestParam(name = "id", required = true) String id) {
        AdwebEnquiry adwebEnquiry = adwebEnquiryService.getById(id);
        if (adwebEnquiry == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(adwebEnquiry);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adwebEnquiry
     */
    @PreAuthorize("@jps.requiresPermissions('adweb:adweb_enquiry:exportXls')")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AdwebEnquiry adwebEnquiry) {
        return super.exportXls(request, adwebEnquiry, AdwebEnquiry.class, "询盘信息存储表单");
    }

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

    /**
     * 获取需要轮流询盘的站点code
     */
    @GetMapping("/getTurnInquiryCode")
    public Result<?> getTurnInquiryCode() {
        List<DictPropertyModel> siteRes = sysAdwebApi.queryDictInfoByDictCode("turn_inquiry_site_code");
        if (CollectionUtils.isNotEmpty(siteRes)){
            return Result.OK(siteRes);
        }
        return null;
    }

    /**
     * @return
     */
    @GetMapping(value = "/getEnquiryCatalog")
    public Result<?> getEnquiryCatalog() {
        List<DictPropertyModel> userEffectiveDict = sysAdwebApi.queryDictInfoByDictCode(AdwebConstant.ENQUIRY_EFFECTIVE);
        return Result.OK(FastJsonUtil.toJSONString(userEffectiveDict));
    }

    /**
     * 获取不同状态询盘的数量
     *
     * @param siteId 站点id
     * @return 数量信息
     */
    @GetMapping("getEnquiryNums")
    public Result<?> getEnquiryNums(Integer siteId,
                                 String dateType,
                                 @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
                                 @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.isNotBlank(dateType)) {
            Map<String, Date> map = dealDateType(dateType);
            start = map.get("start");
            end = map.get("end");
        } else {
            if (end != null) {
                end = DateUtil.addDays(end, 1);
            }
        }

        List<Integer> siteIds = null;
        if (siteId != null) {
            String siteCode = adwebSiteService.getSiteCodeById(siteId);
            QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", siteCode).or().eq("parent_group_code", siteCode);
            queryWrapper.ne("status", 0);
            List<AdwebSite> sites = adwebSiteService.list(queryWrapper);
            siteIds = sites.stream().map(AdwebSite::getId).collect(Collectors.toList());
        } else {
            if (sysAdwebApi.isAdmin()) {
                QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
                queryWrapper.ne("status", 0);
                List<AdwebSite> sites = adwebSiteService.list(queryWrapper);
                siteIds = sites.stream().map(AdwebSite::getId).collect(Collectors.toList());
            } else if (sysAdwebApi.isOem()) {
                List<String> oemGroupUids = sysAdwebApi.getOemGroupUids();
                List<String> codeList = siteUserPermissionService.getSiteCodeListByUids(oemGroupUids);
                LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(AdwebSite::getCode, codeList);
                queryWrapper.ne(AdwebSite::getStatus, 0);
                List<AdwebSite> sites = adwebSiteService.list(queryWrapper);
                siteIds = sites.stream().map(AdwebSite::getId).collect(Collectors.toList());
            } else {
                List<String> codeList = siteUserPermissionService.getSiteCodeList(loginUser.getId());
                LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(AdwebSite::getCode, codeList);
                queryWrapper.ne(AdwebSite::getStatus, 0);
                List<AdwebSite> sites = adwebSiteService.list(queryWrapper);
                siteIds = sites.stream().map(AdwebSite::getId).collect(Collectors.toList());
            }
        }

        String principalUid = null;
        if (sysAdwebApi.isAdwebSubVip()) {
            principalUid = loginUser.getId();
        }

        QueryWrapper<AdwebEnquiry> enquiryQueryWrapper = new QueryWrapper<>();
        enquiryQueryWrapper.eq("status", 1);
        if (start != null) {
            enquiryQueryWrapper.ge("record_ctime", start);
        }
        if (end != null) {
            enquiryQueryWrapper.lt("record_ctime", end);
        }
        if (siteIds != null) {
            enquiryQueryWrapper.in("site_id", siteIds);
        }
        if (StringUtils.isNotBlank(principalUid)) {
            String finalPrincipalUid = principalUid;
            enquiryQueryWrapper.and(wrapper -> wrapper.eq("principal_uid", finalPrincipalUid).or().eq("principal_uid", "ALL"));
        }
        enquiryQueryWrapper.ne("user_effective", 0);
        int all = (int) adwebEnquiryService.count(enquiryQueryWrapper);

        QueryWrapper<AdwebEnquiry> enquiryQueryWrapper1 = new QueryWrapper<>();
        enquiryQueryWrapper1.eq("status", 1);
        if (start != null) {
            enquiryQueryWrapper1.ge("record_ctime", start);
        }
        if (end != null) {
            enquiryQueryWrapper1.lt("record_ctime", end);
        }
        if (siteIds != null) {
            enquiryQueryWrapper1.in("site_id", siteIds);
        }
        enquiryQueryWrapper1.eq("read_status", 0);
        if (StringUtils.isNotBlank(principalUid)) {
            String finalPrincipalUid = principalUid;
            enquiryQueryWrapper1.and(wrapper -> wrapper.eq("principal_uid", finalPrincipalUid).or().eq("principal_uid", "ALL"));
        }
        enquiryQueryWrapper1.ne("user_effective", 0);
        int noRead = (int) adwebEnquiryService.count(enquiryQueryWrapper1);

        QueryWrapper<AdwebEnquiry> enquiryQueryWrapper2 = new QueryWrapper<>();
        enquiryQueryWrapper2.eq("status", 1);
        if (start != null) {
            enquiryQueryWrapper2.ge("record_ctime", start);
        }
        if (end != null) {
            enquiryQueryWrapper2.lt("record_ctime", end);
        }
        if (siteIds != null) {
            enquiryQueryWrapper2.in("site_id", siteIds);
        }
        enquiryQueryWrapper2.eq("user_effective", 1);
        if (StringUtils.isNotBlank(principalUid)) {
            String finalPrincipalUid = principalUid;
            enquiryQueryWrapper2.and(wrapper -> wrapper.eq("principal_uid", finalPrincipalUid).or().eq("principal_uid", "ALL"));
        }
        enquiryQueryWrapper2.ne("user_effective", 0);
        int product = (int) adwebEnquiryService.count(enquiryQueryWrapper2);

        QueryWrapper<AdwebEnquiry> enquiryQueryWrapper3 = new QueryWrapper<>();
        enquiryQueryWrapper3.eq("status", 1);
        if (start != null) {
            enquiryQueryWrapper3.ge("record_ctime", start);
        }
        if (end != null) {
            enquiryQueryWrapper3.lt("record_ctime", end);
        }
        if (siteIds != null) {
            enquiryQueryWrapper3.in("site_id", siteIds);
        }
        enquiryQueryWrapper3.eq("user_effective", 2);
        if (StringUtils.isNotBlank(principalUid)) {
            String finalPrincipalUid = principalUid;
            enquiryQueryWrapper3.and(wrapper -> wrapper.eq("principal_uid", finalPrincipalUid).or().eq("principal_uid", "ALL"));
        }
        enquiryQueryWrapper3.ne("user_effective", 0);
        int wait = (int) adwebEnquiryService.count(enquiryQueryWrapper3);

        Map<String, Integer> map = new HashMap<>();
        map.put("all", all);
        map.put("noRead", noRead);
        map.put("product", product);
        map.put("wait", wait);

        return Result.OK(map);
    }

    /**
     * 将询盘的状态改为已读
     *
     * @param id 询盘id
     * @return 处理结果
     */
    @GetMapping("/read")
    public Result<?> read(@Param("id") String id) {
        if (disableAdminRead && (sysAdwebApi.isAdmin() || sysAdwebApi.isOem())) {
            return Result.OK();
        }
        UpdateWrapper<AdwebEnquiry> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", (Object) id.split(","));
        updateWrapper.set("read_status", 1);
        adwebEnquiryService.update(updateWrapper);
        return Result.OK();
    }

    /**
     * @param query
     * @return
     */
    @RequestMapping(value = "/enquiryTrans", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> getEnquiryTrans(String query, String id) {
        String text = awsTranslateUtils.translate(query);
        UpdateWrapper<AdwebEnquiry> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("trans_content", text);
        adwebEnquiryService.update(updateWrapper);

        return Result.ok(text);
    }

    /**
     * 更改询盘用户有效性
     */
    @PostMapping("/update/user/effective")
    public Result<?> updateUserEffective(EffectiveEnquiryParamDto effectiveEnquiryParamDto) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        boolean res = adwebEnquiryService.updateUserEffective(effectiveEnquiryParamDto);
        if (res) {
            return Result.OK("ok");
        }
        return Result.error("fail");
    }

    /**
     * 转发询盘
     */
    @AutoLog(value = "转发询盘")
    @GetMapping(value = "/setForward")
    public Result<?> setForward(@RequestParam String ids, @RequestParam String uid, @RequestParam String code) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        SysUser user = sysUserService.getById(uid);
        if (StringUtils.isEmpty(user.getEmail())){
            return Result.error("该账户未设置邮箱！");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        UpdateWrapper<AdwebEnquiry> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", idList);
        updateWrapper.set("principal_uid", uid);
        updateWrapper.set("principal_type", 1);
        adwebEnquiryService.update(updateWrapper);

        QueryWrapper<AdwebEnquiry> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);
        List<AdwebEnquiry> list = adwebEnquiryService.list(queryWrapper);
        //获取站点
        QueryWrapper<AdwebSite> adwebSiteQueryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        AdwebSite adwebSite = adwebSiteService.getOne(adwebSiteQueryWrapper);
        adwebEnquiryService.specialSendEmail(list, adwebSite);
        //返回跟进人名称
        for (String id: idList) {
            AdwebEnquiry adwebEnquiry = adwebEnquiryService.getById(id);
            if (adwebEnquiry != null && StringUtils.isNotBlank(adwebEnquiry.getRecordId())) {
                adwebEnquiryService.returnSalesperson(code, adwebEnquiry.getRecordId(), user.getUsername());
            }
        }
        return Result.OK();
    }

    /**
     * 回收站列表接口
     */
    @AutoLog(value = "adweb_enquiry-分页列表查询")
    @GetMapping(value = "/queryWasteEnquiryList")
    public Result<?> queryWasteEnquiryList(Integer siteId,
                                           String searchText,
                                           String enquiryType,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize) {
        if (sysAdwebApi.isNotOwnSite(siteId)) {
            return Result.OK(new Page<>());
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page<EnquirySearchDto> page = new Page<>(pageNo, pageSize);
        List<String> codeList = null;
        List<String> uidList = null;

        if (sysAdwebApi.isAdmin()) {
        } else if (sysAdwebApi.isOem()) {
            uidList = sysAdwebApi.getOemGroupUids();
        } else {
            uidList = new ArrayList<>();
            uidList.add(sysUser.getId());
        }

        List<String> siteCodeList = null;
        if(CollectionUtils.isNotEmpty(uidList)){
            siteCodeList = siteUserPermissionService.getSiteCodeListByUids(uidList);
        }

        codeList = adwebSiteService.list(new LambdaQueryWrapper<AdwebSite>()
                .eq(siteId != null, AdwebSite::getId, siteId)
                .in(!sysAdwebApi.isAdmin(), AdwebSite::getCode, siteCodeList)
                .ne(AdwebSite::getStatus, 0)).stream().map(AdwebSite::getCode).collect(Collectors.toList());

        String principalUid = null;
        if (sysAdwebApi.isAdwebSubVip()) {
            principalUid = sysUser.getId();
        }
        if (StringUtils.isNotBlank(searchText)) {
            searchText = searchText.trim();
        }
        enquiryType = "(" + enquiryType + ")";
        IPage<EnquiryListDto> pageList = adwebEnquiryMapper.queryWasteEnquiryList(page, codeList, "", enquiryType, searchText, null, null, null, principalUid);
        if (CollectionUtils.isNotEmpty(pageList.getRecords())) {
            dealInfo(pageList.getRecords());
            return Result.OK(pageList);
        }
        dealInfo(pageList.getRecords());
        return Result.OK(pageList);
    }

    /**
     * 批量复原
     *
     * @param adwebEnquiry
     * @return
     */
    @PutMapping(value = "/refreshBatch")
    public Result<?> refreshBatch(@RequestBody AdwebEnquiry adwebEnquiry) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        UpdateWrapper<AdwebEnquiry> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", adwebEnquiry.getNo().split(","));
        updateWrapper.set("status", 1);
        adwebEnquiryService.update(updateWrapper);

        return Result.OK("批量复原成功!");
    }

    @GetMapping("/getWastedEnquiry")
    public Result<List<EnquiryListDto>> getWastedEnquiry(EnquiryListSearchDto enquiryListSearchDto) {

        List<EnquiryListDto> wasterEnquiries = adwebEnquiryMapper.getWastedEnquiry(
                enquiryListSearchDto.getWasteEnquiryType()
                ,enquiryListSearchDto.getIp()
                ,enquiryListSearchDto.getEmail()
                ,enquiryListSearchDto.getKeyword()
                ,enquiryListSearchDto.getSearchText()
                ,enquiryListSearchDto.getType()
                ,enquiryListSearchDto.getSiteId()
        );

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        return Result.OK(wasterEnquiries);
    }


    /**
     * 根据询盘信息创建邮件发送记录
     * @param adwebEnquiry      询盘信息
     * @param email             接收邮箱
     * @return
     */
    private static EnquiryEmailMessage newEmail(AdwebEnquiry adwebEnquiry, String email) {
        EnquiryEmailMessage enquiryEmailMessage = new EnquiryEmailMessage();
        enquiryEmailMessage.setEnquiryId(adwebEnquiry.getId());
        enquiryEmailMessage.setEmail(email);
        enquiryEmailMessage.setFromEmail(adwebEnquiry.getFromEmail());
        enquiryEmailMessage.setCreateTime(new Date());
        enquiryEmailMessage.setSiteCode(adwebEnquiry.getSiteCode());
        enquiryEmailMessage.setSendStatus(EnquirySendStatus.WAIT_SEND);
        enquiryEmailMessage.setSendErrorNum(0);

        return enquiryEmailMessage;
    }

    /**
     * 特殊时间数据处理
     *
     * @param dateType 时间
     */
    private Map<String, Date> dealDateType(String dateType) {
        Date now = new Date();
        Date start = null;
        Date end = null;
        if ("yesterday".equals(dateType)) {
            start = DateUtil.getTodayZeroTime(DateUtil.addDays(now, -1));
            end = DateUtil.getTodayZeroTime(now);
        }
        if ("today".equals(dateType)) {
            start = DateUtil.getTodayZeroTime(now);
            end = DateUtil.getTmrZeroTime(now);
        }
        if ("sevenDay".equals(dateType)) {
            end = DateUtil.getTmrZeroTime(now);
            start = DateUtil.addDays(end, -7);
        }
        if ("thirtyDay".equals(dateType)) {
            end = DateUtil.getTmrZeroTime(now);
            start = DateUtil.addDays(end, -30);
        }
        Map<String, Date> map = new HashMap<>();
        map.put("start", start);
        map.put("end", end);
        return map;
    }


}
