package com.bonus.material.notice.service.impl;

import cn.hutool.json.JSONObject;
import com.ah.sbd.SmsTool;
import com.ah.sbd.utils.param.SmsParam;
import com.bonus.common.biz.constant.BmConfigItems;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.biz.enums.NoticeSmsEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.utils.sms.SmsUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.notice.entity.Notice;
import com.bonus.material.notice.mapper.NoticeMapper;
import com.bonus.material.notice.service.NoticeService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @Author：liang.chao
 * @Date：2024/12/20 - 19:23
 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Resource
    private NoticeMapper noticeMapper;

    /**
     * 查询通知公告列表
     * @param notice
     * @return
     */
    @Override
    public List<Notice> selectNoticeList(Notice notice) {
        Long userId = SecurityUtils.getUserId();
        // 根据userId查询角色id
        List<Notice> dtoList = noticeMapper.selectRoleId(userId);
        // 从dtoList中取出roleId集合
        List<Long> roleIdList = new ArrayList<>();
        for (Notice info : dtoList) {
            roleIdList.add(info.getRoleId());
        }
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        List<Notice> list = noticeMapper.selectNoticeList(notice);
        if (!CollectionUtils.isEmpty(list)) {
            // 后台默认全部展示
            if (notice.getIsHome() != null && notice.getIsHome() == 1) {
                return list;
            }
            Iterator<Notice> iterator = list.iterator();
            while (iterator.hasNext()) {
                Notice info = iterator.next();
                // 过滤关闭公告
                if ("1".equals(info.getStatus())) {
                    iterator.remove();
                    continue;
                }
                // 过期公告过滤
                if (info.getExpiryDate() != null) {
                    if (info.getExpiryDate().before(DateUtils.getNowDate())) {
                        iterator.remove();
                        continue;
                    }
                }
                // 根据角色和部门进行过滤
                if (info.getDeptId() != null && info.getRoleId() == null) {
                    if (!info.getDeptId().equals(deptId)) {
                        iterator.remove();
                        continue;
                    }
                }
                if (info.getRoleId() != null && info.getDeptId() == null) {
                    if (!roleIdList.contains(info.getRoleId())) {
                        iterator.remove();
                        continue;
                    }
                }
                if (info.getDeptId() != null && info.getRoleId() != null) {
                    if (!info.getDeptId().equals(deptId) || !roleIdList.contains(info.getRoleId())) {
                        iterator.remove();
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Notice> noticeList(Notice notice) {
        return noticeMapper.noticeList(notice);
    }

    @Override
    public List<Notice> messageList(Notice notice) {
        notice.setOwnCo(SecurityUtils.getLoginUser().getSysUser().getCompanyId().intValue());
        return noticeMapper.messageList(notice);
    }

    /**
     * 新增通知公告
     * @param notice
     * @return
     */
    @Override
    public AjaxResult insertNotice(Notice notice) {
        if (notice == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        // 针对于短信通告进行短信人员通知
        if (NoticeSmsEnum.SENDSMS_ENABLED.getCode().equals(notice.getIsSms())) {
            if (NoticeSmsEnum.SENDSMS_DISABLED.getCode().equals(notice.getStatus())) {
                return AjaxResult.error("通知公告状态为关闭，无法进行发送短信通知公告服务");
            }
            List<Notice> smsList = noticeMapper.getSmsList(notice);
            if (CollectionUtils.isEmpty(smsList)) {
                return AjaxResult.error("所选组织机构及角色下属人员信息为空，无法进行发送短信通知公告服务");
            }
            if (!CollectionUtils.isEmpty(smsList)) {
                for (Notice info : smsList) {
                    if (StringUtils.isBlank(info.getPhoneNumber())) {
                        continue;
                    }
                    String phoneNumber = info.getPhoneNumber();
                    if (Objects.nonNull(info.getPhoneNumber()) && info.getPhoneNumber().length() > 11) {
                        phoneNumber = Sm4Utils.decrypt(info.getPhoneNumber());
                    }
                    // 根据电话号码数量发送短信
                    JSONObject sendResult = SmsTool.sendSms(new SmsParam(phoneNumber, notice.getNoticeContent()), BmConfigItems.ANHUI_COMPANY_SMS_KEY);
                    // 公司内部短信发送
                    //String sendResult = SmsUtils.smsToken(phoneNumber, notice.getNoticeContent(), "");
                    if (StringUtils.isBlank(sendResult.toString())) {
                        return AjaxResult.error("短信发送失败");
                    } else {
                        System.out.println("短信发送成功:" + sendResult);
                    }
                }
            }
        }
        notice.setCreateTime(DateUtils.getNowDate());
        int result = noticeMapper.addNotice(notice);
        if (result == 0) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
        }
        return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg());
    }

    /**
     * 修改通知公告
     * @param notice
     * @return
     */
    @Override
    public AjaxResult updateNotice(Notice notice) {
        if (notice == null || notice.getNoticeId() == null) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        // 查询通知公告
        List<Notice> list = noticeMapper.selectNoticeList(notice);
        List<Notice> smsList = new ArrayList<>();
        Notice info = new Notice();
        if (!CollectionUtils.isEmpty(list)) {
            info = list.get(0);
            if (NoticeSmsEnum.SENDSMS_ENABLED.getCode().equals(info.getIsSms())) {
                // 查询上一次已经发送的短信人员
                smsList = noticeMapper.getSmsList(info);
            }
        }
        // 进行短信通知公告
        if (NoticeSmsEnum.SENDSMS_ENABLED.getCode().equals(notice.getIsSms())) {
            if (NoticeSmsEnum.SENDSMS_DISABLED.getCode().equals(notice.getStatus())) {
                return AjaxResult.error("通知公告状态为关闭，无法进行发送短信通知公告服务");
            }
            // 查询待短信通知公告人员
            List<Notice> newSmsList = noticeMapper.getSmsList(notice);
            if (CollectionUtils.isEmpty(newSmsList)) {
                return AjaxResult.error("所选组织机构及角色下属人员信息为空，无法进行发送短信通知公告服务");
            }
            if (notice.getNoticeContent().equals(info.getNoticeContent()) && !CollectionUtils.isEmpty(smsList)) {
                // 移出已经发送的短信人员
                for (Notice smsInfo : smsList) {
                    newSmsList.removeIf(newSmsInfo -> smsInfo.getUserId().equals(newSmsInfo.getUserId()));
                }
            }
            if (!CollectionUtils.isEmpty(newSmsList)) {
                for (Notice notice1 : newSmsList) {
                    if (StringUtils.isBlank(notice1.getPhoneNumber())) {
                        continue;
                    }
                    String phoneNumber = notice1.getPhoneNumber();
                    if (Objects.nonNull(notice1.getPhoneNumber()) && notice1.getPhoneNumber().length() > 11) {
                        phoneNumber = Sm4Utils.decrypt(notice1.getPhoneNumber());
                    }
                    // 根据电话号码数量发送短信
                    JSONObject sendResult = SmsTool.sendSms(new SmsParam(phoneNumber, notice.getNoticeContent()), BmConfigItems.ANHUI_COMPANY_SMS_KEY);
                    //String sendResult = SmsUtils.smsToken(phoneNumber, notice.getNoticeContent(), "");
                    if (StringUtils.isBlank(sendResult.toString())) {
                        return AjaxResult.error("短信发送失败");
                    } else {
                        System.out.println("短信发送成功:" + sendResult);
                    }
                }
            }
        }
        int result = noticeMapper.updateNotice(notice);
        if (result == 0) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
        }
        return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg());
    }

    /**
     * 删除通知公告
     * @param noticeIds
     * @return
     */
    @Override
    public AjaxResult deleteNoticeByIds(Long[] noticeIds) {
        if (noticeIds == null || noticeIds.length == 0) {
            return AjaxResult.error(HttpCodeEnum.TO_PARAM_NULL.getCode(), HttpCodeEnum.TO_PARAM_NULL.getMsg());
        }
        int result = noticeMapper.deleteNoticeByIds(noticeIds);
        if (result == 0) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
        }
        return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg());
    }
}
