using Lucee.WebBase.Data;
using Lucee.WebBase.Utils;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Text;

public partial class Temp_SplitQuestion : System.Web.UI.Page
{
    public long tenant = 0;
    public string QuestionTempValue = "";
    public string PaperType = "";
    public string TempPicture64_nvarchar = "";
    public string ystihaoList = "";
    public string TempID = "";
    public string TempMainID = "";
    public string questionNum = "";
    public string xuhao, xiaoti, fenshu, yuejuanfen;
    public long exam_subject_id = 0;
    public long subjective = 0;
    public string token = "";

    private void UpdateData()
    {
        long TemDataID = Convert.ToInt64(Globals.Request("TemDataID"));
        string tempMainID = Globals.Request("TempMainID");
        string zhuguantiList = Server.UrlDecode(Globals.Request("zhuguantiList"));
        string questionNum = Globals.Request("questionNum");
        tenant = Convert.ToInt64(Globals.Request("tenant"));
        string sql = "SELECT TempValue_nvarchar FROM MK_TempleteData WHERE ID_bigint=" + TemDataID;
        string TempValue = new MysqlDBHelper(tenant).ExecuteScalar(sql).ToString();
        if (TempValue != "")
        {
            string[] list = TempValue.Split('$');//拿模板
            string zhuguanti = list[3];//拿主观题
            bool isP = false;
            if (zhuguanti != "")
            {
                string[] quList = zhuguanti.Split('^');//切题

                for (int i = 0; i < quList.Length; i++)
                {

                    if (questionNum == quList[i].Split(',')[4])//匹配哪道题
                    {
                        quList[i] = zhuguantiList;
                        isP = true;
                        break;
                    }
                }

                //获取原始图片
                sql = "SELECT CutWidth_int,CutHeight_int,PyPPostion_nvarchar FROM MK_TempleteData WHERE ID_bigint=" + TemDataID;
                DataTable dttmp = new MysqlDBHelper(tenant).ExecuteQuery(sql);
                int oldWidth = Convert.ToInt32(dttmp.Rows[0]["CutWidth_int"]);
                int oldHeight = Convert.ToInt32(dttmp.Rows[0]["CutHeight_int"]);
                string PYPostionList = dttmp.Rows[0]["PyPPostion_nvarchar"].ToString();
                string tempEx = TempV(zhuguantiList, PYPostionList, oldWidth, oldHeight);
                if (tempEx != "ok")
                {
                    Response.Write(tempEx);
                    return;
                }

                if (!isP)
                {
                    Response.Write("该题数据不存在，请刷新后重试！");
                }
                else
                {//重新组装题

                    long exam_subject_id = Convert.ToInt64(Globals.Request("exam_subject_id"));
                    long subjective = Convert.ToInt64(Globals.Request("subjective"));

                    var checkResult = CheckStatusByApi(subjective);
                    if (!checkResult.data.Value)
                    {
                        Response.Write("验证失败！" + checkResult.message);
                        return;
                    }


                    string[] newQuestionList = zhuguantiList.Split('^');
                    List<CutList> lt = new List<CutList>();
                    //写入拆分题目
                    foreach (string x in newQuestionList)
                    {
                        string[] questionList = x.Split(',');

                        string mkscoretype = "";
                        if (string.IsNullOrEmpty(questionList[7]))
                        {
                            mkscoretype = "1";
                        }
                        else
                        {
                            mkscoretype = questionList[7];
                        }

                        CutList cl = new CutList();
                        cl.questionNum = Server.UrlEncode(questionList[4]);
                        cl.subQuestionCount = Convert.ToInt32(questionList[5]);
                        cl.scoreInterval = mkscoretype;
                        cl.score = questionList[6];
                        lt.Add(cl);
                    }

                    string zhuguanlistString = "";
                    foreach (string x in quList)
                    {
                        zhuguanlistString += x + "^";
                    }
                    list[3] = zhuguanlistString.Trim('^');
                    string allData = "";
                    foreach (string x in list)
                    {
                        allData += x + "$";
                    }
                    allData = allData.Trim('$');



                    //更新原始模板
                    sql = "UPDATE MK_TempleteData SET TempValue_nvarchar=@TempValue_nvarchar WHERE  ID_bigint=" + TemDataID;
                    MySqlParameter[] sp = new MySqlParameter[] {
                             new MySqlParameter("@TempValue_nvarchar",allData)
                           };
                    new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);
                    //删除原始记录表
                    sql = "DELETE FROM MK_TempQuestionData WHERE QuestionIndex_int='" + questionNum + "' AND TempID_bigint='" + TemDataID + "'";
                    new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);



                    string ids = "";//获取返回值,拆分后ID值

                    string questionNumList = "";
                    //写入拆分题目
                    foreach (string x in newQuestionList)
                    {
                        string[] questionList = x.Split(',');

                        string mkscoretype = "";
                        if (string.IsNullOrEmpty(questionList[7]))
                        {
                            mkscoretype = "1";
                        }
                        else
                        {
                            mkscoretype = questionList[7];
                        }

                        questionNumList += questionList[4] + "$";
                        sql = string.Format(@"INSERT INTO MK_TempQuestionData(
                                    TempID_bigint,
                                    QuestionIndex_int,
                                    SmallQuestionDetail_nvarchar,
                                    Score_float,
                                    smallQuestionNum_int,
                                    questiontype_int,
                                    mkscoretype_float) VALUES
                                    ({0},{1},{2},{3},{4},1,{5});select @@IDENTITY",
                                TemDataID,
                                "'" + questionList[4] + "'",
                                "''",
                                questionList[6] == "" ? "0" : questionList[6],
                                questionList[5],
                                mkscoretype
                                );
                        ids += new MysqlDBHelper(tenant).ExecuteScalar(sql).ToString() + ",";
                    }
                    questionNumList = questionNumList.Trim('$');

                    int is_cutout = 0;
                    if (Convert.ToInt32(new MysqlDBHelper(tenant).ExecuteScalar("SELECT COUNT(1) FROM `MK_ExamResult` where ExamSubjectId=" + exam_subject_id + " AND QuestionNumber_int='" + questionNum + "'")) <= 0)
                    {
                        is_cutout = 1;
                    }

                    //写入任务表
                    sql = "Insert Into mk_subjective_cut_record(temp_main_id,temp_detail_id,temp_question_num,is_cutout,exam_subject_id,temp_question_Newdata_ids,subjective_questions_data,cutted_question_num) VALUES(" + tempMainID + "," + TemDataID + ",'" + questionNum + "'," + is_cutout + "," + exam_subject_id + ",'" + ids.Trim(',') + "','" + zhuguantiList + "','" + questionNumList + "')";
                    new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);


                    //调用接口
                    //result r = (result)JsonConvert.DeserializeObject(RequestPost(subjective.ToString(), lt.ToJsonString()), typeof(result));
                    var r = JsonConvert.DeserializeObject<result>(RequestPost(subjective.ToString(), JsonConvert.SerializeObject(lt)));
                    if (r == null || r.code != "200")
                    {
                        throw new Exception("调用接口失败了！");
                    }
                    if (r.code == "200" && r.data.Value)
                    {
                        Response.Write("1");
                    }
                    else
                    {
                        Response.Write(r.message);
                    }
                }
            }
            else
            {
                Response.Write("找不到该题");
            }
        }
        else
        {
            Response.Write("无模板数据");
        }

    }

    /// <summary>
    /// 检查边距是否合格
    /// </summary>
    /// <param name="getdata"></param>
    private string TempV(string GetData, string PYPostionList, int oldWidth, int oldHeight)
    {
        double pyLeft = Convert.ToInt32(PYPostionList.Split(',')[0]);
        double pyTop = Convert.ToInt32(PYPostionList.Split(',')[1]);
        double Xtop = 0;
        double Xleft = 0;
        double Xwidth = 0;
        double Xheight = 0;
        if (GetData != "")//主观题
        {
            string[] keguantiList = GetData.Split('^');
            foreach (string slist in keguantiList)
            {
                string[] list = slist.Split(',');
                Xleft = Convert.ToDouble(list[0]);
                Xtop = Convert.ToDouble(list[1]);
                Xwidth = Convert.ToDouble(list[2]);
                Xheight = Convert.ToDouble(list[3]);
                string tihao = list[4];
                if (Xleft < pyLeft)
                {
                    return "题号：[" + tihao + "] 编辑框左边超过定位点边界!";
                }
                if (Xleft + Xwidth - pyLeft > oldWidth)
                {
                    return "题号：[" + tihao + "] 编辑框右边超过定位点边界!";
                }
                if (Xtop < pyTop)
                {
                    return "题号：[" + tihao + "] 编辑框上边超过定位点边界!";
                }

                if (Xtop + Xheight - pyTop > oldHeight)
                {
                    return "题号：[" + tihao + "] 编辑框下边超过定位点边界!";
                }
            }
        }
        return "ok";
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int action = Globals.Request("action") == "" ? 0 : Convert.ToInt32(Globals.Request("action"));
            tenant = Globals.Request("tenant") == "" ? 0 : Convert.ToInt64(Globals.Request("tenant"));
            subjective = Convert.ToInt64(Globals.Request("subjective"));
            token = Globals.Request("token");
            if (action == 0)
            {
                string sql = "SELECT exam_subject_id,question_num,score,score_interval FROM  marking_setting_subjective WHERE id=" + subjective;
                DataTable dtSubSetting = new MysqlDBHelper(tenant).ExecuteQuery(sql);
                if (dtSubSetting.Rows.Count == 0)
                {
                    Response.Write("<script>alert('无模板数据');window.close();</script>");
                    return;
                }
                exam_subject_id = Convert.ToInt64(dtSubSetting.Rows[0]["exam_subject_id"]);
                questionNum = dtSubSetting.Rows[0]["question_num"].ToString();

                sql = "SELECT template_id FROM  exam_subject WHERE id=" + exam_subject_id;
                long template_id_main = Convert.ToInt64(new MysqlDBHelper(tenant).ExecuteScalar(sql));

                sql = "SELECT PaperType FROM MK_TempleteMain WHERE ID_bigint=" + template_id_main;
                PaperType = new MysqlDBHelper(tenant).ExecuteScalar(sql).ToString();
                TempMainID = template_id_main.ToString();

                sql = "SELECT ID_bigint,TempValue_nvarchar,TempPicture64_nvarchar FROM MK_TempleteData WHERE MainID_bigint=" + template_id_main;
                DataTable dt = new MysqlDBHelper(tenant).ExecuteQuery(sql);
                bool isHave = false;
                TempID = "";

                foreach (DataRow dr in dt.Rows)
                {
                    string data = dr["TempValue_nvarchar"].ToString();
                    if (data != "")
                    {
                        string[] list = data.Split('$');
                        string zhuguanti = list[3];
                        if (zhuguanti != "")
                        {
                            string[] quList = zhuguanti.Split('^');
                            foreach (string q in quList)
                            {
                                if (questionNum == q.Split(',')[4])
                                {
                                    TempID = dr["ID_bigint"].ToString();
                                    TempPicture64_nvarchar = dr["TempPicture64_nvarchar"].ToString();
                                    QuestionTempValue = q;
                                    xuhao = questionNum;
                                    xiaoti = q.Split(',')[5];
                                    fenshu = dtSubSetting.Rows[0]["score"].ToString();
                                    yuejuanfen = dtSubSetting.Rows[0]["score_interval"].ToString();
                                    isHave = true;
                                    break;
                                }
                            }
                        }
                    }
                }

                foreach (DataRow dr in dt.Rows)
                {
                    string data = dr["TempValue_nvarchar"].ToString();
                    if (data != "")
                    {
                        string[] list = data.Split('$');
                        string zhuguanti = list[3];
                        if (zhuguanti != "")
                        {
                            string[] quList = zhuguanti.Split('^');
                            foreach (string q in quList)
                            {
                                ystihaoList += q.Split(',')[4] + ",";
                            }
                        }
                    }
                }
                ystihaoList = ystihaoList.Trim(',');


                if (TempID == "")
                {
                    Response.Write("<script>alert('无模板数据')</script>");
                }
                else
                {
                    // Response.Write(TempID);
                }
                // Response.Write(TempID+"*"+ QuestionTempValue);
            }
            if (action == 1)
            {
                Response.Clear();
                try
                {
                    UpdateData();
                }
                catch (Exception ex)
                {
                    Response.Write("拆题失败" + ex);
                }

                Response.End();
            }
        }
    }

    private bool CheckStatus(long exam_subject_id)
    {
        if (exam_subject_id <= 0)
        {
            Response.Write("考试id有误，保存失败！");
            return false;
        }

        string sql = "SELECT `status` FROM exam_subject WHERE id=" + exam_subject_id;
        var examStatus = Convert.ToInt32(new MysqlDBHelper(tenant).ExecuteScalar(sql));
        if (examStatus != 1 && examStatus != 2)
        {
            Response.Write("当前考试状态无法执行该操作！");
            return false;
        }
        sql = "SELECT COUNT(1) FROM ScanResult WHERE IsMarking=0 AND IsDeleted=0 AND ExamSubjectId=" + exam_subject_id;
        var unScanCount = Convert.ToInt32(new MysqlDBHelper(tenant).ExecuteScalar(sql));
        if (unScanCount > 0)
        {
            Response.Write("系统正在识别试卷，请全部识别完成后再保存！");
            return false;
        }

        sql = "SELECT COUNT(1) FROM MK_ExamResult WHERE ExamSubjectId=" + exam_subject_id + " AND IsSync=0 AND IsObjectiveQuestions_bit=0 " +
            " and GroupNO_nvarchar not in (SELECT GroupNo FROM ScanResult WHERE ExamSubjectId=" + exam_subject_id + " and IsDeleted=1)";
        var unSyncCount = Convert.ToInt32(new MysqlDBHelper(tenant).ExecuteScalar(sql));
        if (unSyncCount > 0 && examStatus == 2)
        {
            Response.Write("系统正在识别分配试题，请等待1分钟后重试！");
            return false;
        }


        return true;
    }

    string bearer = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3MTllNTBhZS1hZGY0LTRjZTAtYmYyMy1lMTI5ZTcxMzZlNTYiLCJpYXQiOiIxMi8xMi8yMDIzIDEzOjQ2OjMxIiwicm9sZSI6IjUiLCJ0ZW5hbnQiOiIxIiwidXNlciI6IjI1IiwiaWQiOiIyNSIsInBvc2l0aW9uIjoiNDg4NDg0NjI1NzkzMDkzIiwic2NvcGUiOiJMZWFybkFkbWluIiwibmFtZSI6Iua2qumZteWNgeS4g-S4reWtpueuoeeQhuWRmCIsIm5iZiI6MTcwMjM1OTk5MSwiZXhwIjoxNzAyNzkxOTkxLCJpc3MiOiJtay1hZCIsImF1ZCI6IkRUQ1RBZG1pbkNsaWVudCJ9.aGsfeD2vpTv6q_KmeRID12GY6GnztZoavQtxWlJOoDo";
    private result CheckStatusByApi(long subjectiveSettingId)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
        string url = "http://192.168.2.9:6500/";

        if (Request.Url.Host.ToLower().Contains("w.23544.com"))
        {
            // 测试地址
            url = "https://mka.w.23544.com:8843/";
            bearer = token;
        }
        else if (Request.Url.Host.ToLower().Contains("23544.com"))
        {
            // 正式地址
            url = "https://mk-api.23544.com/ad/";
            bearer = token;
        }
        else if (Request.Url.Host.ToLower().Contains("localhost"))
        {
            // 开发地址
            url = "http://192.168.2.8:6500/";
        }
        url += "api/marking-setting/sub/" + subjectiveSettingId + "/cut-check";

        //Response.Write("<script>alert('"+ bearer + ",,,,+"+ url + "')</script>");

        var httpItem = new HttpItem();
        httpItem.Header.Add("Authorization", bearer);
        httpItem.Method = "GET";
        //httpItem.Postdata = body;
        //httpItem.PostEncoding = Encoding.UTF8;
        httpItem.ContentType = "application/json";
        httpItem.URL = url;
        var reponse = HttpHelper.Default.GetHtml(httpItem);
        if (reponse.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("验证接口调用失败！" + Response.StatusCode + " |||   " + reponse.Html);
        }

        //return (result)JsonConvert.DeserializeObject(reponse.Html, typeof(result));
        var ress = JsonConvert.DeserializeObject<result>(reponse.Html);
        if (ress == null || ress.code != "200")
        {
            throw new Exception("验证接口调用失败！" + Response.StatusCode + " |||   " + reponse.Html);
        }
        return ress;
    }
    private string RequestPost(string id, string body)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
        // 测试地址
        string url = "http://192.168.2.9:6500/";
        if (Request.Url.Host.ToLower().Contains("w.23544.com"))
        {
            // 测试地址
            url = "https://mka.w.23544.com:8843/";
            bearer = token;
        }
        else if (Request.Url.Host.ToLower().Contains("23544.com"))
        {
            // 正式地址
            url = "https://mk-api.23544.com/ad/";
            bearer = token;
        }
        else if (Request.Url.Host.ToLower().Contains("localhost"))
        {
            // 开发地址
            url = "http://192.168.2.8:6500/";
        }
        url += "api/marking-setting/sub/" + id + "/cut";
        var httpItem = new HttpItem();
        httpItem.Header.Add("Authorization", bearer);
        httpItem.Method = "POST";
        httpItem.Postdata = body;
        httpItem.PostEncoding = Encoding.UTF8;
        httpItem.ContentType = "application/json";
        httpItem.URL = url;
        var reponse = HttpHelper.Default.GetHtml(httpItem);
        if (reponse.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("调用保存失败！");
        }

        return reponse.Html;
        //WebRequest request = WebRequest.Create(url);
        //request.Method = "POST";
        ////post传参数  
        //byte[] bytes = Encoding.ASCII.GetBytes(body);
        //request.Headers.Add("Authorization", bearer);
        //request.ContentType = "application/json";
        //request.ContentLength = body.Length;
        //Stream sendStream = request.GetRequestStream();
        //sendStream.Write(bytes, 0, bytes.Length);
        //sendStream.Close();
        ////得到返回值  
        //WebResponse response = request.GetResponse();
        //string OrderQuantity = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")).ReadToEnd();
        //return OrderQuantity;
    }


    public class CutList
    {
        public string questionNum { get; set; }
        public int subQuestionCount { get; set; }
        public string score { get; set; }
        public string scoreInterval { get; set; }
    }

    public class result
    {
        public string message { get; set; }
        public string code { get; set; }

        public bool? data { get; set; }

    }


}