package com.fs.company.controller.qw;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.result.Result;
import com.fs.qw.domain.QwCustomerLink;
import com.fs.qw.domain.QwCustomerLinkChannel;
import com.fs.qw.domain.QwCustomerLinkUser;
import com.fs.qw.dto.QwCustomerLinkChannelReq;
import com.fs.qw.dto.QwCustomerLinkReq;
import com.fs.qw.dto.QwCustomerLinkUserDto;
import com.fs.qw.service.IQwCustomerLinkChannelService;
import com.fs.qw.service.IQwCustomerLinkService;
import com.fs.qw.service.IQwCustomerLinkUserService;
import com.fs.qwApi.domain.QwLinkCreateResult;
import com.fs.qwApi.param.QwLinkCreateParam;
import com.fs.qwApi.service.QwApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 企微获客链接 前端控制器
 * </p>
 *
 * @author zhangqin
 * @since 2025-12-03
 */
@RestController
@RequestMapping("/qwCustomerLink")
public class QwCustomerLinkController {

    @Autowired
    private IQwCustomerLinkService qwCustomerLinkService;
    @Autowired
    private IQwCustomerLinkUserService qwCustomerLinkUserService;
    @Autowired
    private IQwCustomerLinkChannelService qwCustomerLinkChannelService;
    @Autowired
    private QwApiService qwApiService;

    /**
     * 分页查询主链
     */
    @GetMapping("/page")
    public Result<IPage<QwCustomerLink>> page(
            @RequestParam(defaultValue = "1") Long pageNum,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String corpName,
            @RequestParam(required = false) String linkName
    ) {
        Page<QwCustomerLink> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QwCustomerLink> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(corpName), QwCustomerLink::getCorpName, corpName);
        wrapper.like(StrUtil.isNotBlank(linkName), QwCustomerLink::getLinkName, linkName);
        wrapper.eq(QwCustomerLink::getStatus, 0);
        wrapper.orderByDesc(QwCustomerLink::getCreateTime);
        IPage<QwCustomerLink> result = qwCustomerLinkService.page(page, wrapper);
        return Result.success(result);
    }

    /**
     * 分页查询渠道链
     */
    @GetMapping("/channel/page")
    public Result<IPage<QwCustomerLinkChannel>> pageChannel(
            @RequestParam(defaultValue = "1") Long pageNum,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String linkName,
            @RequestParam(required = false) String sysLinkId
    ) {
        Page<QwCustomerLinkChannel> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QwCustomerLinkChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(linkName), QwCustomerLinkChannel::getLinkName, linkName);
        wrapper.eq(QwCustomerLinkChannel::getStatus, 0);
        wrapper.eq(QwCustomerLinkChannel::getSysLinkId, sysLinkId);
        wrapper.orderByDesc(QwCustomerLinkChannel::getCreateTime);
        IPage<QwCustomerLinkChannel> result = qwCustomerLinkChannelService.page(page, wrapper);
        return Result.success(result);
    }

    /**
     * 新增/编辑 主链
     */
    @PostMapping("/createOrUpdate")
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> create(@RequestBody QwCustomerLinkReq qwGroupLiveCode) {
        QwCustomerLink bean = BeanUtil.toBean(qwGroupLiveCode, QwCustomerLink.class);

        QwLinkCreateParam qwLinkCreateParam = new QwLinkCreateParam();
        qwLinkCreateParam.setLink_name(qwGroupLiveCode.getLinkName());
        qwLinkCreateParam.setSkip_verify(qwGroupLiveCode.getSkipVerify());
        QwLinkCreateParam.Range range = new QwLinkCreateParam.Range();

        range.setUser_list(qwGroupLiveCode.getLinkUser().stream().map(QwCustomerLinkUserDto::getQwUserId).collect(Collectors.toList()));
        qwLinkCreateParam.setRange(range);

        boolean success = false;
        if (qwGroupLiveCode.getId() != null) {
            QwCustomerLink byId = qwCustomerLinkService.getById(qwGroupLiveCode.getId());
            qwLinkCreateParam.setLink_id(byId.getLinkId());
            // qwApiService.linkUpdate(qwLinkCreateParam, qwGroupLiveCode.getCorpId());
            success = qwCustomerLinkService.updateById(bean);
        } else {
            QwLinkCreateResult qwLinkCreateResult = qwApiService.linkCreate(qwLinkCreateParam, qwGroupLiveCode.getCorpId());
            bean.setLinkId(qwLinkCreateResult.getLinkId());
            bean.setUrl(qwLinkCreateResult.getUrl());
/*            bean.setLinkId(IdUtil.randomUUID());
            bean.setUrl("https://work.weixin.qq.com/ca/" + IdUtil.randomUUID())*/;
            success = qwCustomerLinkService.save(bean);
        }

        if (success) {
            qwCustomerLinkUserService.remove(new LambdaQueryWrapper<QwCustomerLinkUser>().eq(QwCustomerLinkUser::getSysLinkId, bean.getId()));
            qwCustomerLinkUserService.saveBatch(qwGroupLiveCode.getLinkUser().stream()
                    .map(e -> {
                        QwCustomerLinkUser user = new QwCustomerLinkUser();
                        user.setSysLinkId(bean.getId());
                        user.setQwUserId(e.getQwUserId());
                        user.setSysQwUserId(e.getSysQwUserId());
                        user.setQwUserName(e.getQwUserName());
                        return user;
                    })
                    .collect(Collectors.toList()));
        }
        return success ? Result.success() : Result.error("创建失败");
    }

    /**
     * 新增渠道链接
     */
    @PostMapping("/channel/create")
    public Result<Void> createChannel(@RequestBody QwCustomerLinkChannelReq linkChannelReq) {

        // 主链
        QwCustomerLink qwCustomerLink = qwCustomerLinkService.getById(linkChannelReq.getSysLinkId());
        // 主链关联的企微用户
        List<QwCustomerLinkUser> linkUsers = qwCustomerLinkUserService.list(new LambdaQueryWrapper<QwCustomerLinkUser>()
                .eq(QwCustomerLinkUser::getSysLinkId, qwCustomerLink.getId()));
        List<String> userIdList = linkUsers.stream()
                .map(QwCustomerLinkUser::getQwUserId)
                .collect(Collectors.toList());

        List<QwCustomerLinkChannel> channels = linkChannelReq.getChannelList().stream()
                .map(channelDto -> {
                    QwLinkCreateParam param = new QwLinkCreateParam();
                    param.setLink_name(channelDto.getChannelName());
                    param.setSkip_verify(qwCustomerLink.getSkipVerify().equals(1));
                    QwLinkCreateParam.Range range = new QwLinkCreateParam.Range();
                    range.setUser_list(userIdList);
                    param.setRange(range);

                    // QwLinkCreateResult linkResult = qwApiService.linkCreate(param, qwCustomerLink.getCorpId());

                    QwCustomerLinkChannel channel = new QwCustomerLinkChannel();
                    channel.setChannelId(channelDto.getChannelId());
                    channel.setChannelName(channelDto.getChannelName());
                    channel.setSysLinkId(linkChannelReq.getSysLinkId());
                    channel.setLinkName(channelDto.getChannelName());
                    // channel.setLinkId(linkResult.getLinkId());
                    // channel.setUrl(linkResult.getUrl());

                    channel.setLinkId(IdUtil.randomUUID());
                    channel.setUrl("https://work.weixin.qq.com/ca/" + IdUtil.randomUUID());
                    return channel;
                })
                .collect(Collectors.toList());

        return qwCustomerLinkChannelService.saveBatch(channels) ? Result.success() : Result.error("创建失败");
    }


    /**
     * 删除 主链
     */
    @PostMapping("/delete/{id}")
    public Result<Void> create(@PathVariable Long id) {
        return qwCustomerLinkService.update(new LambdaUpdateWrapper<QwCustomerLink>()
                .eq(QwCustomerLink::getId, id)
                .set(QwCustomerLink::getStatus, 1)) ? Result.success() : Result.error("删除失败");
    }

    /**
     * 删除 渠道链
     */
    @PostMapping("/channel/delete/{id}")
    public Result<Void> createChannel(@PathVariable Long id) {
        return qwCustomerLinkChannelService.removeById(id) ? Result.success() : Result.error("删除失败");
    }

    /**
     * 查询主链信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<QwCustomerLink> getById(@PathVariable Long id) {
        QwCustomerLink byId = qwCustomerLinkService.getById(id);
        byId.setQwCustomerLinkUsers(qwCustomerLinkUserService.list(new LambdaQueryWrapper<QwCustomerLinkUser>()
                .eq(QwCustomerLinkUser::getSysLinkId, id)));
        return Result.success(byId);
    }
}
