package com.sunyard.ssp.modules.sysconf.paramconf.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunyard.chsm.config.IpFilter;
import com.sunyard.chsm.mapper.ParamConfMapper;
import com.sunyard.chsm.model.entity.ParamConf;
import com.sunyard.chsm.service.IpWhitelistService;
import com.sunyard.ssp.modules.sysconf.paramconf.service.IParamConfService;
import com.sunyard.ssp.modules.user.entity.ScPermission;
import com.sunyard.ssp.modules.user.service.IScPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.sunyard.chsm.constant.ParamConfKeyConstant.APPROVAL_TRUE;
import static com.sunyard.chsm.constant.ParamConfKeyConstant.AUTHORITY_APPROVAL_PARAM_ITEM;
import static com.sunyard.chsm.constant.ParamConfKeyConstant.ENCRYPTION_MACHINE_APPROVAL;
import static com.sunyard.chsm.constant.ParamConfKeyConstant.IP_WHITELIST_ITEM;
import static com.sunyard.chsm.constant.ParamConfKeyConstant.IP_WHITELIST_SWITCH;
import static com.sunyard.ssp.common.constant.CommonConstant.STATUS_DISABLE;
import static com.sunyard.ssp.common.constant.CommonConstant.STATUS_NORMAL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fyc
 * @since 2020-03-17
 */
@Slf4j
@Service
@Transactional
public class ParamConfServiceImpl extends ServiceImpl<ParamConfMapper, ParamConf> implements IParamConfService {

    @Autowired
    private IScPermissionService permissionService;

    @Autowired
    private ParamConfMapper paramConfMapper;
    @Autowired
    private IpWhitelistService ipWhitelistService;

//    @Autowired
//    private IIpWhitelistService iIpWhitelistService;


    @Override
    public boolean save(Map map) {
        Integer item = (Integer) map.get("item");
        map.remove("item");
        Set<String> keySet = map.keySet();
        boolean result = false;
        for (String key : keySet) {
            ParamConf paramConf = paramConfMapper.selectByKey(key);
            if (paramConf == null) {
                paramConf = new ParamConf();
                paramConf.setItem(item);
                paramConf.setStatus(0);
                paramConf.setCreatTime(LocalDateTime.now());
                paramConf.setKey(key);
                paramConf.setValue(String.valueOf(map.get(key)));
                paramConf.setType("OBJECT");
                result = save(paramConf);
            } else {
                paramConf.setValue(String.valueOf(map.get(key)));
                result = updateById(paramConf);
            }
            if (!result) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                break;
            }
            //存储成功生效配置
            takeEffectConfiguration(paramConf);
        }
        return result;
    }

    @Override
    public Map selectByItem(Integer item) {
        Map result = new HashMap();
        List<ParamConf> paramConfs = paramConfMapper.selectByItem(item);
        for (ParamConf paramConf : paramConfs) {
            result.put(paramConf.getKey(), paramConf.getValue());
        }
        return result;
    }

    @Override
    public ParamConf selectByKey(String key) {
        return paramConfMapper.selectByKey(key);
    }

    @Override
    public Boolean findByItemAndKeyAndValue(Integer item, String key, String value) {

        List<ParamConf> paramConfs = paramConfMapper.selectList(new QueryWrapper<ParamConf>().lambda()
                .eq(ParamConf::getItem, item)
                .eq(ParamConf::getKey, key)
                .eq(ParamConf::getValue, value)
        );
        if (paramConfs.isEmpty()) {
            return false;
        }
        return true;
    }

    /**
     * 参数修改后进行配置生效
     * @param paramConf
     * @return
     */
    @Async
    public void takeEffectConfiguration(ParamConf paramConf) {
        //审批权限
        if (AUTHORITY_APPROVAL_PARAM_ITEM.equals(paramConf.getItem())
                && ENCRYPTION_MACHINE_APPROVAL.equals(paramConf.getKey())) {
            QueryWrapper<ScPermission> wrapper = new QueryWrapper<ScPermission>();
            String[] names = {"myApply", "approvalDev", "device"};
            wrapper.lambda().in(ScPermission::getName, names);
            List<ScPermission> permissions = permissionService.list(wrapper);
            permissions.forEach(p -> {
                if (APPROVAL_TRUE.equals(paramConf.getValue())) {
                    p.setPStatus(STATUS_NORMAL);
                } else {
                    p.setPStatus(STATUS_DISABLE);
                }
            });
            permissionService.updateBatchById(permissions);
        }
        //白名单通知
        else if (IP_WHITELIST_ITEM.equals(paramConf.getItem())
                && IP_WHITELIST_SWITCH.equals(paramConf.getKey())) {

            IpFilter.enableWhiteIp = Objects.equals("true", paramConf.getValue());
            if(IpFilter.enableWhiteIp) {
                ipWhitelistService.enableWhiteIpEvent();
            }
//            iIpWhitelistService.messengerWhitelistUpdate();
        }
    }

    /**
     * 启动加载初始化系统参数
     *
     * @param args
     * @throws Exception
     */
//    @Override
    public void run(ApplicationArguments args) throws Exception {
//        System.out.println("初始化系统参数-----------------");
//        List<ParamConf> paramConfs = getParamConfByJsonFile();
//        paramConfs.forEach(paramConf -> {
//            ParamConf temp = selectByKey(paramConf.getKey());
//            if (temp == null) {
//                paramConf.setCreatTime(LocalDateTime.now());
//                save(paramConf);
//            } else {
//                temp.setValue(paramConf.getValue());
//                updateById(temp);
//            }
//        });
    }

    /**
     * 从JSON 文件里获取初始化配置
     *
     * @return
     */
//    private List<ParamConf> getParamConfByJsonFile() {
//        String jsonStr = "";
//        List<ParamConf> paramConfs = new ArrayList<>();
//        try {
//            File jsonFile = new File(ParamConfKeyConstant.SYS_PARAM_CONFIG_FILE_PATH);
//            jsonStr = JsonUtil.getJsonStrFromJsonFile(jsonFile);
//            paramConfs = JsonUtils.objectMapper().readValue(jsonStr, new TypeReference<List<ParamConf>>() {
//            });
////            paramConfs = JSON.parseArray(jsonStr, ParamConf.class);
//            return paramConfs;
//        } catch (Exception ex) {
//            return paramConfs;
//        }
//    }
}
