package org.example.Utils;


import org.example.Impl.BaseImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 功能说明：消息推送类
 **/
public class PushHelper extends BaseImpl {
    private static final Logger log = LoggerFactory.getLogger(PushHelper.class);

    private String billid;
    private String stepcode;
    private String menuid;
    private String beforeusers;
    private String beforemenuname;
    private int beforeid;
    private Map<String, PushMessage> pushMessages = new HashMap<>();


    public PushHelper(String billid, String stepcode, String menuid, String beforeusers, String beforemenuname, int beforeid) {
        this.billid = billid;
        this.menuid = menuid;
        this.stepcode = stepcode;
        this.beforeusers = beforeusers;
        this.beforemenuname = beforemenuname;
        this.beforeid = beforeid;
    }

    /**
     * 推送单据审核确认消息
     */
    public void push_bill_comfirm_message() {

    }

    /**
     * 推送单据审核消息
     *
     * @remarks 创建人：龚宇超
     * 创建日期：2017-07-10
     * 修改人：
     * 修改日期：
     * 修改备注：无
     * 版本：1.0
     */
    public void push_bill_oper_message() {
        try {
            pushMessages.clear();

            // 极光推送key
            List<Map<String, Object>> systemTabList = jdbcTemplate.queryForList("select * from dbo.p_systemtab");
            if (systemTabList.isEmpty()) {
                return;
            }
            Map<String, Object> systemTab = systemTabList.get(0);
            String appKey = (String) systemTab.get("JPushAppKey");
            String masterSecret = (String) systemTab.get("JPushMaster_Secret");
            String clientCode = (String) systemTab.get("ClientCode");

            if (appKey == null || appKey.isEmpty()) {
                return;
            }

            String sql = String.format("select operators, typeName as menuname, '2' + CAST(b.id as varchar(10)) as id " +
                            "from dbo.wms_billflowOper a, dbo.p_systembilltype b " +
                            "where a.modid = b.typeCode and keyvalue = '%s' and stepcode = '%s' and a.stepover = 0",
                    billid, stepcode);
            List<Map<String, Object>> dtTable = jdbcTemplate.queryForList(sql);

            // 清空上一步人员消息
            if (beforeusers != null && !beforeusers.isEmpty() && beforemenuname != null && !beforemenuname.isEmpty() && beforeid > 0) {
                String userSql = String.format("select employeeid as userid, employeename as username " +
                                "from dbo.P_employeeTab where employeename in (%s)",
                        "'" + beforeusers.replace(",", "','") + "'");
                List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                for (Map<String, Object> user : userList) {
                    String uid = (String) user.get("userid");
                    String username = (String) user.get("username");

                    addPushSource(appKey, masterSecret, clientCode, beforeid, 0, beforemenuname, menuid, uid);
                }
            } else {
                // 单据提交处理
                String userSql = String.format("select operators, typeName as menuname, '2' + CAST(b.id as varchar(10)) as id " +
                                "from dbo.wms_billflowOper a, dbo.p_systembilltype b " +
                                "where a.modid = b.typeCode and keyvalue = '%s' and a.stepover = 0",
                        billid);
                List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                if (!userList.isEmpty()) {
                    Map<String, Object> firstRow = userList.get(0);
                    beforeusers = (String) firstRow.get("operators");
                    beforemenuname = (String) firstRow.get("menuname");
                    beforeid = Integer.parseInt((String) firstRow.get("id"));
                }
            }

            // 推送本次人员消息
            if (dtTable != null && !dtTable.isEmpty()) {
                Map<String, Object> firstRow = dtTable.get(0);
                String operators = (String) firstRow.get("operators");
                String menuname = (String) firstRow.get("menuname");
                int id = Integer.parseInt((String) firstRow.get("id"));

                String userSql = String.format("select employeeid as userid, employeename as username " +
                                "from dbo.P_employeeTab where employeename in (%s)",
                        "'" + operators.replace(",", "','") + "'");
                List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                for (Map<String, Object> user : userList) {
                    String uid = (String) user.get("userid");
                    String username = (String) user.get("username");

                    String countSql = String.format("select COUNT(1) as total from dbo.wms_BillflowOper " +
                                    "where stepOver = 0 and modid = '%s' and CHARINDEX(',%s,', ',' + operators + ',') > 0",
                            menuid, username);
                    List<Map<String, Object>> countList = jdbcTemplate.queryForList(countSql);
                    int total = countList.isEmpty() ? 0 : Integer.parseInt(countList.get(0).get("total").toString());

                    addPushSource(appKey, masterSecret, clientCode, beforeid, total, beforemenuname, menuid, uid);
                }
            } else {
                // 重新计算人员消息
                if (beforeusers != null && !beforeusers.isEmpty() && beforemenuname != null && !beforemenuname.isEmpty() && beforeid > 0) {
                    String userSql = String.format("select employeeid as userid, employeename as username " +
                                    "from dbo.P_employeeTab where employeename in (%s)",
                            "'" + beforeusers.replace(",", "','") + "'");
                    List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                    for (Map<String, Object> user : userList) {
                        String uid = (String) user.get("userid");
                        String username = (String) user.get("username");

                        String countSql = String.format("select COUNT(1) as total from dbo.wms_BillflowOper " +
                                        "where stepOver = 0 and modid = '%s' and CHARINDEX(',%s,', ',' + operators + ',') > 0",
                                menuid, username);
                        List<Map<String, Object>> countList = jdbcTemplate.queryForList(countSql);
                        int total = countList.isEmpty() ? 0 : Integer.parseInt(countList.get(0).get("total").toString());

                        addPushSource(appKey, masterSecret, clientCode, beforeid, total, beforemenuname, menuid, uid);
                    }
                }
            }
        } catch (Exception e) {
            log.error("推送单据审核消息异常", e);
        }

        ResourceExecutors.submitPush(this::push_all_message);
    }

    /**
     * 推送基础档案审核确认消息
     *
     * @remarks 创建人：龚宇超
     * 创建日期：2017-07-10
     * 修改人：
     * 修改日期：
     * 修改备注：无
     * 版本：1.0
     */
    public void push_base_comfirm_message() {

    }

    /**
     * 推送基础档案审核消息
     *
     * @remarks 创建人：龚宇超
     * 创建日期：2017-07-10
     * 修改人：
     * 修改日期：
     * 修改备注：无
     * 版本：1.0
     */
    public void push_base_oper_message() {
        try {
            pushMessages.clear();

            // 极光推送key
            List<Map<String, Object>> systemTabList = jdbcTemplate.queryForList("select * from dbo.p_systemtab");
            if (systemTabList.isEmpty()) {
                return;
            }
            Map<String, Object> systemTab = systemTabList.get(0);
            String appKey = (String) systemTab.get("JPushAppKey");
            String masterSecret = (String) systemTab.get("JPushMaster_Secret");
            String clientCode = (String) systemTab.get("ClientCode");

            if (appKey == null || appKey.isEmpty()) {
                return;
            }

            String sql = String.format("select operators, ToolsName as menuname, '1' + CAST(b.dllid as varchar(10)) as id " +
                            "from dbo.P_baseflowOper a, dbo.P_systemdlltab b " +
                            "where a.modid = b.DllCoid and keyvalue = '%s' and stepcode = '%s' and a.stepover = 0",
                    billid, stepcode);
            List<Map<String, Object>> dtTable = jdbcTemplate.queryForList(sql);

            // 清空上一步人员消息
            if (beforeusers != null && !beforeusers.isEmpty() && beforemenuname != null && !beforemenuname.isEmpty() && beforeid > 0) {
                String userSql = String.format("select employeeid as userid, employeename as username " +
                                "from dbo.P_employeeTab where employeename in (%s)",
                        "'" + beforeusers.replace(",", "','") + "'");
                List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                for (Map<String, Object> user : userList) {
                    String uid = (String) user.get("userid");
                    addPushSource(appKey, masterSecret, clientCode, beforeid, 0, beforemenuname, menuid, uid);
                }
            } else {
                // 单据提交处理
                String userSql = String.format("select operators, ToolsName as menuname, '1' + CAST(b.dllid as varchar(10)) as id " +
                                "from dbo.P_baseflowOper a, dbo.P_systemdlltab b " +
                                "where a.modid = b.DllCoid and keyvalue = '%s' and a.stepover = 0",
                        billid);
                List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                if (!userList.isEmpty()) {
                    Map<String, Object> firstRow = userList.get(0);
                    beforeusers = (String) firstRow.get("operators");
                    beforemenuname = (String) firstRow.get("menuname");
                    beforeid = Integer.parseInt((String) firstRow.get("id"));
                }
            }

            // 推送本次人员消息
            if (dtTable != null && !dtTable.isEmpty()) {
                Map<String, Object> firstRow = dtTable.get(0);
                String operators = (String) firstRow.get("operators");
                String menuname = (String) firstRow.get("menuname");
                int id = Integer.parseInt((String) firstRow.get("id"));

                String userSql = String.format("select employeeid as userid, employeename as username " +
                                "from dbo.P_employeeTab where employeename in (%s)",
                        "'" + operators.replace(",", "','") + "'");
                List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                for (Map<String, Object> user : userList) {
                    String uid = (String) user.get("userid");
                    String username = (String) user.get("username");

                    String countSql = String.format("select COUNT(1) as total from dbo.P_baseflowOper " +
                                    "where stepOver = 0 and modid = '%s' and CHARINDEX(',%s,', ',' + operators + ',') > 0",
                            menuid, username);
                    List<Map<String, Object>> countList = jdbcTemplate.queryForList(countSql);
                    int total = countList.isEmpty() ? 0 : Integer.parseInt(countList.get(0).get("total").toString());

                    addPushSource(appKey, masterSecret, clientCode, beforeid, total, beforemenuname, menuid, uid);
                }
            } else {
                // 终审重新计算人员
                if (beforeusers != null && !beforeusers.isEmpty() && beforemenuname != null && !beforemenuname.isEmpty() && beforeid > 0) {
                    String userSql = String.format("select employeeid as userid, employeename as username " +
                                    "from dbo.P_employeeTab where employeename in (%s)",
                            "'" + beforeusers.replace(",", "','") + "'");
                    List<Map<String, Object>> userList = jdbcTemplate.queryForList(userSql);

                    for (Map<String, Object> user : userList) {
                        String uid = (String) user.get("userid");
                        String username = (String) user.get("username");

                        String countSql = String.format("select COUNT(1) as total from dbo.P_baseflowOper " +
                                        "where stepOver = 0 and modid = '%s' and CHARINDEX(',%s,', ',' + operators + ',') > 0",
                                menuid, username);
                        List<Map<String, Object>> countList = jdbcTemplate.queryForList(countSql);
                        int total = countList.isEmpty() ? 0 : Integer.parseInt(countList.get(0).get("total").toString());

                        addPushSource(appKey, masterSecret, clientCode, beforeid, total, beforemenuname, menuid, uid);
                    }
                }
            }
        } catch (Exception ex) {
            log.error("推送基础档案审核消息异常", ex);
        }

        ResourceExecutors.submitPush(this::push_all_message);
    }

    /**
     * 去除重复消息通知
     *
     * @param appkey    应用key
     * @param appsecret 应用密钥
     * @param appclict  客户端标识
     * @param id        消息ID
     * @param total     总数
     * @param menuname  菜单名称
     * @param menuid    菜单ID
     * @param uid       用户ID
     */
    private void addPushSource(String appkey, String appsecret, String appclict, int id, int total, String menuname, String menuid, String uid) {
        if (pushMessages.containsKey(uid)) {
            PushMessage push = pushMessages.get(uid);
            if (push.total == 0) {
                push.total = total;
            }
        } else {
            PushMessage message = new PushMessage();
            message.appkey = appkey;
            message.appsecret = appsecret;
            message.appclict = appclict;
            message.id = beforeid;
            message.total = total;
            message.menuname = beforemenuname;
            message.menuid = menuid;
            message.uid = uid;
            pushMessages.put(uid, message);
        }
    }

    /**
     * 推送消息
     *
     * @remarks 创建人：龚宇超
     * 创建日期：2017-07-10
     * 修改人：
     * 修改日期：
     * 修改备注：无
     * 版本：1.0
     */
    private void push_all_message() {
//        for (PushMessage item : pushMessages.values()) {
//            // 推送android、ios消息
//            JPushClient jPushClient = new JPushClient(item.appkey, item.appsecret);
//
//            Map<String, Object> extras = new HashMap<>();
//            extras.put("id", item.id);   // 1.基础档案审批通知，2.单据审核通知
//            extras.put("title", item.menuname);
//            extras.put("total", item.total);
//            extras.put("desc", String.format("您有%d条数据需要审批.", item.total));
//            extras.put("menuid", menuid);
//
//            // 发送android消息
//            try {
//                PushPayload androidPayload = JPushApi.pushObjectAndroidMessage("1002", item.appclict + "_" + item.uid, extras);
//                MessageResult androidResult = jPushClient.sendPush(androidPayload);
//            } catch (Exception ex) {
//                log.error("发送安卓消息错误", ex);
//            }
//
//            // 发送ios消息
//            try {
//                PushPayload iosPayload = JPushApi.pushObjectIosAliasTitleWithContent(
//                        item.menuname,
//                        String.format("您有%d条数据需要审批.", item.total),
//                        item.appclict + "_" + item.uid,
//                        extras
//                );
//                MessageResult iosResult = jPushClient.sendPush(iosPayload);
//            } catch (Exception ex) {
//                log.error("发送IOS消息错误", ex);
//            }
//        }
    }

    /**
     * 推送实体
     */
    public static class PushMessage {
        public String appkey;
        public String appsecret;
        public String appclict;
        public int id;
        public int total;
        public String menuname;
        public String menuid;
        public String uid;
    }
}
