package com.cyksj.web.controller.manage.corp;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.SysCorpFollowRelateMapper;
import com.cyksj.mapper.corp.CorpCustomerAcquisitionLinkExtraCustomerMapper;
import com.cyksj.mapper.corp.CorpFollowMapper;
import com.cyksj.mapper.corp.CorpTagMapper;
import com.cyksj.mapper.corp.CorpWelcomeTemplateMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.CorpCustomerAcquisitionLinkExtraCustomerView;
import com.cyksj.model.views.SysCorpFollowView;
import com.cyksj.service.corp.CorpCustomerAcquisitionLinkService;
import com.cyksj.service.sys.SysConfigService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *  获客助手
 * @author chan
 * @date 2023/11/10 09:53
 */
@RestController
@RequestMapping("/manage/corp/customer/acuistion/link")
@RequiredArgsConstructor
public class CorpCustomerAcquistionLinkController {

    private final CorpCustomerAcquisitionLinkService corpCustomerAcquisitionLinkService;

    private final CorpFollowMapper corpFollowMapper;

    private final CorpTagMapper corpTagMapper;

    private final CorpWelcomeTemplateMapper corpWelcomeTemplateMapper;

    private final BeanSearcher beanSearcher;

    private final HttpServletRequest request;

    private final SysConfigService sysConfigService;

    private final CorpCustomerAcquisitionLinkExtraCustomerMapper corpCustomerAcquisitionLinkExtraCustomerMapper;

    private final SysCorpFollowRelateMapper sysCorpFollowRelateMapper;

    /**
     * 新增获客助手链接
     */
    @PostMapping
    public Result<String> add(@RequestBody CorpCustomerAcquisitionLink corpCustomerAcquisitionLink) throws Exception {
        corpCustomerAcquisitionLinkService.add(corpCustomerAcquisitionLink);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改获客助手链接
     */
    @PutMapping
    public Result<String> up(@RequestBody CorpCustomerAcquisitionLink corpCustomerAcquisitionLink) throws Exception {
        corpCustomerAcquisitionLinkService.up(corpCustomerAcquisitionLink);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 删除获客助手链接
     */
    @DeleteMapping("/{id}")
    public Result<String> up(@PathVariable Long id) throws Exception {
        corpCustomerAcquisitionLinkService.del(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 获取获客助手链接
     */
    @GetMapping("/get")
    public Result<SearchResult<CorpCustomerAcquisitionLink>> get() throws Exception {
        SearchResult<CorpCustomerAcquisitionLink> search = beanSearcher.search(CorpCustomerAcquisitionLink.class, MapUtils.flatBuilder(request.getParameterMap()).build());

        List<SysCorpFollowView> corpFollowServiceDtos = beanSearcher.searchAll(SysCorpFollowView.class, MapUtils.builder().build());

        search.getDataList().forEach(e -> {
            try {
                List<String> userStrList = corpFollowServiceDtos.stream().filter(cf -> {
                    try {
                        return Jsons.parseList(e.getUserList(), Long.class).contains(cf.getSid());
                    } catch (Exception ex) {
                    }
                    return false;
                }).map(SysCorpFollowView::getShowName).collect(Collectors.toList());
                e.setUserStrList(userStrList);

                if (StrUtil.isNotEmpty(e.getChooseDutyUsers())) {
                    List<String> dutyUserList = corpFollowServiceDtos.stream().filter(cf -> {
                        try {
                            return Jsons.parseList(e.getChooseDutyUsers(), Long.class).contains(cf.getSid());
                        } catch (Exception ex) {
                        }
                        return false;
                    }).map(SysCorpFollowView::getShowName).collect(Collectors.toList());

                    e.setChooseDutyUserList(dutyUserList);
                }

                List<String> tagStrList = corpTagMapper.selectList(Wrappers.lambdaQuery(CorpTag.class)
                        .in(CorpTag::getId, Jsons.parseList(e.getTags(), Long.class))).stream().map(CorpTag::getName).collect(Collectors.toList());
                e.setTagStrList(tagStrList);
            } catch (Exception ex) {
            }

            CorpWelcomeTemplate corpWelcomeTemplate = corpWelcomeTemplateMapper.selectById(e.getMsgId());
            if (corpWelcomeTemplate != null) {
                e.setMsgName(corpWelcomeTemplate.getName());
            }
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * 针对获客链接添加额外客服
     */
    @PostMapping("/add/extra/service")
    public Result<String> addExtraService(@RequestBody @Validated CorpCustomerAcquisitionLinkExtraCustomer extraCustomer) throws Exception {
        Integer serviceId = extraCustomer.getServiceId();
        SysCorpFollowRelate sysCorpFollowRelate = sysCorpFollowRelateMapper.selectById(serviceId);
        extraCustomer.setFollowId(sysCorpFollowRelate.getFollowId());
        corpCustomerAcquisitionLinkExtraCustomerMapper.insert(extraCustomer);
        corpCustomerAcquisitionLinkService.handleCorpLinkSchedulerJob();
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改获客链接添加额外客服
     */
    @PutMapping("/update/extra/service")
    public Result<String> updateExtraService(@RequestBody @Validated CorpCustomerAcquisitionLinkExtraCustomer extraCustomer) throws Exception {
        Integer serviceId = extraCustomer.getServiceId();
        SysCorpFollowRelate sysCorpFollowRelate = sysCorpFollowRelateMapper.selectById(serviceId);
        extraCustomer.setFollowId(sysCorpFollowRelate.getFollowId());
	    corpCustomerAcquisitionLinkExtraCustomerMapper.updateById(extraCustomer);
        corpCustomerAcquisitionLinkService.handleCorpLinkSchedulerJob();
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 删除获客链接添加额外客服
     */
    @DeleteMapping("/del/extra/service/{id}")
    public Result<String> delExtraService(@PathVariable Long id) {
	    Optional.ofNullable(corpCustomerAcquisitionLinkExtraCustomerMapper.selectById(id))
			    .ifPresent(e -> {
				    if (e.getDeleted()) {
                        try {
                            e.setDeleted(false);
                            corpCustomerAcquisitionLinkExtraCustomerMapper.updateById(e);
                            corpCustomerAcquisitionLinkService.handleCorpLinkSchedulerJob();
                        } catch (Exception ex) {
                        }
                    }
			    });
	    return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 获取获客链接添加额外客服
     */
    @GetMapping("/get/extra/service")
    public Result<SearchResult<CorpCustomerAcquisitionLinkExtraCustomerView>> getExtraService() throws Exception {
        SearchResult<CorpCustomerAcquisitionLinkExtraCustomerView> search = beanSearcher.search(CorpCustomerAcquisitionLinkExtraCustomerView.class, MapUtils.flatBuilder(request.getParameterMap())
                .orderBy(CorpCustomerAcquisitionLinkExtraCustomerView::getAcId).asc()
                .orderBy(CorpCustomerAcquisitionLinkExtraCustomerView::getCreatedTime).desc()
                .build());
        List<SysCorpFollowView> corpFollowServiceDtos = beanSearcher.searchAll(SysCorpFollowView.class, MapUtils.builder().build());
        Map<Long, List<SysCorpFollowView>> serviceMap = corpFollowServiceDtos.stream().collect(Collectors.groupingBy(SysCorpFollowView::getSid));
        search.getDataList().forEach(e->{
            Optional.ofNullable(serviceMap.get(e.getServiceId()))
                    .ifPresent(service -> e.setServiceName(service.get(0).getShowName()));
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

}
