package com.dkl.large.service.impl;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.koal.kms.sdk.ed.KmsSdkException;
import com.dkl.common.annotation.DataScope;
import com.dkl.common.constant.UserConstants;
import com.dkl.common.core.domain.entity.SysDictData;
import com.dkl.common.core.domain.entity.SysUser;
import com.dkl.common.exception.ServiceException;
import com.dkl.common.utils.DateUtils;
import com.dkl.common.utils.SecurityUtils;
import com.dkl.common.utils.StringUtils;
import com.dkl.common.utils.bean.BeanValidators;
import com.dkl.large.domain.DklActivity;
import com.dkl.large.mapper.DklActivityMapper;
import com.dkl.large.service.IDklActivityService;
import com.dkl.large.utli.EnciphermentUtil;
import com.dkl.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.dkl.common.utils.SecurityUtils.getDeptId;
import static com.dkl.common.utils.SecurityUtils.getUsername;
import static org.springframework.util.SerializationUtils.serialize;

/**
 * 大客流活动Service业务层处理
 *
 * @author Dkl
 * @date 2025-05-27
 */
@Service
public class DklActivityServiceImpl implements IDklActivityService
{
    @Autowired
    private DklActivityMapper dklActivityMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    static EnciphermentUtil enciphermentUtil;
    //手机号正则
    private static final String PHONE_REGEX = "^((0\\d{2,3}-\\d{7,8})|(1[3456789]\\d{9}))$";
    //经度
    private static final String LNG_REGEX = "^-?\\d{1,3}(\\.\\d+)?$";
    //维度
    private static final String LAT_REGEX = "^-?\\d{1,2}(\\.\\d+)?$";
    /**
     * 查询大客流活动
     *
     * @param id 大客流活动主键
     * @return 大客流活动
     */
    @Override
    public DklActivity selectDklActivityById(int id) throws KmsSdkException {
        DklActivity dklActivityInfo =dklActivityMapper.selectDklActivityById(id);
        if (StringUtils.isNotEmpty(dklActivityInfo.getDutyPeople())&&StringUtils.isNotEmpty(dklActivityInfo.getDutyPhone())) {
            String dutyPeople = dklActivityInfo.getDutyPeople();
            String dutyPhone = dklActivityInfo.getDutyPhone();
            dklActivityInfo.setDutyPeople(EnciphermentUtil.kmsDencrypt(dutyPeople));
            dklActivityInfo.setDutyPhone(EnciphermentUtil.kmsDencrypt(dutyPhone));
        }
        return dklActivityInfo;
    }

    /**
     * 查询大客流活动列表
     *
     * @param dklActivity 大客流活动
     * @return 大客流活动
     */
    @Override
    public List<DklActivity> selectDklActivityList(DklActivity dklActivity) throws KmsSdkException {
        List<DklActivity> list = dklActivityMapper.selectDklActivityList(dklActivity);
        for (DklActivity dklActivityInfo : list) {
            if (StringUtils.isNotEmpty(dklActivityInfo.getDutyPeople())&&("0").equals(dklActivityInfo.getDelFlag())) {
            String dutyPeople = dklActivityInfo.getDutyPeople();
            dklActivityInfo.setDutyPeople(EnciphermentUtil.kmsDencrypt(dutyPeople));
            }
            if (StringUtils.isNotEmpty(dklActivityInfo.getDutyPhone())&&("0").equals(dklActivityInfo.getDelFlag())) {
                String dutyPhone = dklActivityInfo.getDutyPhone();
                dklActivityInfo.setDutyPhone(EnciphermentUtil.kmsDencrypt(dutyPhone));
            }
//            if (StringUtils.isNotEmpty(dklActivityInfo.getSigenCode())&&("0").equals(dklActivityInfo.getDelFlag())) {
//                byte[] bytes = serialize(dklActivityInfo.getDutyPeople()+","+dklActivityInfo.getDutyPhone());
//                    boolean isor =  EnciphermentUtil.verifySign(bytes,dklActivityInfo.getSigenCode());
//                    if (isor) {
//                        dklActivityList.add(dklActivityInfo);
//                    }
//
//            }
        }
        return list;
    }

    @Override
    public String selectDklActivityListMessage(DklActivity dklActivity) throws KmsSdkException {
        StringBuilder successMsg = new StringBuilder();
        List<DklActivity> list = dklActivityMapper.selectDklActivityList(dklActivity);
        for (DklActivity dklActivityInfo : list) {
            if (StringUtils.isNotEmpty(dklActivityInfo.getDutyPeople())&&("0").equals(dklActivityInfo.getDelFlag())) {
                String dutyPeople = dklActivityInfo.getDutyPeople();
                dklActivityInfo.setDutyPeople(EnciphermentUtil.kmsDencrypt(dutyPeople));
            }
            if (StringUtils.isNotEmpty(dklActivityInfo.getDutyPhone())&&("0").equals(dklActivityInfo.getDelFlag())) {
                String dutyPhone = dklActivityInfo.getDutyPhone();
                dklActivityInfo.setDutyPhone(EnciphermentUtil.kmsDencrypt(dutyPhone));
            }
            if (StringUtils.isNotEmpty(dklActivityInfo.getSigenCode())&&("0").equals(dklActivityInfo.getDelFlag())) {
                byte[] bytes = serialize(dklActivityInfo.getDutyPeople()+","+dklActivityInfo.getDutyPhone());
                    String isor = EnciphermentUtil.kmsSign(bytes);
                    if (!isor.equals(dklActivityInfo.getSigenCode())) {
                        successMsg.append("活动名称为"+dklActivityInfo.getActivityName()+"的数据被篡改");
                    }

            }
        }
        return successMsg.toString();
    }


    /**
     * 新增大客流活动
     *
     * @param dklActivity 大客流活动
     * @return 结果
     */
    @Override
    public int insertDklActivity(DklActivity dklActivity) throws KmsSdkException {


        String dutyPeople = dklActivity.getDutyPeople();
        String dutyPhone = dklActivity.getDutyPhone();
        dklActivity.setDutyPeople(EnciphermentUtil.kmsEncrypt(dutyPeople));
        dklActivity.setDutyPhone(EnciphermentUtil.kmsEncrypt(dutyPhone));
        // （序列化）
        byte[] bytes = serialize(dutyPeople+","+dutyPhone);
        String sigenCode = EnciphermentUtil.kmsSign(bytes);
        dklActivity.setSigenCode(sigenCode);
        return dklActivityMapper.insertDklActivity(dklActivity);
    }

    /**
     * 修改大客流活动
     *
     * @param dklActivity 大客流活动
     * @return 结果
     */
    @Override
    public int updateDklActivity(DklActivity dklActivity) throws KmsSdkException {
        dklActivity.setUpdateTime(DateUtils.getNowDate());
        String dutyPeople = dklActivity.getDutyPeople();
        String dutyPhone = dklActivity.getDutyPhone();
        dklActivity.setDutyPeople(EnciphermentUtil.kmsEncrypt(dutyPeople));
        dklActivity.setDutyPhone(EnciphermentUtil.kmsEncrypt(dutyPhone));
        // （序列化）
        byte[] bytes = serialize(dutyPeople+","+dutyPhone);
        String sigenCode = EnciphermentUtil.kmsSign(bytes);
        dklActivity.setSigenCode(sigenCode);
        return dklActivityMapper.updateDklActivity(dklActivity);
    }

    /**
     * 批量删除大客流活动
     *
     * @param ids 需要删除的大客流活动主键
     * @return 结果
     */
    @Override
    public int deleteDklActivityByIds(int[] ids)
    {
        return dklActivityMapper.deleteDklActivityByIds(ids);
    }

    /**
     * 删除大客流活动信息
     *
     * @param id 大客流活动主键
     * @return 结果
     */
    @Override
    public int deleteDklActivityById(int id)
    {
        return dklActivityMapper.deleteDklActivityById(id);
    }

    /**
     * @Author :rq
     * @Description :大屏预警信息统计
     * @Date :2025/06/09 10:22
     * @Param :[]
     * @return :java.util.List<com.dkl.large.domain.DklActivity>
     **/
    @Override
    public List<DklActivity> ativityEarlyWarning(DklActivity dklActivity) {
        return dklActivityMapper.ativityEarlyWarning(dklActivity);
    }

    /**
     * @Author :rq
     * @Description :大屏重点场所热力图/景区热力图
     * @Date :2025/06/09 13:22
     * @Param :[]
     * @return :java.util.List<com.dkl.large.domain.DklActivity>
     **/
    @Override
    public List<DklActivity> thermogramStatistics(DklActivity dklActivity) {
        return dklActivityMapper.thermogramStatistics(dklActivity);
    }

    @Override
    public List<DklActivity> homeActivityStatistics(DklActivity dklActivity) {
        return dklActivityMapper.homeActivityStatistics(dklActivity);
    }

    @Override
    public List<DklActivity> homeActivityStatisticsPeople(DklActivity dklActivity) {
        return dklActivityMapper.homeActivityStatisticsPeople(dklActivity);
    }

    @Override
    public String importDate(List<DklActivity> activityList, String operName) throws KmsSdkException {
        //区域集合
        List<SysDictData> areaDict=sysDictDataMapper.selectDictDataByType("activity_area");
        //所有大客流活动
        DklActivity dklActivity = new DklActivity();
        dklActivity.setDelFlag("0");
        List<DklActivity> activitys= dklActivityMapper.selectDklActivityList(dklActivity);
        if (StringUtils.isNull(activityList) || activityList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
            for (int i = 0; i < activityList.size(); i++) {
            try
            {
                //活动名称
            if (StringUtils.isEmpty(activityList.get(i).getActivityName())){
                failureNum++;
                failureMsg.append("<br/> 第" + (i+1) + "条数据活动名称为空");
            }else{
                if (activityList.get(i).getActivityName().length()>=30){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据活动名称长度过长");
                }
            }

            //节假日名称
                if (StringUtils.isEmpty(activityList.get(i).getHolidayName())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据节假日名称为空");
                }else{
                    if (activityList.get(i).getHolidayName().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" +(i+1)+ "条数据节假日名称长度过长");
                    }
                }

                //地址
                if (StringUtils.isEmpty(activityList.get(i).getAddress())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1)+ "条数据地址为空");
                }else{
                    if (activityList.get(i).getAddress().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据地址长度过长");
                    }
                }

                //区域
                if (StringUtils.isEmpty(activityList.get(i).getRegionname())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1)+ "条数据区域为空");
                }else{
                    if (activityList.get(i).getRegionname().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" +(i+1) + "条数据区域长度过长");
                    }else{
                        for (SysDictData sysDictData : areaDict) {
                            if (sysDictData.getDictLabel().equals(activityList.get(i).getRegionname())) {
                                activityList.get(i).setRegion(sysDictData.getDictValue());
                                break;
                            }

                        }
                        if (StringUtils.isEmpty(activityList.get(i).getRegion())){
                            failureNum++;
                            failureMsg.append("<br/> 第" +(i+1) + "条数据区域未找到");
                        }
                    }
                }

                //重点日标识
                if (StringUtils.isEmpty(activityList.get(i).getIsKeyDay())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据重点日标识为空");
                }else{
                    if (activityList.get(i).getIsKeyDay().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" +(i+1)+ "条数据重点日标识长度过长");
                    }else{
                            if (!("Y").equals(activityList.get(i).getIsKeyDay())&&!("N").equals(activityList.get(i).getIsKeyDay())) {
                                failureNum++;
                                failureMsg.append("<br/> 第" + (i+1) + "条数据重点日标识有误");
                            }
                    }
                }

                //开始时间
                if (StringUtils.isEmpty(activityList.get(i).getStartTime().toString())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据开始时间为空,时间应该为yyyy-MM-dd HH:mm:ss");
                }

                //结束时间
                if (StringUtils.isEmpty(activityList.get(i).getEndTime().toString())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据结束时间为空,时间应该为yyyy-MM-dd HH:mm:ss");
                }

                //值班人员
                if (StringUtils.isEmpty(activityList.get(i).getDutyPeople())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据值班人员为空");
                }else{
                    if (activityList.get(i).getDutyPeople().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据值班人员长度过长");
                    }
                }

                //值班联系方式
                if (StringUtils.isEmpty(activityList.get(i).getDutyPhone())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据值班联系方式为空");
                }else{
                    if (activityList.get(i).getDutyPhone().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据值班联系方式长度过长");
                    }else if (!Pattern.matches(PHONE_REGEX, activityList.get(i).getDutyPhone())){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据值班联系方式有误");
                    }
                }


                //经度
                if (StringUtils.isEmpty(activityList.get(i).getLng())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据经度为空");
                }else{
                    if (activityList.get(i).getLng().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据经度长度过长");
                    }else if (!Pattern.matches(LNG_REGEX, activityList.get(i).getLng())){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据值经度有误");
                    }
                }

                //纬度
                if (StringUtils.isEmpty(activityList.get(i).getLat())){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据纬度为空");
                }else{
                    if (activityList.get(i).getLat().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据纬度长度过长");
                    }else if (!Pattern.matches(LAT_REGEX, activityList.get(i).getLat())){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据值纬度有误");
                    }
                }

                //纬度
                if (activityList.get(i).getLoadBearingMax()<=0){
                    failureNum++;
                    failureMsg.append("<br/> 第" + (i+1) + "条数据最大承载量为空");
                }else{
                    if (activityList.get(i).getLoadBearingMax()>=999999999){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1) + "条数据最大承载量长度过长");
                    }
                }

                //活动内容
                if (StringUtils.isEmpty(activityList.get(i).getActivityText())){
                    failureNum++;
                    failureMsg.append("<br/> 第" +(i+1) + "条数据活动内容为空");
                }else{
                    if (activityList.get(i).getActivityText().length()>=30){
                        failureNum++;
                        failureMsg.append("<br/> 第" + (i+1)+ "条数据活动内容长度过长");
                    }
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "导入失败：";
                failureMsg.append(msg + e.getMessage());
            }

        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            List<DklActivity> lists = Stream.of(activitys, activityList)
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());

            boolean hasDuplicates = lists.stream()
                    .map(DklActivity::getActivityName)
                    .distinct()
                    .count() != lists.size();
            if(hasDuplicates){
                failureMsg.insert(0, "很抱歉，导入失败！共导入数据中有和系统原数据名称相同的数据");
                throw new ServiceException(failureMsg.toString());

            }else{
            for (DklActivity activity :activityList){
                //添加系统信息
                activity.setDelFlag("0");
                activity.setCreateTime(new Date());
                activity.setCreateBy(getUsername());
                activity.setDeptId(getDeptId());
                activity.setUpdateTime(new Date());
                activity.setUpdateBy(getUsername());
                String dutyPeople = activity.getDutyPeople();
                String dutyPhone = activity.getDutyPhone();
                activity.setDutyPeople(EnciphermentUtil.kmsEncrypt(dutyPeople));
                activity.setDutyPhone(EnciphermentUtil.kmsEncrypt(dutyPhone));
//
//                if (StringUtils.isNotEmpty(dklActivityInfo.getDutyPeople())&&("0").equals(dklActivityInfo.getDelFlag())) {
//                    String dutyPeople = dklActivityInfo.getDutyPeople();
//                    dklActivityInfo.setDutyPeople(EnciphermentUtil.kmsDencrypt(dutyPeople));
//                }
//                if (StringUtils.isNotEmpty(dklActivityInfo.getDutyPhone())&&("0").equals(dklActivityInfo.getDelFlag())) {
//                    String dutyPhone = dklActivityInfo.getDutyPhone();
//                    dklActivityInfo.setDutyPhone(EnciphermentUtil.kmsDencrypt(dutyPhone));
//                }
//                if (StringUtils.isNotEmpty(dklActivityInfo.getSigenCode())&&("0").equals(dklActivityInfo.getDelFlag())) {
//                    byte[] bytes = serialize(dklActivityInfo.getDutyPeople()+","+dklActivityInfo.getDutyPhone());
//                    String isor = EnciphermentUtil.kmsSign(bytes);
//                    if (!isor.equals(dklActivityInfo.getSigenCode())) {
//                        successMsg.append("活动名称为"+dklActivityInfo.getActivityName()+"的数据被篡改");
//                    }
//
//                }
                // （序列化）
                byte[] bytes = serialize(dutyPeople+","+dutyPhone);
                String sigenCode = EnciphermentUtil.kmsSign(bytes);
                activity.setSigenCode(sigenCode);
                dklActivityMapper.insertDklActivity(activity);
            }
            successMsg.insert(0, "恭喜您，数据已全部导入成功！");
            }
        }

            return successMsg.toString();
        }

    @Override
    public boolean checkActivityNameUnique(DklActivity dklActivity) {
        Long activityId = StringUtils.isNull(dklActivity.getId()) ? -1L : dklActivity.getId();
        DklActivity info =dklActivityMapper.checkActivityNameUnique(dklActivity.getActivityName());
        if (StringUtils.isNotNull(info) && info.getId() != activityId)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


}
