package com.liquidnet.client.admin.zhengzai.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.common.enums.UpushTargetType;
import com.liquidnet.client.admin.common.utils.ShiroUtils;
import com.liquidnet.client.admin.zhengzai.kylin.utils.upush.AndroidNotification;
import com.liquidnet.client.admin.zhengzai.kylin.utils.upush.PushClient;
import com.liquidnet.client.admin.zhengzai.kylin.utils.upush.android.AndroidBroadcast;
import com.liquidnet.client.admin.zhengzai.kylin.utils.upush.ios.IOSBroadcast;
import com.liquidnet.commons.lang.constant.LnsEnum;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.kylin.dao.UpushDetailsListDao;
import com.liquidnet.service.kylin.dto.param.admin.UpushParam;
import com.liquidnet.service.kylin.dto.param.admin.UpushSearchParam;
import com.liquidnet.service.kylin.entity.AdminUpush;
import com.liquidnet.service.kylin.mapper.AdminUpushMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.service.kylin.service.admin.IAdminUpushService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 友盟消息推送 服务实现类
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-07-13
 */
@Service
public class AdminUpushServiceImpl extends ServiceImpl<AdminUpushMapper, AdminUpush> implements IAdminUpushService {

    @Value("${liquidnet.al-oss.imgUrl}")
    private String imgUrl;

    @Value("${liquidnet.umeng.ios.appkey}")
    private String iosAppkey;
    @Value("${liquidnet.umeng.ios.appMasterSecret}")
    private String iosAppMasterSecret;
    @Value("${liquidnet.umeng.android.appkey}")
    private String androidAppkey;
    @Value("${liquidnet.umeng.android.appMasterSecret}")
    private String androidAppMasterSecret;

    private PushClient client = new PushClient();

    @Autowired
    Environment environment;

    @Autowired
    private AdminUpushMapper adminUpushMapper;

    public Boolean create(UpushParam upushParam) {
        try {
            // 入数据库
            String upushId = IDGenerator.nextSnowId();
            upushParam.setUpushId(upushId);
            String authId = ShiroUtils.getUserId().toString();
            String authName = ShiroUtils.getLoginName();
            AdminUpush adminUpush = new AdminUpush();
            BeanUtils.copyProperties(upushParam, adminUpush);
            adminUpush.setCreatedAt(DateUtil.getNowTime());
            adminUpush.setPushedBy(authId);
            adminUpush.setPushedName(authName);
            if (adminUpush.getPushTime().isEmpty()) {
                adminUpush.setPushTime(null);
            }
            adminUpushMapper.insert(adminUpush);

            if (adminUpush.getIsPush() == 1) {
                if (adminUpush.getPushRange() == 1) {
                    sendAndroidBroadcast(adminUpush);
                    sendIOSBroadcast(adminUpush);
                } else if (adminUpush.getPushRange() == 2) {
                    sendIOSBroadcast(adminUpush);
                } else if (adminUpush.getPushRange() == 3) {
                    sendAndroidBroadcast(adminUpush);
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public PageInfo<UpushDetailsListDao> lists(UpushSearchParam upushSearchParam) {
        try {
            PageHelper.startPage(upushSearchParam.getPageNum(), upushSearchParam.getPageSize());
            List<UpushDetailsListDao> voList = adminUpushMapper.searchList(BeanUtil.convertBeanToMap(upushSearchParam));
            for (UpushDetailsListDao item : voList) {
                String typeName = UpushTargetType.getTypeName(item.getJumpType());
                item.setJumpName(typeName);
            }

            return new PageInfo(voList);
        } catch (Exception e) {
            return new PageInfo(new ArrayList());
        }
    }

    public UpushDetailsListDao detail(String upushId) {
        AdminUpush data = adminUpushMapper.selectOne(Wrappers.lambdaQuery(AdminUpush.class).eq(AdminUpush::getUpushId, upushId));
        UpushDetailsListDao upushDetailsListDao = new UpushDetailsListDao();
        if (null != data) {
            String typeName = UpushTargetType.getTypeName(data.getJumpType());
            BeanUtils.copyProperties(data, upushDetailsListDao);
            upushDetailsListDao.setImg(imgUrl + upushDetailsListDao.getImg());
            upushDetailsListDao.setJumpName(typeName);
        } else {
            return null;
        }

        return upushDetailsListDao;
    }

    public void sendAndroidBroadcast(AdminUpush adminUpush) {
        try {
            AndroidBroadcast broadcast = new AndroidBroadcast(androidAppkey, androidAppMasterSecret);
            broadcast.setTicker(adminUpush.getPushTitle());
            broadcast.setTitle(adminUpush.getPushTitle());
            broadcast.setText(adminUpush.getPushContent());
            broadcast.goAppAfterOpen();
            broadcast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
            if (Arrays.asList(LnsEnum.ENV.dev.name(), LnsEnum.ENV.test.name()).contains(environment.getProperty(CurrentUtil.CK_ENV_ACTIVE))) {
                broadcast.setTestMode();
            } else {
                broadcast.setProductionMode();
            }
            // Set customized fields
            broadcast.setExtraField("type", adminUpush.getJumpType().toString());
            broadcast.setExtraField("id", adminUpush.getJumpValue());
            broadcast.setExtraField("url", adminUpush.getJumpValue());

            if (adminUpush.getSendType() == 1) {
                String pushTime = adminUpush.getPushTime();
                broadcast.setPredefinedKeyValue("start_time", pushTime);
            }
            client.send(broadcast);
        } catch (Exception e) {

        }
    }

    public void sendIOSBroadcast(AdminUpush adminUpush) {
        try {
            IOSBroadcast broadcast = new IOSBroadcast(iosAppkey, iosAppMasterSecret);
            //alert的值设置为字典
            broadcast.setAlert(adminUpush.getPushTitle(), adminUpush.getPushTitle(), adminUpush.getPushContent());
            broadcast.setBadge(0);
            broadcast.setSound("default");
            if (Arrays.asList(LnsEnum.ENV.dev.name(), LnsEnum.ENV.test.name()).contains(environment.getProperty(CurrentUtil.CK_ENV_ACTIVE))) {
                broadcast.setTestMode();
            } else {
                broadcast.setProductionMode();
            }
            // Set customized fields
            broadcast.setCustomizedField("type", adminUpush.getJumpType().toString());
            broadcast.setCustomizedField("id", adminUpush.getJumpValue());
            broadcast.setCustomizedField("url", adminUpush.getJumpValue());

            if (adminUpush.getSendType() == 1) {
                String pushTime = adminUpush.getPushTime();
                broadcast.setPredefinedKeyValue("start_time", pushTime);
            }
            client.send(broadcast);
        } catch (Exception e) {

        }

    }
}
