using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Business;
using PTMedicalInsurance.Common;
using PTMedicalInsurance.Entity.BaseLine.ElectronicSettlementCertificate;
using PTMedicalInsurance.Forms.Setters.ElectronicSettlementCertificates;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;

namespace PTMedicalInsurance.Forms.ElectronicSettlementCertificates
{
    public partial class EcSettlCertUpload : Form
    {
        private ElectronicSettlementCertificate ecSettlCert = new ElectronicSettlementCertificate();
        private DataTable  dtEcSettlCertList;
        private EcSettlCertMainForm mainForm;
        private string err;



        public EcSettlCertUpload()
        {
            InitializeComponent();
        }

        public EcSettlCertUpload(Form frm)
        {
            InitializeComponent(); 
            InitForm(frm);
        }

        private void InitForm(Form frm)
        {
            mainForm = (EcSettlCertMainForm)frm;
            CheckForIllegalCrossThreadCalls = false;
            // 禁用关闭按钮
            this.FormBorderStyle = FormBorderStyle.None;

            // 隐藏标题栏
            this.ControlBox = false;

            // 其他可能需要的配置
            this.TopLevel = false;
            this.Dock = DockStyle.Fill; // 根据需要设置 Dock 属性

            //
            SetHeaderOfDgv();

            //
            dpST.Value = DateTime.Now;
            dpED.Value = DateTime.Now;
        }

        private void SetHeaderOfDgv()
        {
            GridViewSetter gvs = new GridViewSetter();
            gvs.setDgvEcSettlCertList(dgvEcSettlCertList);
        }

        #region 函数封装

        /// <summary>
        /// 更新成功后，刷新界面
        /// </summary>
        private void freshForm()
        { 
        
        }

        /// <summary>
        /// 单条上传
        /// </summary>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private int SingleUpload(out String errMsg)
        {
            int i = dgvEcSettlCertList.CurrentRow.Index;

            UploadEcSettlCertIn inpar = new UploadEcSettlCertIn();
            JObject joIn = new JObject();
            joIn.Add("InvNo", dtEcSettlCertList.Rows[i]["InvNo"].ToString());
            joIn.Add("PrintPaymentInvDr", dtEcSettlCertList.Rows[i]["PrintPaymentInvDr"].ToString());
            joIn.Add("HospDr", dtEcSettlCertList.Rows[i]["HospDr"].ToString());

            //获取HIS 原始入参
            JObject joOrignalInput = ecSettlCert.Get4901Input(joIn);
            if (JsonHelper.parseIrisRtnValue(joOrignalInput, out err) != 0)
            {
                errMsg = ("获取4901入参失败：" + err);
                return -1;
            }

            //通过原始入参，转换为接口需要的入参，PDF,XML,编码转换等等
            ecSettlCert.SavePath = Global.curEvt.path;
            JObject joNeedConvertData = JObject.Parse(JsonHelper.getDestValue(joOrignalInput,"data"));
            //joNeedConvertData.Add("fixmedinsCode", Global.inf.hospitalNO);
            //joNeedConvertData.Add("fixmedinsName", Global.inf.hospitalName);
            joNeedConvertData["fixmedinsCode"] = Global.inf.hospitalNO;
            joNeedConvertData["fixmedinsName"] = Global.inf.hospitalName;
            //joNeedConvertData["upldBchno"] = DateTime.Now.ToString("yyyyMMdd" + "00001");//上传日期年月日加5位顺序号
            joNeedConvertData["filename"] = "";//压缩包文件名称
            JArray jaUpldDetlList = JArray.Parse(JsonHelper.getDestValue(joNeedConvertData, "upldDetlList"));
            foreach (JObject jo in jaUpldDetlList)
            {
                jo["mdtrtareaAdmdvs"] = Global.inf.areaCode;
            }
            JArray jaXML = JArray.Parse(JsonHelper.getDestValue(joNeedConvertData, "xml"));
            foreach (JObject jo in jaXML)
            {
                jo["tktextinfo"]["mdtrtInfo"]["fixmedinsCode"] = Global.inf.hospitalNO;
                jo["tktextinfo"]["mdtrtInfo"]["fixmedinsName"] = Global.inf.hospitalName;
            }

            joNeedConvertData["upldDetlList"] = jaUpldDetlList;
            joNeedConvertData["xml"] = jaXML;
            JObject joConvertedInput = ecSettlCert.Convert4901Input(joNeedConvertData);

            JObject joRtn = ecSettlCert.Upload(joConvertedInput);

            if (JsonHelper.parseCenterRtnValue(joRtn, out err) != 0)
            {
                errMsg =("上传失败：" + err);
                return -1;
            }
            else
            {
                JObject joUpdateIn = new JObject();
                joUpdateIn.Add("businessCode","EcSettlCertUpload");
                joUpdateIn.Add("businessID", ecSettlCert.ecSettlCertNo);//单条传，如果批量传，这么处理就有问题
                joUpdateIn.Add("memo", ecSettlCert.upldBchno);//单条传，如果批量传，这么处理就有问题
                joUpdateIn.Add("input", joConvertedInput);
                joRtn["errorCode"] = new JObject();
                joRtn["errorCode"] = 0;
                joUpdateIn.Add("output", joRtn);
                JObject joUpdateRtn = ecSettlCert.Update(joUpdateIn);
                if (JsonHelper.parseIrisRtnValue(joUpdateRtn, out err) != 0)
                {
                    errMsg = ("上传成功但更新后台失败：" + err);
                    return -1;
                }
                else
                {
                    errMsg = ("上传成功！");
                    freshForm();
                    return 0;
                }
            }
        }

        private int QueryStatus(out String errMsg)
        {
            int i = dgvEcSettlCertList.CurrentRow.Index;

            JObject joIn = new JObject();
            joIn.Add("fixmedinsCode", Global.inf.hospitalNO);
            joIn.Add("fixmedinsName", Global.inf.hospitalName);
            joIn.Add("elecSetlCertCode", "");
            joIn.Add("elecSetlCertNo", dtEcSettlCertList.Rows[i]["InvNo"].ToString());
            joIn.Add("elecSetlCertChkcode","");
            joIn.Add("elecSetlCertType", 3);

            JObject joRtn = ecSettlCert.QueryUploadStatus(joIn);

            string err;
            if (JsonHelper.parseCenterRtnValue(joRtn, out err) != 0)
            {
                errMsg = ("查询状态失败：" + err);
                return -1;
            }
            else
            {

                errMsg = ("查询状态成功！");
                freshForm();
                return 0;
            }
        }

        private int QueryUploadResult(out String errMsg)
        {
            int i = dgvEcSettlCertList.CurrentRow.Index;

            string upldBchno = dtEcSettlCertList.Rows[i]["UpldBchno"].ToString();
            if (string.IsNullOrEmpty(upldBchno))
            {
                errMsg =("该记录未上传或上传成功！");
                return -1;
            }
            string printDateStr = dtEcSettlCertList.Rows[i]["PrintDate"].ToString();

            JObject joData = new JObject();
            joData.Add("fixmedinsCode", Global.inf.hospitalNO);
            joData.Add("fixmedinsName", Global.inf.hospitalName);
            joData.Add("bizStsb",$"{printDateStr.Replace("-", "")}-{printDateStr.Replace("-", "")}");
            joData.Add("upldBchno", dtEcSettlCertList.Rows[i]["UpldBchno"].ToString());

            JObject joRtn = ecSettlCert.QueryUploadResult(joData);

            string err;
            if (JsonHelper.parseCenterRtnValue(joRtn, out err) != 0)
            {
                errMsg = ("查询上传结果失败：" + err);
                return -1;
            }
            else
            {

                errMsg = ("查询上传成功！");
                freshForm();
                return 0;
            }
        }

        private int ReUpload(out String errMsg)
        {
            int i = dgvEcSettlCertList.CurrentRow.Index;

            UploadEcSettlCertIn inpar = new UploadEcSettlCertIn();
            JObject joIn = new JObject();
            joIn.Add("InvNo", dtEcSettlCertList.Rows[i]["InvNo"].ToString());
            joIn.Add("PrintPaymentInvDr", dtEcSettlCertList.Rows[i]["PrintPaymentInvDr"].ToString());
            joIn.Add("HospDr", dtEcSettlCertList.Rows[i]["HospDr"].ToString());

            //获取HIS 原始入参
            JObject joOrignalInput = ecSettlCert.Get4901Input(joIn);
            string err;
            if (JsonHelper.parseIrisRtnValue(joOrignalInput, out err) != 0)
            {
                errMsg = ("获取4901入参失败：" + err);
                return -1;
            }

            //通过原始入参，转换为接口需要的入参，PDF,XML,编码转换等等
            ecSettlCert.SavePath = Global.curEvt.path;
            JObject joNeedConvertData = JObject.Parse(JsonHelper.getDestValue(joOrignalInput, "data"));
            //joNeedConvertData.Add("fixmedinsCode", Global.inf.hospitalNO);
            //joNeedConvertData.Add("fixmedinsName", Global.inf.hospitalName);
            joNeedConvertData["fixmedinsCode"] = Global.inf.hospitalNO;
            joNeedConvertData["fixmedinsName"] = Global.inf.hospitalName;
            joNeedConvertData["upldBchno"] = DateTime.Now.ToString("yyyyMMdd" + "00001");//上传日期年月日加5位顺序号
            joNeedConvertData["filename"] = "";//压缩包文件名称
            JArray jaXML = JArray.Parse(JsonHelper.getDestValue(joNeedConvertData, "xml"));
            foreach (JObject jo in jaXML)
            { 
                jo["fixmedinsCode"] = Global.inf.hospitalNO;
                jo["fixmedinsName"] = Global.inf.hospitalName;
            }
            JObject joConvertedInput = ecSettlCert.Convert4901Input(joNeedConvertData);
            JArray jaRetrmDetlList = JArray.Parse(JsonHelper.getDestValue(joConvertedInput, "upldDetlList"));
            foreach (JObject jo in jaRetrmDetlList)
            {
                jo.Add("initElecSetlCertCode", "");
                jo.Add("initElecSetlCertNo", jo["elecSetlCertNo"].ToString());
                jo.Add("initUpldWay", "1");//原上传方式 1使用4901医疗机构上传电子结算凭证2使用4903医疗机构上传电子结算凭证基本信息
                jo.Add("certCodeNoErrFlag", "0"); //凭证代码号码错误标志  0否（原凭证代码号码与重传凭证代码号码一致）1是（原凭证代码号码与重传凭证代码号码不一致）
                jo.Add("rea", "测试"); //理由

            }
            joConvertedInput.Remove("upldDetlList");
            joConvertedInput.Add("reUploadDetlDTOList", jaRetrmDetlList);
            JObject joRtn = ecSettlCert.ReUpload(joConvertedInput);

            if (JsonHelper.parseCenterRtnValue(joRtn, out err) != 0)
            {
                errMsg = "重传失败：" + err;
                return -1;
            }
            else
            {
                JObject joUpdateIn = new JObject();
                joUpdateIn.Add("businessCode", "EcSettlCertUpload");
                joUpdateIn.Add("businessID", ecSettlCert.ecSettlCertNo);//单条传，如果批量传，这么处理就有问题
                joUpdateIn.Add("memo", ecSettlCert.upldBchno);//单条传，如果批量传，这么处理就有问题
                joUpdateIn.Add("input", joConvertedInput);
                joRtn["errorCode"] = new JObject();
                joRtn["errorCode"] = 0;
                joUpdateIn.Add("output", joRtn);
                JObject joUpdateRtn = ecSettlCert.Update(joUpdateIn);
                if (JsonHelper.parseIrisRtnValue(joUpdateRtn, out err) != 0)
                {
                    errMsg = "重成功但更新后台失败：" + err;
                    return -1;
                }
                else
                {
                    errMsg =  "重传成功！";
                    freshForm();
                    return 0;
                }
            }
        }

        #endregion



        private void btnQuery_Click(object sender, EventArgs e)
        {
            JObject joIn = new JObject();
            joIn.Add("BeginDate", dpST.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            joIn.Add("EndDate", dpED.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            joIn.Add("HospDr", Global.inf.hospitalDr);
            joIn.Add("PatName",tbName.Text);
            joIn.Add("InvNo", tbInvNO.Text);
            joIn.Add("InterfaceID", Global.inf.interfaceDr);

            JObject joRtn = ecSettlCert.QueryEcSettlCertList(joIn);
            if (JsonHelper.parseIrisRtnValue(joRtn, out err) != 0)
            {
                MessageBox.Show(err);
                return;
            }
            dtEcSettlCertList = (DataTable)joRtn["data"].ToObject(typeof(DataTable));
            dgvEcSettlCertList.DataSource = dtEcSettlCertList;
        }

        private void tsmUploadSingle_Click(object sender, EventArgs e)
        {
            SingleUpload(out err);
            MessageBox.Show(err);
        }

        private void tsmQueryStatus_Click(object sender, EventArgs e)
        {
            QueryStatus(out err);
            MessageBox.Show(err);
        }

        private void tsReUpload_Click(object sender, EventArgs e)
        {
            ReUpload(out err);
            MessageBox.Show(err);
        }

        private void btnClose_3_Click(object sender, EventArgs e)
        {
            mainForm.Close();
        }

        private void tsmQueryUploadResult_Click(object sender, EventArgs e)
        {
            QueryUploadResult(out err);
            MessageBox.Show(err);
        }

        //// 定义进度回调委托
        //public delegate void ProgressCallback(int progress);

        private int BachUpload(out string errMsg, DataLoader.ProgressCallback callback)
        {
            int errCount = 0;
            List<string> errList = new List<string>();
            for (int i = 0; i < dgvEcSettlCertList.Rows.Count; i++)
            {
                dgvEcSettlCertList.CurrentCell = dgvEcSettlCertList.Rows[i].Cells[0];
                if (SingleUpload(out err) != 0)
                {
                    errCount++;
                    errList.Add(err);
                }

                if (callback != null)
                {
                    callback(i + 1);
                }
            }

            if (errCount != 0)
            {
                errMsg = $"批量上传有错误！上传总条数为:{dgvEcSettlCertList.Rows.Count};错误条数为:{errCount}";
            }
            else
            {
                errMsg = $"批量上传成功！上传总条数为:{dgvEcSettlCertList.Rows.Count}";
            }
            return -errCount;
        }

        private void btnBatchUpload_Click(object sender, EventArgs e)
        {
            // 创建 DataLoader 并传递 queryExportData 方法
            DataLoader _dataLoader;
            _dataLoader = new DataLoader((out string errMsg, DataLoader.ProgressCallback callback) =>BachUpload(out errMsg, callback), this);

            _dataLoader.StartQueryExportData(dgvEcSettlCertList.Rows.Count, (result, errMsg) =>
            {
                // 在这里处理结果和错误信息
                if (result == 0)
                {
                    MessageBox.Show(errMsg);
                }
                else
                {
                    MessageBox.Show(errMsg);
                }
            });
        }
    }
}
