package com.citygis.web.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.citygis.common.core.domain.AjaxResult;
import com.citygis.web.domain.*;
import com.citygis.web.mapper.TabAccessReadyMapper;
import com.citygis.web.service.ITabAccessAndReadyService;
import com.citygis.web.service.ITabAccessReadyService;
import com.citygis.web.service.ITabAccessService;
import com.citygis.web.service.ITabSystemMsgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.citygis.common.utils.SecurityUtils.*;

/**
 * <p>
 * 接入基本准备表 服务实现类
 * </p>
 *
 * @author citygis
 * @since 2025-01-10
 */
@Service
public class TabAccessReadyServiceImpl extends ServiceImpl<TabAccessReadyMapper, TabAccessReady> implements ITabAccessReadyService {

    @Resource
    TabAccessReadyMapper tabAccessReadyMapper;

    @Resource
    ITabAccessAndReadyService tabAccessAndReadyService;

    @Resource
    ITabAccessService tabAccessService;

    @Resource
    ITabSystemMsgService tabSystemMsgService;

    @Override
    public AjaxResult getTabAccessAndReadyById(Long id) {
        TabAccessReady byId = this.getById(id);

        // 查询接入方列表
        LambdaQueryWrapper<TabAccessAndReady> ql = new LambdaQueryWrapper<>();
        ql.eq(TabAccessAndReady::getAccessOnlyId, id);
        ql.eq(TabAccessAndReady::getAccessType, "0");
        List<TabAccessAndReady> accessList = tabAccessAndReadyService.list(ql);
        byId.setAccess(accessList);

        // 查询提供方列表
        LambdaQueryWrapper<TabAccessAndReady> ql1 = new LambdaQueryWrapper<>();
        ql1.eq(TabAccessAndReady::getAccessOnlyId, id);
        ql1.eq(TabAccessAndReady::getAccessType, "1");
        List<TabAccessAndReady> offerList = tabAccessAndReadyService.list(ql1);
        byId.setOffers(offerList);

        return AjaxResult.success(byId);
    }

    @Override
    @Transactional
    public AjaxResult insertTabAccessReady(TabAccessReady tabAccessReady) {
        // 获取雪花 ID 生成器
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();

        // 设置基本属性
        tabAccessReady.setId(id);
        tabAccessReady.setCreateBy(getUsername());
        tabAccessReady.setCreateTime(new Date());
        tabAccessReady.setUserId(getUserId());
        tabAccessReady.setDeptId(getDeptId());
        this.save(tabAccessReady);

        // 处理 Access 列表
        List<TabAccessAndReady> accessList = tabAccessReady.getAccess();
        List<TabAccessAndReady> offersList = tabAccessReady.getOffers();

        // 给 access 和 offers 设置 ID
        setAccessAndOfferIds(accessList, id, snowflake);
        setAccessAndOfferIds(offersList, id, snowflake);

        // 保存 access 和 offers 批量数据
        tabAccessAndReadyService.saveBatch(accessList);
        tabAccessAndReadyService.saveBatch(offersList);

        // 提取 access 和 offers 的访问系统信息，避免重复查询
        Map<Long, TabAccess> accessMap = getAccessInfoMap(accessList);
        Map<Long, TabAccess> offerMap = getAccessInfoMap(offersList);

        // 构建反馈信息
        List<TabAccessFeedback> feedbackList = buildAccessFeedbackList(accessList, offersList, accessMap, offerMap, id, tabAccessReady);

        return AjaxResult.success(feedbackList);
    }

    @Override
    @Transactional
    public AjaxResult updateTabAccessReadyById(TabAccessReady tabAccessReady) {
        tabAccessReady.setUpdateBy(getUsername());
        tabAccessReady.setUpdateTime(new Date());
        this.updateById(tabAccessReady);

        // 处理 Access 列表
        List<TabAccessAndReady> accessList = tabAccessReady.getAccess();
        List<TabAccessAndReady> offersList = tabAccessReady.getOffers();

        if (accessList != null) {
            accessList.forEach(access -> {
                TabAccessAndReady byId = tabAccessAndReadyService.getById(access.getId());
                if (byId == null) {
                    access.setAccessOnlyId(tabAccessReady.getId());
                    tabAccessAndReadyService.save(access);
                } else {
                    tabAccessAndReadyService.updateById(access);
                }
            });
        }

        if (offersList != null) {
            offersList.forEach(offer -> {
                TabAccessAndReady byId = tabAccessAndReadyService.getById(offer.getId());
                if (byId == null) {
                    offer.setAccessOnlyId(tabAccessReady.getId());
                    tabAccessAndReadyService.save(offer);
                } else {
                    tabAccessAndReadyService.updateById(offer);
                }
            });
        }


        return AjaxResult.success("修改成功");
    }

    @Override
    @Transactional
    public AjaxResult falseDeleteTabAccessAndReadyById(Long id) {

        TabAccessAndReady tabAccessAndReady = new TabAccessAndReady();
        tabAccessAndReady.setId(id);
        boolean b = tabAccessAndReadyService.removeById(tabAccessAndReady);
        if (b) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.success("删除失败");
        }
    }

    @Override
    public List<TabAccessReady> list(TabAccessReady tabAccessReady) {
        List<Integer> states = new ArrayList<>();
        if (tabAccessReady.getStatus() != null) {
            Integer state = tabAccessReady.getStatus();

            //正式运行
            if (state == 1) {
                states.add(5);
                states.add(6);
            } else if (state == 2) {//申请反馈
                states.add(1);
                states.add(2);
                states.add(3);
                states.add(4);
            }

            tabAccessReady.setStates(states);
        }


        List<TabAccessReady> list = tabAccessReadyMapper.list(tabAccessReady);
        if (list != null) {
            list.forEach(tabAccessReady1 -> {
                LambdaQueryWrapper<TabAccessAndReady> qw = new LambdaQueryWrapper<>();
                qw.eq(TabAccessAndReady::getAccessOnlyId, tabAccessReady1.getId());
                qw.eq(TabAccessAndReady::getAccessType, "0");
                List<TabAccessAndReady> accessList = tabAccessAndReadyService.list(qw);
                String accessDept = "";
                String accessSystem = "";
                String ip = "";
                String port = "";
                for (TabAccessAndReady tabAccessAndReady : accessList) {
                    accessDept += ", " + tabAccessAndReady.getDept();
                    accessSystem += ", " + tabAccessAndReady.getSystem();
                    ip += " , " + tabAccessAndReady.getReadyIp();
                    port += " , " + tabAccessAndReady.getReadyPort();
                }

                tabAccessReady1.setAccessDept(accessDept);
                tabAccessReady1.setAccessSystem(accessSystem);
                tabAccessReady1.setIp(ip);
                tabAccessReady1.setPort(port);

                LambdaQueryWrapper<TabAccessAndReady> qw1 = new LambdaQueryWrapper<>();
                qw1.eq(TabAccessAndReady::getAccessOnlyId, tabAccessReady1.getId());
                qw1.eq(TabAccessAndReady::getAccessType, "1");
                List<TabAccessAndReady> offerList = tabAccessAndReadyService.list(qw1);

                String offerDept = "";
                String offerSystem = "";
                for (TabAccessAndReady tabAccessAndReady : offerList) {
                    offerDept += ", " + tabAccessAndReady.getDept();
                    offerSystem += ", " + tabAccessAndReady.getSystem();
                }
                tabAccessReady1.setOfferDept(offerDept);
                tabAccessReady1.setOfferSystem(offerSystem);

            });
        }
        return list;
    }

    @Override
    @Transactional
    public AjaxResult updateStatusById(TabAccessReady tabAccessReady) {
        boolean b = this.updateById(tabAccessReady);
        if (b) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.success("修改失败");
        }
    }

    // 设置 Access 和 Offer 的 ID
    private void setAccessAndOfferIds(List<TabAccessAndReady> list, long id, Snowflake snowflake) {
        list.forEach(item -> {
            item.setId(snowflake.nextId());
            item.setAccessOnlyId(id);
        });
    }

    // 获取 Access 信息的映射表
    private Map<Long, TabAccess> getAccessInfoMap(List<TabAccessAndReady> list) {
        Map<Long, TabAccess> accessMap = new HashMap<>();
        list.forEach(item -> {
            TabAccess access = tabAccessService.getById(item.getAccessId());
            accessMap.put(item.getAccessId(), access);
        });
        return accessMap;
    }

    // 构建 TabAccessFeedback 列表
    private List<TabAccessFeedback> buildAccessFeedbackList(List<TabAccessAndReady> accessList, List<TabAccessAndReady> offersList,
                                                            Map<Long, TabAccess> accessMap, Map<Long, TabAccess> offerMap, long id, TabAccessReady tabAccessReady) {
        List<TabAccessFeedback> feedbackList = new ArrayList<>();

        accessList.forEach(accessItem -> {
            // 获取对应的 TabAccess 对象
            TabAccess access = accessMap.get(accessItem.getAccessId());

            offersList.forEach(offerItem -> {
                // 为每个 offer 创建新的 TabAccessFeedback 对象
                TabAccessFeedback feedback = new TabAccessFeedback();
                feedback.setAccessOnlyId(id);
                feedback.setCode(tabAccessReady.getCode());
                feedback.setOfferType(tabAccessReady.getDataOfferType());
                feedback.setAccessCode(tabAccessReady.getDataAccessType());

                // 设置 Access 的信息
                feedback.setAccessName(access.getDept());
                feedback.setAccessSystemName(access.getName());

                // 获取对应的 Offer 信息
                TabAccess offer = offerMap.get(offerItem.getAccessId());
                feedback.setOfferName(offer.getDept());
                feedback.setOfferSystemName(offer.getName());

                // 将创建的 feedback 添加到 feedbackList 中
                feedbackList.add(feedback);
            });
        });

        return feedbackList;
    }

}
