package cn.com.countrygarden.bi.main.service.dmn.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.dmn.CostInformationMapper;
import cn.com.countrygarden.bi.main.dao.dmn.DnmDomainInformationMapper;
import cn.com.countrygarden.bi.main.dto.dmn.DnmDomainInformationAndCost;
import cn.com.countrygarden.bi.main.dto.dmn.DnmDomainInformationPage;
import cn.com.countrygarden.bi.main.model.dmn.CostInformation;
import cn.com.countrygarden.bi.main.model.dmn.DnmDomainInformation;
import cn.com.countrygarden.bi.main.service.dmn.CostInformationService;
import cn.com.countrygarden.bi.main.service.dmn.DnmDomainInformationService;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: backEnd
 * @description: 域名信息俯实现层
 * @author: bug大神
 * @create: 2024-07-24 17:27
 **/
import cn.com.countrygarden.bi.main.core.Result;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Service
public class DnmDomainInformationServiceImpl implements DnmDomainInformationService {
    @Autowired
    private DnmDomainInformationMapper dnmDomainInformationMapper;
    @Autowired
    private CostInformationMapper costInformationMapper;


    @Override
    public Result getDomainInformation() {

        return Response.response(dnmDomainInformationMapper.selectAll());
    }

    @Override
    public Result insertDomainInformation(DnmDomainInformation domainInformation) {
        dnmDomainInformationMapper.insertDomainInformation(domainInformation);
        return Response.response(domainInformation.getId());
    }

    @Override
    public Result updateDnmDomainInformation(DnmDomainInformation domainInformation) {
        return dnmDomainInformationMapper.updateDnmDomainInformation(domainInformation) > 0 ? Response.response("成功") : Response.response("失败");
    }

    @Override
    public Result deleteDnmDomainInformation(Integer id) {
        return dnmDomainInformationMapper.deleteDnmDomainInformation(id) > 0 ? Response.response("成功") : Response.response("失败");

    }

    @Override
    @Transactional
//    操作两个表需要加上事务，一个表出错回滚
    public Result insertDnmDomainInformationAndCost(DnmDomainInformationAndCost dnmDomainInformationAndCost) {
        DnmDomainInformation domainInformation = dnmDomainInformationAndCost.getDomainInformation();

//        修改域名信息
        dnmDomainInformationMapper.insertDomainInformation(domainInformation);
            //        处理空指针问题 optional优化
        int domainInformationId = domainInformation.getId();
        List<CostInformation> costList = dnmDomainInformationAndCost.getCostList();
        for (CostInformation cost : costList) {
            cost.setDnmDomainInformationId(domainInformationId);
//            插入费用信息，可以优化为批量插入数据库性能
            costInformationMapper.addCostInformation(cost);
        }
        return Response.response("成功");
    }

    @Override

    public Result getDnmDomainInformationAndCost(Integer id) {
//        并行查询数据库
        CompletableFuture<DnmDomainInformation> domainInformationFuture = CompletableFuture.supplyAsync(() -> dnmDomainInformationMapper.getDnmDomainInformationById(id));
        CompletableFuture<List<CostInformation>> costListFuture = CompletableFuture.supplyAsync(() -> costInformationMapper.getCostInformationBydnmId(id));
        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(domainInformationFuture, costListFuture);
        try {
            combinedFuture.get(); // 等待所有任务完成
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        DnmDomainInformation domainInformation = domainInformationFuture.join();
        List<CostInformation> costList = costListFuture.join();
        return Response.response(new DnmDomainInformationAndCost(domainInformation, costList));
    }

    //域名管理员领导的查询service
    @Override
    public Result searchDomainsByPage(String domainName, String domainCouponNumber, String owner, String auditStatus, String startDate, String endDate, Integer pageSize, Integer page) {
        // 判断是否为空
        if (pageSize == null) {
            pageSize = 5;
        }
        if (page == null) {
            page = 1;
        }
        final Date startDate1;
        final Date endDate1;
        // 尝试解析开始日期和结束日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (startDate != null && !startDate.isEmpty()) {
                startDate1 = sdf.parse(startDate);
            } else {
                startDate1 = null;
            }
            if (endDate != null && !endDate.isEmpty()) {
                endDate1 = sdf.parse(endDate);
            } else {
                endDate1 = null;
            }
        } catch (ParseException e) {
            e.printStackTrace(); // 在实际应用中，应根据情况处理异常
            return null; // 根据实际情况返回结果
        }
        int limit = pageSize;
        int offset = (page - 1) * pageSize;
        // 使用 CompletableFuture 实现并行查询
        CompletableFuture<List<DnmDomainInformation>> listFuture = CompletableFuture.supplyAsync(() ->
                dnmDomainInformationMapper.dynamicQuery(domainName, domainCouponNumber, owner, auditStatus, startDate1, endDate1, limit, offset)
        );
        CompletableFuture<List<DnmDomainInformation>> countFuture = CompletableFuture.supplyAsync(() ->
                dnmDomainInformationMapper.dynamicQueryCount(domainName, domainCouponNumber, owner, auditStatus, startDate1, endDate1)
        );
        // 等待两个查询操作都完成
        CompletableFuture.allOf(listFuture, countFuture).join();
        List<DnmDomainInformation> list = listFuture.join();
        List<DnmDomainInformation> count = countFuture.join();
        int total = count.size();
        return Response.response(new DnmDomainInformationPage(list, total, page, pageSize));
    }

    //法务部领导的查询service
    @Override
    public Result searchDomainsByPageByLeader(String domainName, String domainCouponNumber, String owner, String auditStatus, String startDate, String endDate, Integer pageSize, Integer page) {
        // 判断是否为空
        if (pageSize == null) {
            pageSize = 5;
        }
        if (page == null) {
            page = 1;
        }
        final Date startDate1;
        final Date endDate1;
        // 尝试解析开始日期和结束日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (startDate != null && !startDate.isEmpty()) {
                startDate1 = sdf.parse(startDate);
            } else {
                startDate1 = null;
            }
            if (endDate != null && !endDate.isEmpty()) {
                endDate1 = sdf.parse(endDate);
            } else {
                endDate1 = null;
            }
        } catch (ParseException e) {
            e.printStackTrace(); // 在实际应用中，应根据情况处理异常
            return null; // 根据实际情况返回结果
        }
        int limit = pageSize;
        int offset = (page - 1) * pageSize;
        // 使用 CompletableFuture 实现并行查询
        CompletableFuture<List<DnmDomainInformation>> listFuture = CompletableFuture.supplyAsync(() ->
                dnmDomainInformationMapper.dynamicQueryByLeader(domainName, domainCouponNumber, owner, auditStatus, startDate1, endDate1, limit, offset)
        );
        CompletableFuture<List<DnmDomainInformation>> countFuture = CompletableFuture.supplyAsync(() ->
                dnmDomainInformationMapper.dynamicQueryCountByLeader(domainName, domainCouponNumber, owner, auditStatus, startDate1, endDate1)
        );
        // 等待两个查询操作都完成
        CompletableFuture.allOf(listFuture, countFuture).join();
        List<DnmDomainInformation> list = listFuture.join();
        List<DnmDomainInformation> count = countFuture.join();
        int total = count.size();
        return Response.response(new DnmDomainInformationPage(list, total, page, pageSize));
    }

    @Override
    public Result updateDnmDomainInformationById(Integer id, Integer flag) {
        int n = 0;
        if (flag == 0) {
            n = dnmDomainInformationMapper.updateDnmDomainInformationById(id, "已发布");
            return n > 0 ? Response.response("审核成功") : Response.responseFail("审核失败");
        }
        if (flag == 1) {
            n = dnmDomainInformationMapper.updateDnmDomainInformationById(id, "未通过");
            return n > 0 ? Response.response("审核成功") : Response.responseFail("审核失败");
        }

        return Response.responseFail("系统异常");
    }

    @Override
    public Result checkDomainName(String domainName) {
        return dnmDomainInformationMapper.checkDomainName(domainName).size() > 0 ? Response.response("该域名已存在") : Response.response("该域名不存在");
    }

    @Override
    public Result generateDomainCouponNumber() {
        String year = String.valueOf(Year.now().getValue()); // 获取当前年份
        String couponNumber;
        // 拼接年度和流水号
        do {
            int randomNum = ThreadLocalRandom.current().nextInt(10000);
            couponNumber = year + String.format("%04d", randomNum);
            if (Objects.isNull(RedisUtils.get(couponNumber))) {
                RedisUtils.sadd(couponNumber, couponNumber);
                break;
            }
        } while (true);
        // 检查Redis中是否已存在该券号
        return Response.response(couponNumber);
    }

    @Override
    @Transactional
    public Result updateDnmDomainInformationAndCost(DnmDomainInformationAndCost dnmDomainInformationAndCost) {
        DnmDomainInformation domainInformation = dnmDomainInformationAndCost.getDomainInformation();
//        插入域名信息
        int n = dnmDomainInformationMapper.updateDnmDomainInformation(domainInformation);
        List<CostInformation> costList = dnmDomainInformationAndCost.getCostList();
        for (CostInformation cost : costList) {
//            修改费用信息，可以优化为批量修改数据库性能
            costInformationMapper.updateByConditionById(cost);
        }
        return n > 0 ? Response.response("成功") : Response.responseFail("系统异常");
    }

}
