package org.jeecg.modules.adweb.enquiry.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.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.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.DictModel;
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.DateUtil;
import org.jeecg.modules.adweb.common.util.ListUtil;
import org.jeecg.modules.adweb.enquiry.dto.param.AdmpEnquirySearchDto;
import org.jeecg.modules.adweb.enquiry.dto.param.EnquiryListSearchDto;
import org.jeecg.modules.adweb.enquiry.dto.result.AdmpEnquiryListDto;
import org.jeecg.modules.adweb.enquiry.dto.result.EnquirySpecialFields;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiry;
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.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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> {
    @Autowired
    private IAdwebEnquiryService adwebEnquiryService;

    @Value("${enquiry.demoFlag:false}")
    private Boolean demoFlag;

    @Resource
    private AdwebEnquiryMapper adwebEnquiryMapper;

    @Autowired
    private SysAdwebApi sysAdwebApi;

    @Autowired
    private IAdwebSiteService adwebSiteService;

    @Autowired
    private ISiteUserPermissionService siteUserPermissionService;

    @Autowired
    private ISysDictService sysDictService;

    /**
     * 分页列表查询
     *
     * @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) {
//
//		String message = "Hello World";
//		rocketMQTemplate.convertAndSend("TEST", message);
//		System.out.println("Message sent: " + message);

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

        Page<AdmpEnquirySearchDto> 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 (ListUtil.notEmpty(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)) {
			Map<String, Date> map = DateUtil.dealDateType(dateType);
			start = map.get("start");
			end = map.get("end");
		} else {
			if (end != null) {
				end = DateUtil.addDays(end, 1);
			}
		}
		if(ListUtil.isEmpty(codeList)){
			return Result.OK(page);
		}

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

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


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

        if (ListUtil.notEmpty(pageList.getRecords())) {
            dealInfo(pageList.getRecords());
        }
        return Result.OK(pageList);
    }

    /**
     * 处理询盘列表结果集
     * @param enquiryList
     */
    private void dealInfo(List<AdmpEnquiryListDto> enquiryList) {
        if (ListUtil.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 (ListUtil.notEmpty(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);
    }

}
