package com.vctgo.system.service.impl;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.utils.Base64Helper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vctgo.common.core.constant.HttpStatus;
import com.vctgo.common.core.utils.DateUtils;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysTenant;
import com.vctgo.system.domain.SysBranchKindergarten;
import com.vctgo.system.domain.SysGardenManage;
import com.vctgo.system.domain.SysPlatformTeachQualifyCertificate;
import com.vctgo.system.mapper.*;
import com.vctgo.system.service.ISysPlatformTeachQualifyCertificateService;
import com.vctgo.system.util.StreamUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.vctgo.system.domain.SysPlatformTeachStaff;
import com.vctgo.system.service.ISysPlatformTeachStaffService;
import com.vctgo.system.util.ConstantUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;

/**
 * 教职工信息Service业务层处理
 *
 * @author caesar
 * @date 2024-03-26
 */
@Api(tags = "教职工信息")
@Slf4j
@Service
public class SysPlatformPlatformTeachStaffServiceImpl implements ISysPlatformTeachStaffService {

    @Autowired
    private SysPlatformTeachStaffMapper sysPlatformTeachStaffMapper;

    @Autowired
    private SysTenantMapper sysTenantMapper;

    @Autowired
    private KeyPair keyPair;

    @Autowired
    private SysBranchKindergartenMapper sysBranchKindergartenMapper;

    @Autowired
    private SysGardenManageMapper sysGardenManageMapper;

    /**
     * 查询教职工信息
     *
     * @param id 教职工信息主键
     * @return 教职工信息
     */
    @Override
    public SysPlatformTeachStaff selectSysTeachStaffById(Long id) {
        LambdaQueryWrapper<SysPlatformTeachStaff> sysTeachStaffWrapper = new LambdaQueryWrapper<>();
        sysTeachStaffWrapper.eq(SysPlatformTeachStaff::getIsDeleted, ConstantUtils.IS_DELETED_0);
        sysTeachStaffWrapper.eq(SysPlatformTeachStaff::getId, id);
        SysPlatformTeachStaff sysPlatformTeachStaff = sysPlatformTeachStaffMapper.selectOne(sysTeachStaffWrapper);
        if (Objects.isNull(sysPlatformTeachStaff)) {
            throw new SecurityException("该员工不存在");
        }

        Long kindergartenId = sysPlatformTeachStaff.getKindergartenId();
        String kindergartenType = sysPlatformTeachStaff.getKindergartenType();
        if (ConstantUtils.KINDERGARTEN_TYPE_1.equals(kindergartenType) || ConstantUtils.KINDERGARTEN_TYPE_2.equals(kindergartenType)) {
            SysBranchKindergarten sysBranchKindergarten = sysBranchKindergartenMapper.selectById(kindergartenId);
            if (Objects.nonNull(sysBranchKindergarten)) {
                sysPlatformTeachStaff.setProvinceId(sysBranchKindergarten.getProvinceId());
                sysPlatformTeachStaff.setCityId(sysBranchKindergarten.getCityId());
                sysPlatformTeachStaff.setDistrictId(sysBranchKindergarten.getDistrictId());
                sysPlatformTeachStaff.setBelongRegion(sysBranchKindergarten.getBelongRegion());
            }
        } else {
            SysGardenManage sysGardenManage = sysGardenManageMapper.selectById(kindergartenId);
            if (Objects.nonNull(sysGardenManage)) {
                sysPlatformTeachStaff.setProvinceId(sysGardenManage.getProvinceId());
                sysPlatformTeachStaff.setCityId(sysGardenManage.getCityId());
                sysPlatformTeachStaff.setDistrictId(sysGardenManage.getDistrictId());
                sysPlatformTeachStaff.setBelongRegion(sysGardenManage.getBelongRegion());
            }
        }

        return sysPlatformTeachStaff;
    }

    /**
     * 查询教职工信息列表-分页
     *
     * @param sysPlatformTeachStaff 教职工信息
     * @return 教职工信息
     */
    @Override
    public IPage<SysPlatformTeachStaff> selectSysTeachStaffPage(SysPlatformTeachStaff sysPlatformTeachStaff) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        IPage<SysPlatformTeachStaff> sysTeachStaffIPage = sysPlatformTeachStaffMapper.selectSysTeachStaffList(mpPage, sysPlatformTeachStaff);
        List<SysPlatformTeachStaff> sysPlatformTeachStaffList = sysTeachStaffIPage.getRecords();
        if (CollectionUtils.isEmpty(sysPlatformTeachStaffList)) {
            return new Page<>();
        }

        String[] phoneList = sysPlatformTeachStaffList.stream().map(SysPlatformTeachStaff::getPhone).toArray(String[]::new);
        List<SysTenant> sysTenantPhoneList = sysTenantMapper.slectTenantByPhoneList(phoneList);
        sysPlatformTeachStaffList.forEach(sysPlatformTeachStaffTmp -> {
            Optional<SysTenant> sysTenantOptional = Optional.empty();
            if (ConstantUtils.KINDERGARTEN_TYPE_3.equals(sysPlatformTeachStaffTmp.getKindergartenType())) {
                sysTenantOptional = sysTenantPhoneList.stream().filter(sysTenant -> Objects.nonNull(sysTenant.getGardenId())
                                && Objects.isNull(sysTenant.getBranchId())
                                && sysPlatformTeachStaffTmp.getKindergartenId().longValue() == sysTenant.getGardenId().longValue()
                                && sysPlatformTeachStaffTmp.getPhone().equals(sysTenant.getPhonenumber()))
                        .findFirst();
            } else if (ConstantUtils.KINDERGARTEN_TYPE_2.equals(sysPlatformTeachStaffTmp.getKindergartenType())) {
                sysTenantOptional = sysTenantPhoneList.stream().filter(sysTenant -> Objects.nonNull(sysTenant.getGardenId())
                                && Objects.nonNull(sysTenant.getBranchId())
                                && sysPlatformTeachStaffTmp.getKindergartenId().longValue() == sysTenant.getBranchId().longValue()
                                && sysPlatformTeachStaffTmp.getPhone().equals(sysTenant.getPhonenumber()))
                        .findFirst();
            } else if (ConstantUtils.KINDERGARTEN_TYPE_1.equals(sysPlatformTeachStaffTmp.getKindergartenType())) {
                sysTenantOptional = sysTenantPhoneList.stream().filter(sysTenant -> Objects.isNull(sysTenant.getGardenId())
                                && Objects.nonNull(sysTenant.getBranchId())
                                && sysPlatformTeachStaffTmp.getKindergartenId().longValue() == sysTenant.getBranchId().longValue()
                                && sysPlatformTeachStaffTmp.getPhone().equals(sysTenant.getPhonenumber()))
                        .findFirst();
            }
            sysTenantOptional.ifPresent(sysTenant -> sysPlatformTeachStaffTmp.setAccountStatus(sysTenant.getAccountStatus()));
        });

        // 获取所有的租户信息
        LambdaQueryWrapper<SysTenant> sysTenantWrapper = new LambdaQueryWrapper<>();
        sysTenantWrapper.eq(SysTenant::getDelFlag, ConstantUtils.IS_DELETED_0);
        sysTenantWrapper.select(SysTenant::getGardenId, SysTenant::getBranchId);
        List<SysTenant> sysTenantList = sysTenantMapper.selectList(sysTenantWrapper);
        for (SysPlatformTeachStaff sysPlatformTeachStaffTmp : sysPlatformTeachStaffList) {

            // 租户类型   （1：集团，2：幼儿园有集团 3:幼儿园无集团）
            // 幼儿园类型  1=独立幼儿园,2=集团幼儿园,3=集团
            Optional<SysTenant> sysTenantOptional = Optional.empty();
            if (ConstantUtils.KINDERGARTEN_TYPE_3.equals(sysPlatformTeachStaffTmp.getKindergartenType())) {
                sysTenantOptional = sysTenantList.stream().filter(sysTenant -> Objects.nonNull(sysTenant.getGardenId()) && Objects.isNull(sysTenant.getBranchId()) && sysPlatformTeachStaffTmp.getKindergartenId().longValue() == sysTenant.getGardenId().longValue()).findFirst();
            } else if (ConstantUtils.KINDERGARTEN_TYPE_2.equals(sysPlatformTeachStaffTmp.getKindergartenType())) {
                sysTenantOptional = sysTenantList.stream().filter(sysTenant -> Objects.nonNull(sysTenant.getGardenId()) && Objects.nonNull(sysTenant.getBranchId()) && sysPlatformTeachStaffTmp.getKindergartenId().longValue() == sysTenant.getBranchId().longValue()).findFirst();
            } else if (ConstantUtils.KINDERGARTEN_TYPE_1.equals(sysPlatformTeachStaffTmp.getKindergartenType())) {
                sysTenantOptional = sysTenantList.stream().filter(sysTenant -> Objects.isNull(sysTenant.getGardenId()) && Objects.nonNull(sysTenant.getBranchId()) && sysPlatformTeachStaffTmp.getKindergartenId().longValue() == sysTenant.getBranchId().longValue()).findFirst();
            }
            // 租户内部用户状态  1 -- 2 未开通 3 启用 4 禁用
            if (sysTenantOptional.isPresent()) {
                if (Objects.isNull(sysPlatformTeachStaffTmp.getAccountStatus())) {
                    sysPlatformTeachStaffTmp.setAccountStatus(ConstantUtils.ACCOUNT_STATUS_2);
                } else {
                    if (Objects.nonNull(sysTenantOptional.get().getStatus())) {
                        String status = sysTenantOptional.get().getStatus().toString();
                        if (ConstantUtils.ACCOUNT_STATUS_0.equals(status)) {
                            if ("0".equals(sysPlatformTeachStaffTmp.getAccountStatus())) {
                                sysPlatformTeachStaffTmp.setAccountStatus("3");
                            } else {
                                sysPlatformTeachStaffTmp.setAccountStatus("4");
                            }
                        } else if (ConstantUtils.ACCOUNT_STATUS_1.equals(status)) {
                            sysPlatformTeachStaffTmp.setAccountStatus("4");
                        }
                    }
                }
            } else {
                sysPlatformTeachStaffTmp.setAccountStatus(ConstantUtils.ACCOUNT_STATUS_1);
            }
        }

        return sysTeachStaffIPage;
    }

    /**
     * 查询教职工信息列表
     *
     * @param sysPlatformTeachStaff 教职工信息
     * @return 教职工信息
     */
    @Override
    public List<SysPlatformTeachStaff> selectSysTeachStaffList(SysPlatformTeachStaff sysPlatformTeachStaff) {
        return sysPlatformTeachStaffMapper.selectSysTeachStaffList(sysPlatformTeachStaff);
    }

    /**
     * 新增教职工信息
     *
     * @param sysPlatformTeachStaff 教职工信息
     * @return 结果
     */

    @Override
    public AjaxResult insertSysTeachStaff(SysPlatformTeachStaff sysPlatformTeachStaff) {
        boolean checkSysTeachStaff = true;
        if (StringUtils.hasText(sysPlatformTeachStaff.getStaffInfo())) {
            checkSysTeachStaff = false;
            Base64.Decoder decoder = Base64.getDecoder();
            sysPlatformTeachStaff = JSONObject.parseObject(new String(decoder.decode(sysPlatformTeachStaff.getStaffInfo()),StandardCharsets.UTF_8), SysPlatformTeachStaff.class);
        }

        sysPlatformTeachStaff.setCreateById(SecurityUtils.getUserId());

        // 查询对应的幼儿园是否开通租户 幼儿园类型：1：集团，2：幼儿园有集团 3:幼儿园无集团
        LambdaQueryWrapper<SysTenant> sysTenantWrapper = new LambdaQueryWrapper<>();
        sysTenantWrapper.eq(SysTenant::getDelFlag, ConstantUtils.IS_DELETED_0);
        sysTenantWrapper.eq(SysTenant::getTenantType, sysPlatformTeachStaff.getKindergartenType());
        sysTenantWrapper.eq(ConstantUtils.KINDERGARTEN_TYPE_1.equals(sysPlatformTeachStaff.getKindergartenType()), SysTenant::getGardenId, sysPlatformTeachStaff.getKindergartenId());
        sysTenantWrapper.eq(ConstantUtils.KINDERGARTEN_TYPE_2.equals(sysPlatformTeachStaff.getKindergartenType()) || ConstantUtils.KINDERGARTEN_TYPE_3.equals(sysPlatformTeachStaff.getKindergartenType()), SysTenant::getBranchId, sysPlatformTeachStaff.getKindergartenId());
        List<SysTenant> sysTenantList = sysTenantMapper.selectList(sysTenantWrapper);
        if (CollectionUtils.isNotEmpty(sysTenantList)) {
            throw new SecurityException("当前幼儿园已开通租户,不能添加职工信息");
        }

        // 判断当前手机号是否存在
        String phone = sysPlatformTeachStaff.getPhone();
        LambdaQueryWrapper<SysPlatformTeachStaff> sysTeachStaffWrapper = new LambdaQueryWrapper<>();
        sysTeachStaffWrapper.eq(SysPlatformTeachStaff::getIsDeleted, ConstantUtils.IS_DELETED_0);
        sysTeachStaffWrapper.eq(SysPlatformTeachStaff::getPhone, phone);
        List<SysPlatformTeachStaff> sysPlatformTeachStaffList = sysPlatformTeachStaffMapper.selectList(sysTeachStaffWrapper);

        // 该手机在当前用户中有
        if (CollectionUtils.isNotEmpty(sysPlatformTeachStaffList)) {
            SysPlatformTeachStaff finalSysPlatformTeachStaff = sysPlatformTeachStaff;
            Optional<SysPlatformTeachStaff> sysTeachStaffOptional = sysPlatformTeachStaffList.stream()
                    .filter(sysTeachStaffTmp -> sysTeachStaffTmp.getKindergartenId().longValue() == finalSysPlatformTeachStaff.getKindergartenId().longValue()
                    && sysTeachStaffTmp.getKindergartenType().equals(finalSysPlatformTeachStaff.getKindergartenType())).findFirst();
            if (sysTeachStaffOptional.isPresent()) {
                throw new SecurityException("该手机号在选中幼儿园下已存在，请核对后再试");
            } else if (checkSysTeachStaff) {
                Base64.Encoder encoder = Base64.getEncoder();
                String encrypt = encoder.encodeToString(JSONObject.toJSONString(sysPlatformTeachStaff).getBytes(StandardCharsets.UTF_8));
                return AjaxResult.error(HttpStatus.ADD_STAFF_ERROR,"该手机号为其他幼儿园教职工手机号，是否确认保存？", encrypt);
            }
        }
        sysPlatformTeachStaff.setInformationSource(ConstantUtils.STAFF_INFO_SOURCE_PLATFORM);
        return sysPlatformTeachStaffMapper.insert(sysPlatformTeachStaff) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改教职工信息
     *
     * @param sysPlatformTeachStaff 教职工信息
     * @return 结果
     */
    @Override
    public AjaxResult updateSysTeachStaff(SysPlatformTeachStaff sysPlatformTeachStaff) {

        boolean checkSysTeachStaff = true;
        if (StringUtils.hasText(sysPlatformTeachStaff.getStaffInfo())) {
            checkSysTeachStaff = false;
            Base64.Decoder decoder = Base64.getDecoder();
            sysPlatformTeachStaff = JSONObject.parseObject(new String(decoder.decode(sysPlatformTeachStaff.getStaffInfo()), StandardCharsets.UTF_8), SysPlatformTeachStaff.class);
        }

        // 判断当前手机号是否存在
        LambdaQueryWrapper<SysPlatformTeachStaff> sysTeachStaffWrapper = new LambdaQueryWrapper<>();
        sysTeachStaffWrapper.eq(SysPlatformTeachStaff::getIsDeleted, ConstantUtils.IS_DELETED_0);
        sysTeachStaffWrapper.eq(SysPlatformTeachStaff::getPhone, sysPlatformTeachStaff.getPhone());
        List<SysPlatformTeachStaff> sysPlatformTeachStaffList = sysPlatformTeachStaffMapper.selectList(sysTeachStaffWrapper);

        SysPlatformTeachStaff finalSysPlatformTeachStaffTmp = sysPlatformTeachStaff;
        long count = sysPlatformTeachStaffList.stream().filter(sysPlatformTeachStaffTmp ->
                finalSysPlatformTeachStaffTmp.getKindergartenId().longValue() == sysPlatformTeachStaffTmp.getKindergartenId().longValue()
                        && sysPlatformTeachStaffTmp.getKindergartenType().equals(finalSysPlatformTeachStaffTmp.getKindergartenType())
                        && sysPlatformTeachStaffTmp.getId().longValue() == finalSysPlatformTeachStaffTmp.getId().longValue()
                        && sysPlatformTeachStaffTmp.getPhone().equals(finalSysPlatformTeachStaffTmp.getPhone())).count();

        // 该手机在当前用户中有
        if (0L == count && CollectionUtils.isNotEmpty(sysPlatformTeachStaffList)) {
            SysPlatformTeachStaff finalSysPlatformTeachStaff = sysPlatformTeachStaff;
            Optional<SysPlatformTeachStaff> sysTeachStaffOptional = sysPlatformTeachStaffList.stream()
                    .filter(sysTeachStaffTmp -> sysTeachStaffTmp.getKindergartenId().longValue() == finalSysPlatformTeachStaff.getKindergartenId().longValue()
                            && sysTeachStaffTmp.getKindergartenType().equals(finalSysPlatformTeachStaff.getKindergartenType())).findAny();
            if (sysTeachStaffOptional.isPresent()) {
                throw new SecurityException("该手机号在选中幼儿园下已存在，请核对后再试");
            }

            if (checkSysTeachStaff) {
                Base64.Encoder encoder = Base64.getEncoder();
                String encrypt = encoder.encodeToString(JSONObject.toJSONString(sysPlatformTeachStaff).getBytes(StandardCharsets.UTF_8));
                return AjaxResult.error(HttpStatus.ADD_STAFF_ERROR, "该手机号为其他幼儿园教职工手机号，是否确认保存？", encrypt);
            }
        }

        return sysPlatformTeachStaffMapper.updateById(sysPlatformTeachStaff) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 逻辑删除教职工信息
     *
     * @param ids 需要删除的教职工信息主键
     * @return 结果
     */
    @Override
    public int logicalDeleteSysTeachStaffByIds(Long[] ids, Long kindergartenId) {
        SysPlatformTeachStaff sysPlatformTeachStaff = new SysPlatformTeachStaff();
        sysPlatformTeachStaff.setUpdateById(SecurityUtils.getUserId());
        sysPlatformTeachStaff.setUpdateBy(SecurityUtils.getUsername());
        sysPlatformTeachStaff.setUpdateTime(new Date());
        sysPlatformTeachStaff.setIsDeleted(ConstantUtils.IS_DELETED_1);
        sysPlatformTeachStaff.setKindergartenId(kindergartenId);
        return sysPlatformTeachStaffMapper.logicalDeleteSysTeachStaffByIds(ids, sysPlatformTeachStaff);
    }

    /**
     * 批量删除教职工信息
     *
     * @param ids 需要删除的教职工信息主键
     * @return 结果
     */
    @Override
    public int deleteSysTeachStaffByIds(Long[] ids) {
        return sysPlatformTeachStaffMapper.deleteSysTeachStaffByIds(ids);
    }

    /**
     * 删除教职工信息信息
     *
     * @param id 教职工信息主键
     * @return 结果
     */
    @Override
    public int deleteSysTeachStaffById(Long id) {
        return sysPlatformTeachStaffMapper.deleteById(id);
    }
}
