using System.Collections.Generic;
using LitJson;
using Library;
using MySystem.Models;
using System;
using System.Security.Cryptography;
using System.Threading;
using System.Linq;
/// <summary>
/// 获取行销宝信息
/// </summary>

public class GetRadioCardInfoService
{
    public readonly static GetRadioCardInfoService Instance = new GetRadioCardInfoService();
    private GetRadioCardInfoService()
    {
    }

    // //测试
    // string pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGvhfAXw0yoPgMwBfX6jgDT6XBjWqOFcGmsm/pfnGlqGSsMYZNjMLzwOMWfhB8IO7dyh4nu3caXjZTbBUJLQtIKcOoM/ZFZZiOXBW2xDg5WPSswmtCvaSmct9rrd0OGvZtNvgimcNjnHbiE1/1LPxwKHWyzdxzRul5NJdg0Vdw1QIDAQAB";
    // string priKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJVLd0ePGZ6fKK1TwcGIxvknF7liDhGyedk3IRxEwTP6P+YS7Y9WaKxDTxIc77ECFSWlvZIPKOXXufMTzwkEGvuAKO+kD9C5R2D+4U3IhztrzcHif8Pn5+I2fVUGuXisUJ+bPxEKSjw7sn5S94uCIsy7o79rHAovAwn+2veLw8xDAgMBAAECgYAqZ8gWnE/jnUOZj9vOFAKoTHFRp8dlQXOYvi76b5ENKXyy5hdyClIq8+dmtq9icLv++IfTD9lHB7J6l9rLrc3XyNmdRSzxSxOT/kPYv1qZoNCqAlTFjWwLNw8tkarcc9NbNXg9UOS/UE97Hs1vlEThOB12cz+5wEF62l+LvZCxeQJBAMrgiujwoKddhCNGuVr3Gac98j4PBqvgtakvYUzvF78gJ0ffngb0J6s1rmGgmaohJc5YE8RwHa4AbIAUjhsdTx0CQQC8YyPgtD44i6+IQMba5zZH1nISSI5yQlPv8dgLXRLDMTnWXx9F7JxXLzAmeJdpkZrdvv1tLzClqDStRClr28rfAkEArFuD6E62TjpWzpmBU9TmiH1KVorxggiQjUHhijj+lbO9a4SBfyrioMQkeHC23CD5O4r8kEEoFfHqPA46hLKryQJAcCHOvDRtCLlUbRSpiKixLYdedLWNXENQtPTN9M2cmmSVmZ0a/0L8OATVc0C6V1MczDqfnDrHiQMa/7sfsJyuHwJBAMLGVR4buHGR/zrnO7FJa4zPw0KK+xUSttDQ9T2+JzV+RcaffmwSm511q+lAZW8e+SrT08WBKhEY8bYUEV95VAM=";
    // string orgNo = "YCJG10010003";
    // string apiKey = "12345678";
    // string host = "https://bmp-test.cbnyunchang.com";

    //生产
    string pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZ+zsPxpoM85OFlHOqN3aauub5PqC8lmfFQKgWz7XITCPsWdYrBY/Niu29tSNchYZq+wrboyhrhCx9PacWeF5hQ0qkOIw/vcLQJe4RWXj3eBMfbqj7a2dJlcFI12TP0m1lCaI5z9lZ1FHtZDzU0lBBiRUCRNsJa/ktrt1MjU7nAQIDAQAB";
    string priKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJBIQq3hyV0EseFd6X+nzRc++bZoljQqqou2NPUW5RD+wLBTk08LGwhGq7hR9WlG95aQ3NHbqNT/Tt8eiH9a8k7FzXHDzGAnGpYTh1fCzSx+lzmRA0E8WUH2CdjSLiNxb4Dxvqcrht5TpgFp2NRaGIIAvB+h8QZ1Uhjux5LGiJaJAgMBAAECgYBl65WmrSOIYOOi9qsWMRvwetz9HL5WFXmp/clFBKpFqh/FrxQVNxweaYWuS78XYjlNlAFZAVkvNTaq6C+1/zHAl3YmRowVz2ut1WoTT5MjZBJsR1d7SnSKp/ZuquKGGPG9l1jbUgY6CfekUhvKzUdk3/k7r3zUzUzEWq4dDdM/XQJBAP2SwEDg78nJxKMBmjKYwEpYYYL6DxTYje9J07/Ms7L8W7OtIj+Xm6I0siBWLe4Y5tVtBzaohxnbzoKfNODaNFMCQQCRqb+5fD02I+Sa62gTQepb1u1HgguS1KfFB0inmwMs+VEFYs73N8LC3PSzONhOLlIV/bzs4CvpnMHyF16qie4zAkEA9GBR2DTv41EIqPAKY2jDKOM0Vr4XeseZQlusLtRg+sYqumbI8vBxlUmjwXZMnYJyNI32vb59NXaY91nn5Ctm8QJAYSwkwtCm5R88ujygyXgHqAzRbgrLPcCvyzj4txcqHy6TZkxsVW/VdbmBZK5fXoh4KkODbWJ+6PGyUJZWiN5LEQJAelIs1KLSVQ+GAzDslXIyxYhTP9yLcxAMbCuQ3tY0jbsyYyB/WuxTvIdwGfGp/GLht36/6RqsRc9JtAyMeXkE1g==";
    string orgNo = "YCJG10010003";
    string apiKey = "n^ZbEjK%";
    string host = "https://bmp.cbnyunchang.com";

    public void Start()
    {
        Thread th = new Thread(StartEverTimeDo);
        th.IsBackground = true;
        th.Start();
    }

    private void StartEverTimeDo()
    {
        while (true)
        {
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string queryBeginTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); //工号开通时间，开始时间。格式：yyyy-MM-dd
                string queryEndTime = DateTime.Now.ToString("yyyy-MM-dd"); //工号开通时间，结束时间。格式：yyyy-MM-dd
                string pageNo = "1"; //当前页
                string pageSize = "99999"; //每页大小
                string timestamp = function.getTimeStamp(); //时间戳，精确到秒。签名用参数
                SortedList<string, string> req = new SortedList<string, string>();
                req.Add("queryBeginTime", queryBeginTime);
                req.Add("queryEndTime", queryEndTime);
                req.Add("brhNo", orgNo);
                req.Add("pageNo", pageNo);
                req.Add("pageSize", pageSize);
                req.Add("timestamp", timestamp);
                string signstr = function.BuildQueryString(req);
                function.WriteLog(DateTime.Now.ToString(), "广电卡查询开通工号数据");
                function.WriteLog("代签名串\n" + signstr, "广电卡查询开通工号数据");
                req.Add("sign", Sign(signstr));
                string reqstr = Newtonsoft.Json.JsonConvert.SerializeObject(req);
                function.WriteLog("请求参数\n" + reqstr, "广电卡查询开通工号数据");
                string reqUrl = host + "/ycsim-business/openapi/query_marketers_info";
                function.WriteLog("请求地址\n" + reqUrl, "广电卡查询开通工号数据");
                string result = function.PostWebRequest(reqUrl, reqstr, "application/json");
                result = result.Replace("null", "\"\"");
                function.WriteLog("响应数据\n" + result, "广电卡查询开通工号数据");

                JsonData jsonObj = JsonMapper.ToObject(result);
                if (jsonObj["resultCode"].ToString() == "1")
                {
                    var data = jsonObj["data"]["records"];
                    for (int i = 0; i < data.Count; i++)
                    {
                        var IdNo = data[i]["idNo"].ToString();
                        var radioCardInfo = db.RadioCardInfo.FirstOrDefault(m => m.IdNo == IdNo) ?? new RadioCardInfo();
                        if (string.IsNullOrEmpty(radioCardInfo.JobId))
                        {
                            radioCardInfo.JobId = data[i]["jobId"].ToString(); //行销宝工号
                            radioCardInfo.JobStatus = data[i]["status"].ToString(); //工号状态
                            radioCardInfo.OprName = data[i]["oprName"].ToString(); //人员姓名
                            radioCardInfo.Mobile = data[i]["mobile"].ToString(); //广电手机号
                            radioCardInfo.IdNo = data[i]["idNo"].ToString(); //身份证号
                            radioCardInfo.Gender = data[i]["gender"].ToString(); //性别
                            radioCardInfo.Role = data[i]["role"].ToString(); //角色
                            radioCardInfo.ChannelCode = data[i]["channelCode"].ToString(); //归属社招渠道编码
                            radioCardInfo.ChannelName = data[i]["channelName"].ToString(); //归属社招渠道名称
                            radioCardInfo.ProvincialCompany = data[i]["provincialCompany"].ToString(); //归属省公司
                            radioCardInfo.OprInviteCode = data[i]["oprInviteCode"].ToString(); //邀请码
                            radioCardInfo.OpenTime = data[i]["openTime"].ToString(); //开通时间
                            radioCardInfo.BrhName = data[i]["brhName"].ToString(); //机构名称
                            // radioCardInfo.BrhUserId = data[i]["brhUserId"].ToString(); //机构用户编码
                            radioCardInfo.UpdateDate = DateTime.Now; //更新时间
                        }
                    }
                    db.SaveChanges();
                }
                else
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + result, "请求行销宝信息接口异常");
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "获取行销宝信息线程异常");
            }
            db.Dispose();
            Thread.Sleep(1800000);
        }
    }

    private string Sign(string message)
    {
        byte[] keyData = Convert.FromBase64String(priKey);
        byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
        var rsa = System.Security.Cryptography.RSA.Create();
        rsa.ImportPkcs8PrivateKey(keyData, out _);
        return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
    }

}