package com.lutao.cloud.oil.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.core.util.StringUtil;
import com.lutao.cloud.oil.mapper.PersonCertificateMapper;
import com.lutao.cloud.oil.mapper.PersonInInfoMapper;
import com.lutao.cloud.oil.mapper.PlatformPersonTimeInfoMapper;
import com.lutao.cloud.oil.pojo.param.HighRiskCountParam;
import com.lutao.cloud.oil.pojo.param.PersonCertificateParam;
import com.lutao.cloud.oil.pojo.param.PersonGoSeaParam;
import com.lutao.cloud.oil.pojo.param.RecentPeopleLineChartParam;
import com.lutao.cloud.oil.pojo.vo.*;
import com.lutao.cloud.oil.service.*;
import com.lutao.entity.PersonInInfo;
import com.lutao.entity.PersonOutInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service
@Slf4j
public class BusinessPersonnelDynamicsServiceImpl implements IBusinessPersonnelDynamicsService {

    @Resource
    private PersonInInfoService PersonInInfoService;

    @Resource
    private PersonOutInfoService PersonOutInfoService;

    @Resource
    private PersonCertificateService personCertificateService;

    @Resource
    private ContractorManageService contractorManageService;

    @Resource
    private PlatformPersonInfoService platformPersonInfoService;

    @Resource
    private PersonInInfoMapper PersonInInfoMapper;

    @Resource
    private PersonCertificateMapper personCertificateMapper;

    @Resource
    private PlatformPersonTimeInfoMapper platformPersonTimeInfoMapper;

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int LENGTH = 17;

    @Override
    public MessageInfo<PersonGoSeaWorkStatusVO> queryPersonGoSeaWorkStatus(PersonGoSeaParam personGoSeaParam) {


        PersonGoSeaWorkStatusVO personGoSeaWorkStatusVO = new PersonGoSeaWorkStatusVO();
        //今日开始时间
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        //今日结束时间
        LocalDateTime endOfDay = startOfDay.plusHours(23).plusMinutes(59).plusSeconds(59);

        //当日在平台人数 onPlatformAll
        List<PersonTodayPlatformInformationVO> personTodayPlatformInformationList = platformPersonTimeInfoMapper.getPersonTodayPlatformInformationList(personGoSeaParam);


        int onPlatformAll = personTodayPlatformInformationList.size();

        //今日登平台数量
        List<PersonInInfo> personInInfos = PersonInInfoService.list(
                Wrappers.lambdaQuery(PersonInInfo.class)
                        .eq(StringUtil.isNotBlank(personGoSeaParam.getAppId()), PersonInInfo::getAppId, personGoSeaParam.getAppId())
                        .eq(StringUtil.isNotBlank(personGoSeaParam.getPlatformId()), PersonInInfo::getPlatformCode, personGoSeaParam.getPlatformId())
                        .between(PersonInInfo::getInTime, startOfDay, endOfDay)
        );

        int onPlatformTodayCount = personInInfos.size();

        //今日离平台数量
        List<PersonOutInfo> personOutInfos = PersonOutInfoService.list(
                Wrappers.lambdaQuery(PersonOutInfo.class)
                        .eq(StringUtil.isNotBlank(personGoSeaParam.getAppId()), PersonOutInfo::getAppId, personGoSeaParam.getAppId())
                        .eq(StringUtil.isNotBlank(personGoSeaParam.getPlatformId()), PersonOutInfo::getPlatformCode, personGoSeaParam.getPlatformId())
                        .between(PersonOutInfo::getOutTime, startOfDay, endOfDay)
        );

        int leavePlatformYesterdayCount = personOutInfos.size();

        //当日在平台内部人员
        int inPlatformTodayInternalNumber = (int) personTodayPlatformInformationList.stream().filter(item -> Objects.equals(item.getPersonType(), 1)).count();
        //当日在平台承包商人员
        int inPlatformTodayContractorNumber = (int) personTodayPlatformInformationList.stream().filter(item -> Objects.equals(item.getPersonType(), 2)).count();
        //当日在平台其他人员
        long otherInPlatformTodayCount = personTodayPlatformInformationList.stream().filter(item -> !Objects.equals(item.getPersonType(), 1) && !Objects.equals(item.getPersonType(), 2)).count();


        //当日登平台内部人员数量
        int onPlatformTodayInternalNumber = (int) personInInfos.stream().filter(item -> Objects.equals(item.getPersonType(), "1")).count();
        //当日登平台承包商人员
        int onPlatformTodayContractorNumber = (int) personInInfos.stream().filter(item -> Objects.equals(item.getPersonType(), "2")).count();
        //当日登平台其他人员
        long otherOnPlatformTodayCount = personInInfos.stream().filter(item -> !Objects.equals(item.getPersonType(), "1") && !Objects.equals(item.getPersonType(), "2")).count();

        //当日离平台内部人员
        int leavePlatformTodayInternalNumber = (int) personOutInfos.stream().filter(item -> Objects.equals(item.getPersonType(), "1")).count();
        //当日离平台承包商人员
        int leavePlatformTodayContractorNumber = (int) personOutInfos.stream().filter(item -> Objects.equals(item.getPersonType(), "2")).count();
        //当日离平台其他人员
        long otherLeavePlatformTodayCount = personOutInfos.stream().filter(item -> !Objects.equals(item.getPersonType(), "1") && !Objects.equals(item.getPersonType(), "2")).count();

        personGoSeaWorkStatusVO.setInPlatformTodayCount((long) onPlatformAll);
        personGoSeaWorkStatusVO.setLeavePlatformToday((long) leavePlatformYesterdayCount);
        personGoSeaWorkStatusVO.setOnPlatformTodayCount((long) onPlatformTodayCount);
        personGoSeaWorkStatusVO.setInPlatformTodayInternalNumber(inPlatformTodayInternalNumber);
        personGoSeaWorkStatusVO.setInPlatformTodayContractorNumber((long) inPlatformTodayContractorNumber);
        personGoSeaWorkStatusVO.setOnPlatformTodayInternalNumber(onPlatformTodayInternalNumber);
        personGoSeaWorkStatusVO.setOnPlatformTodayContractorNumber(onPlatformTodayContractorNumber);
        personGoSeaWorkStatusVO.setLeavePlatformTodayInternalNumber(leavePlatformTodayInternalNumber);
        personGoSeaWorkStatusVO.setLeavePlatformTodayContractorNumber(leavePlatformTodayContractorNumber);
        personGoSeaWorkStatusVO.setInPlatformTodayOtherNumber(otherInPlatformTodayCount);
        personGoSeaWorkStatusVO.setOnPlatformTodayOtherNumber(otherOnPlatformTodayCount);
        personGoSeaWorkStatusVO.setLeavePlatformTodayOtherNumber(otherLeavePlatformTodayCount);

        return MessageInfo.ok(personGoSeaWorkStatusVO);
    }

    @Override
    public MessageInfo<CertificateExpireWarningVO> queryCertificateExpireWarning(PersonCertificateParam personCertificateParam) {
        //五四小证总数
        Long allCount = personCertificateMapper.getCertificateExpireWarningCount(personCertificateParam);

        //逾期人数
        personCertificateParam.setExpireFlag(1);
        Long expireCount = personCertificateMapper.getCertificateExpireWarningCount(personCertificateParam);

        //即将过期
        Long willExpireCount = personCertificateMapper.getCertificateExpireWarningCount(personCertificateParam.setWillExpireFlag(1).setExpireFlag(0));


        CertificateExpireWarningVO certificateExpireWarningVO = new CertificateExpireWarningVO()
                .setExpireCount(expireCount)
                .setWillExpireCount( willExpireCount)
                .setAllCount(allCount);

        return MessageInfo.ok(certificateExpireWarningVO);
    }

    @Override
    public MessageInfo<IPage<PersonGoSeaDetailInformationVO>> queryPersonGoSeaDetailInformationPage(Page page, PersonGoSeaParam personGoSeaParam) {
        IPage<PersonGoSeaDetailInformationVO> personGoSeaDetailInformationPage = PersonInInfoMapper.getPersonGoSeaDetailInformationPage(page, personGoSeaParam);

        return MessageInfo.ok(personGoSeaDetailInformationPage);
    }

    @Override
    public MessageInfo<IPage<PersonCertificateVO>> queryCertificateExpireWarningPage(Page page, PersonCertificateParam param) {
     IPage<PersonCertificateVO> certificateExpireWarningPage = personCertificateMapper.getCertificateExpireWarningPage(page, param);
        return MessageInfo.ok(certificateExpireWarningPage);
    }

    @Override
    public MessageInfo<IPage<PersonTodayPlatformInformationVO>> queryPersonTodayPlatformInformationPage(Page page, PersonGoSeaParam personGoSeaParam) {

        return MessageInfo.ok(platformPersonTimeInfoMapper.getPersonTodayPlatformInformationPage(page, personGoSeaParam));
    }

    @Override
    public MessageInfo<IPage<PersonPlatformRankVO>> queryPersonPlatformRankPage(Page page, PersonGoSeaParam personGoSeaParam) {
        return MessageInfo.ok(platformPersonTimeInfoMapper.getPersonPlatformRankPage(page, personGoSeaParam));
    }

    @Override
    public MessageInfo<List<RecentPeopleLineChartVO>> queryRecentPeopleLineChart(RecentPeopleLineChartParam param) {
        List<RecentPeopleLineChartVO> recentPeopleLineChartVOS = platformPersonTimeInfoMapper.queryRecentPeopleLineChart(param);
        //按照日期排序
        recentPeopleLineChartVOS.sort(Comparator.comparing(RecentPeopleLineChartVO::getDataDate));
        return MessageInfo.ok(recentPeopleLineChartVOS);
    }




    /**
     * 生成随机五四小证编号
     *
     * @return {@link String}
     */
    public static String generateRandomString() {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();

        sb.append("NTC-");

        for (int i = 0; i < LENGTH; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            char randomChar = CHARACTERS.charAt(randomIndex);
            sb.append(randomChar);

            if (i == 1 || i == 4 || i == 8 || i == 14) {
                sb.append("-");
            }
        }
        return sb.toString();
    }


    /**
     * 生成随机电话号码
     *
     * @return {@link String}
     */
    public static String generateRandomPhoneNumber() {
        Random random = new Random();

        // 生成手机号码前三位（号段）
        String[] prefixList = {
                "130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
                "150", "151", "152", "153", "155", "156", "157", "158", "159",
                "166", "170", "171", "172", "173", "174", "175", "176", "177", "178",
                "180", "181", "182", "183", "184", "185", "186", "187", "188", "189"
        };
        int randomIndex = random.nextInt(prefixList.length);
        String prefix = prefixList[randomIndex];

        // 生成手机号码后八位
        StringBuilder suffix = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            suffix.append(random.nextInt(10));
        }

        return prefix + suffix.toString();
    }


}
