package com.sckw.system.service;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.ClientTypeEnum;
import com.sckw.core.utils.*;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.model.EntCertificateInfo;
import com.sckw.core.web.model.LoginEntInfo;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.SckwMessage;
import com.sckw.stream.model.UserInfo;
import com.sckw.system.dao.KwsEnterpriseDao;
import com.sckw.system.dao.KwsMenuDao;
import com.sckw.system.dao.KwsMenuRightsDao;
import com.sckw.system.model.KwsEnterprise;
import com.sckw.system.model.KwsMenu;
import com.sckw.system.model.KwsMenuRights;
import com.sckw.system.model.vo.res.FindEntListResVo;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;

/**
 * @author czh
 * @desc 公共方法
 * @date 2023/6/30
 */
@Service
@Slf4j
public class CommonService {

    @Autowired
    private KwsEnterpriseDao kwsEnterpriseDao;

    @Autowired
    private KwsMenuRightsDao kwsMenuRightsDao;

    @Autowired
    private KwsMenuDao kwsMenuDao;

    @Resource
    private StreamBridge streamBridge;


    /**
     * @desc: 更新资质
     * @param: entId 企业id entCertificateInfoList 资质信息
     * @author: czh
     * @date 2023/7/23
     */
    public void updateEntCertificate(Long entId, List<EntCertificateInfo> entCertificateInfoList) {
        String string = RedissonUtils.getString(Global.REDIS_ENTERPRISE_PREFIX + entId);
        if (!StringUtils.isBlank(string)) {
            LoginEntInfo loginEntInfo = JSON.parseObject(string, LoginEntInfo.class);
            loginEntInfo.setCertificateInfo(entCertificateInfoList);
            RedissonUtils.putString(Global.REDIS_ENTERPRISE_PREFIX + entId, JSON.toJSONString(loginEntInfo), Global.COMMON_EXPIRE);
        }
    }

    /**
     * @desc: 校验企业是否重复
     * @param: entName 企业名  phone 联系电话
     * @author: czh
     * @date 2023/7/23
     */
    public void checkEntRepeat(String entName, String phone) {
        List<KwsEnterprise> list = kwsEnterpriseDao.checkEntRepeat(entName, phone);
        if (CollectionUtils.isNotEmpty(list)) {
            for (KwsEnterprise kwsEnterprise : list) {
                String firmName = kwsEnterprise.getFirmName();
                String phone1 = kwsEnterprise.getPhone();
                if (entName.equals(firmName)) {
                    throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.ENT_EXISTS);
                }

                if (StringUtils.isNotBlank(phone) && phone.equals(phone1)) {
                    throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.ACCOUNT_EXISTS);
                }
            }
        }
    }


    /**
     * @param phone 手机号
     * @desc: 校验手机号
     * @author: czh
     * @date: 2023/7/26
     */
    public void checkPhone(String phone) {
        if (!RegularUtils.matchs(RegularUtils.PHONE_REG, phone)) {
            throw new SystemException(HttpStatus.PARAMETERS_PATTERN_ERROR_CODE, HttpStatus.CONTACTS_PHONE_ERROR);
        }
    }


//    public void test() {
//        List<FindEntListResVo> list = kwsEnterpriseDao.findList(null);
//        KwsMenu kwsMenu = new KwsMenu();
//        kwsMenu.setClientType(2);
//        kwsMenu.setDelFlag(Global.NO);
//        List<KwsMenu> select = kwsMenuDao.select(kwsMenu);
//        for (FindEntListResVo findEntListResVo : list) {
//            Long id = findEntListResVo.getId();
//
//            List<KwsMenuRights> currrent =  kwsMenuRightsDao.selectEntMenus(id);
//            if (CollectionUtils.isNotEmpty(currrent)) {
//                continue;
//            }
//            Long userId = findEntListResVo.getUserId();
//            if (Objects.isNull(userId)) {
//                userId = 0L;
//            }
//            List<KwsMenuRights> kwsMenuRightsList = new ArrayList<>();
//            Date date = new Date();
//            for (KwsMenu kwsMenu1 : select) {
//                KwsMenuRights kwsMenuRights = new KwsMenuRights();
//                kwsMenuRights.setEntId(id);
//                kwsMenuRights.setMenuId(kwsMenu1.getId());
//                kwsMenuRights.setId(new IdWorker(1L).nextId());
//                kwsMenuRights.setStatus(0);
//                kwsMenuRights.setCreateBy(userId);
//                kwsMenuRights.setCreateTime(date);
//                kwsMenuRights.setUpdateBy(userId);
//                kwsMenuRights.setUpdateTime(date);
//                kwsMenuRights.setDelFlag(0);
//                kwsMenuRightsList.add(kwsMenuRights);
//            }
//            kwsMenuRightsDao.saveBatch(kwsMenuRightsList);
//        }
//    }


    public void sendSystemMessage(List<UserInfo> userInfos, MessageEnum messageEnum, Map<String, Object> map, String msgUrl, String appMsgUrl) {
        SckwMessage msg = new SckwMessage();
        Map<String, String> msgUrls = new HashMap<>(Global.NUMERICAL_FOUR);
        msgUrls.put(ClientTypeEnum.pc.getValue(), msgUrl);
        if (StringUtils.isNotBlank(appMsgUrl)) {
            msgUrls.put(ClientTypeEnum.app.getValue(), appMsgUrl);
        }
        msg.setRequestId(UUIDUtils.get32UUID())
                .setMessageEnum(messageEnum)
                .setParams(map)
                .setMsgUrls(msgUrls)
                .setUserInfos(userInfos)
                .setCreateBy(LoginUserHolder.getUserId());
        log.info("send-message:{}", JSON.toJSONString(msg));
        AsyncThreadUtils.submit(new AsyncProcess(msg, streamBridge));
    }


    static class AsyncProcess implements Runnable {

        private SckwMessage sckwMessage;

        private StreamBridge streamBridge;

        AsyncProcess(SckwMessage sckwMessage, StreamBridge streamBridge) {
            this.sckwMessage = sckwMessage;
            this.streamBridge = streamBridge;
        }

        @Override
        public void run() {
            streamBridge.send("sckw-message", JSON.toJSONString(sckwMessage));
        }
    }

}
