using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Pub_Class;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Http;
using WebAPI.Models;
using System.IO;
using System.Web;
using WebAPI.Controllers.SCGL.日计划管理;
namespace WebAPI.Controllers
{
    //期初余额报表Controller
    public class YS_ContactBalController : ApiController
    {
        //获取系统参数
        Pub_Class.ClsXt_SystemParameter oSystemParameter = new Pub_Class.ClsXt_SystemParameter();
        public DBUtility.ClsPub.Enum_BillStatus BillStatus;
        private json objJsonResult = new json();
        SQLHelper.ClsCN oCN = new SQLHelper.ClsCN();
        DataSet ds;
        #region 期初余额报表 查询
        /// 
        ///参数:string sql。
        ///返回值:object。
        ///  
        [Route("YS_ContactBal/list")]
        [HttpGet]
        public object getYS_ContactBal(string sWhere, string user)
        {
            try
            {
                List columnNameList = new List();
                ////查看权限
                if (!DBUtility.ClsPub.Security_Log("YS_ContactBalReport_Query", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无查看权限!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                if (sWhere == null || sWhere.Equals(""))
                {
                    ds = oCN.RunProcReturn("select * from h_v_YSYF_ContactBal_Query order by 客户代码", "h_v_YSYF_ContactBal_Query");
                }
                else
                {
                    string sql1 = "select * from h_v_YSYF_ContactBal_Query where 1 = 1 ";
                    string sql = sql1 + sWhere + " order by 客户代码 ";
                    ds = oCN.RunProcReturn(sql, "h_v_YSYF_ContactBal_Query");
                }
                //添加列名
                foreach (DataColumn col in ds.Tables[0].Columns)
                {
                    Type dataType = col.DataType;
                    string ColmString = "{\"ColmCols\":\"" + col.ColumnName + "\",\"ColmType\":\"" + dataType.Name + "\"}";
                    columnNameList.Add(JsonConvert.DeserializeObject(ColmString));//获取到DataColumn列对象的列名
                }
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                objJsonResult.list = columnNameList;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region 期初余额报表 文件上传
        [Route("YS_ContactBal/YS_ContactBalReport_ImportByExcel")]
        [HttpPost]
        public object YS_ContactBalReport_ImportByExcel()
        {
            try
            {
                //var WorkBookName = HttpContext.Current.Request["WorkBookName"];
                //DBUtility.ClsPub.HOrgID = long.Parse(HttpContext.Current.Request["HOrgID"]);
                //获取文件名称
                var file = HttpContext.Current.Request.Files[0];
                //获取文件物理路径
                string ExcelPath = HttpContext.Current.Server.MapPath("~/" + file.FileName);
                //保存文件
                file.SaveAs(ExcelPath);
                NpoiHelper np = new NpoiHelper();
                DataSet ExcelDs = np.ReadExcel(ExcelPath, 1, 1, "0");
                //删除文件
                File.Delete(ExcelPath);
                //创建临时表
                DataTable tb2 = new DataTable("dt2");
                //添加列名
                for (int i = 0; i < ExcelDs.Tables[0].Columns.Count; i++)
                {
                    tb2.Columns.Add(ExcelDs.Tables[0].Rows[0][i].ToString());
                }
                //模板缺少列 但需要从数据库中查询出来显示在页面的字段
                tb2.Columns.Add("客户内码", typeof(string));//客户内码
                tb2.Columns.Add("货币内码", typeof(string));//货币内码
                tb2.Columns.Add("货币名称", typeof(string));//货币名称
                tb2.Columns.Add("判定结果", typeof(string));//判定结果
                //添加数据
                for (int i = 1; i < ExcelDs.Tables[0].Rows.Count; i++)
                {
                    DataRow row = tb2.NewRow();
                    for (int j = 0; j < ExcelDs.Tables[0].Columns.Count; j++)
                    {
                        row[j] = ExcelDs.Tables[0].Rows[i][j].ToString();
                    }
                    tb2.Rows.Add(row);
                }
                //查询Excel文件中没有的列
                var error = "";
                if (!tb2.Columns.Contains("类型"))
                {
                    error += "没有找到【类型】的标题,";
                }
                if (!tb2.Columns.Contains("客户代码"))
                {
                    error += "没有找到【客户代码】的标题,";
                }
                if (!tb2.Columns.Contains("客户名称"))
                {
                    error += "没有找到【客户名称】的标题,";
                }
                if (!tb2.Columns.Contains("期初余额"))
                {
                    error += "没有找到【期初余额】的标题,";
                }
                if (!tb2.Columns.Contains("组织代码"))
                {
                    error += "没有找到【组织代码】的标题,";
                }
                if (!tb2.Columns.Contains("组织名称"))
                {
                    error += "没有找到【组织名称】的标题,";
                }
                if (error.Length > 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"Excel模板存在错误,{error}\r\n";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //查询数据赋给数据表
                for (int i = 0; i <= tb2.Rows.Count - 1; i++)
                {
                    string HCusNumber = DBUtility.ClsPub.isStrNull(tb2.Rows[i]["客户代码"].ToString());
                    string HCusName = DBUtility.ClsPub.isStrNull(tb2.Rows[i]["客户名称"].ToString());
                    string HBeginBalance = DBUtility.ClsPub.isStrNull(tb2.Rows[i]["期初余额"].ToString());
                    int index = i + 1;
                    tb2.Rows[i]["判定结果"] = "";
                }
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = error;
                objJsonResult.data = tb2;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region 期初余额报表 导入(数据验证)
        [Route("YS_ContactBal/YS_ContactBalReport_ImportByExcel_Confirm")]
        [HttpPost]
        public object YS_ContactBalReport_ImportByExcel_Confirm([FromBody] JObject sMainSub)
        {
            var _value = sMainSub["sMainSub"].ToString();
            string msg1 = _value.ToString();
            string[] sArray = msg1.Split(new string[] { "&和" }, StringSplitOptions.RemoveEmptyEntries);
            string msg2 = sArray[0].ToString();
            string user = sArray[1].ToString();
            string[] importFieldList = sArray[2].ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            try
            {
                List Excel = Newtonsoft.Json.JsonConvert.DeserializeObject>(msg2);
                List> list = new List>();
                foreach (JObject item in Excel)
                {
                    Dictionary dic = new Dictionary();
                    foreach (var itm in item.Properties())
                    {
                        dic.Add(itm.Name, itm.Value.ToString());
                    }
                    list.Add(dic);
                }
                //创建临时表并设置列名
                DataTable tb2 = new DataTable("dt2");
                tb2.Columns.Add("类型", typeof(string));
                tb2.Columns.Add("客户内码", typeof(string));
                tb2.Columns.Add("客户代码", typeof(string));
                tb2.Columns.Add("客户名称", typeof(string));
                tb2.Columns.Add("货币内码", typeof(string));
                tb2.Columns.Add("货币名称", typeof(string));
                tb2.Columns.Add("期初余额", typeof(string));
                tb2.Columns.Add("组织代码", typeof(string));
                tb2.Columns.Add("组织名称", typeof(string));
                tb2.Columns.Add("判定结果", typeof(string));
                string error = "";
                int i = 1;
                string sql = "";
                foreach (Dictionary item in list)
                {
                    //记录判定结果
                    string err = "";
                    DataRow row = tb2.NewRow();
                    tb2.Rows.Add(row);
                    
                    string HFRP = item["类型"].ToString();
                    string HCusID = item["客户内码"].ToString();
                    string HCusNumber = item["客户代码"].ToString();
                    string HCusName = item["客户名称"].ToString();
                    string HCurID = item["货币内码"].ToString();
                    string HCurName = item["货币名称"].ToString();
                    string HBeginBalance = item["期初余额"].ToString();
                    string HOrgNumber = item["组织代码"].ToString();
                    string HOrgName = item["组织名称"].ToString();
                    tb2.Rows[i - 1]["类型"] = HFRP;
                    tb2.Rows[i - 1]["客户内码"] = HCusID;
                    tb2.Rows[i - 1]["客户代码"] = HCusNumber;
                    tb2.Rows[i - 1]["客户名称"] = HCusName;
                    tb2.Rows[i - 1]["货币内码"] = HCurID;
                    tb2.Rows[i - 1]["货币名称"] = HCurName;
                    tb2.Rows[i - 1]["期初余额"] = HBeginBalance;
                    tb2.Rows[i - 1]["组织代码"] = HOrgNumber;
                    tb2.Rows[i - 1]["组织名称"] = HOrgName;
                    tb2.Rows[i - 1]["判定结果"] = "";
                    //校验类型是否符合规定的类型
                    if(HFRP != "0" && HFRP != "1") 
                    {
                        err += "类型不正确,请输入(0:应收款 或 1:应付款);";
                    }
                    //根据导入字段获取客户相关数据,并进行校验
                    sql = "";
                    if (importFieldList[0] == "HOrgNumber")
                    {
                        sql = "select * from Xt_ORGANIZATIONS where HNumber = '" + HOrgNumber + "'";
                    }
                    else if (importFieldList[0] == "HOrgName")
                    {
                        sql = "select * from Xt_ORGANIZATIONS where HName = '" + HOrgName + "'";
                    }
                    ds = oCN.RunProcReturn(sql, "Xt_ORGANIZATIONS");
                    if (ds.Tables[0].Rows.Count == 0)
                    {
                        err += "组织不存在;";
                        HCusID = "0";
                        tb2.Rows[i - 1]["客户内码"] = "0";
                        tb2.Rows[i - 1]["货币内码"] = "0";
                    }
                    else
                    {
                        tb2.Rows[i - 1]["组织代码"] = ds.Tables[0].Rows[0]["HNumber"];
                        tb2.Rows[i - 1]["组织名称"] = ds.Tables[0].Rows[0]["HName"];
                        sql = "select c.HItemID,c.HNumber,c.HName,ISNULL(c.HCurID,0) HCurID,ISNULL(cur.HName,'') HCurName from " +
                        "Gy_Customer as c " +
                        "left join Xt_ORGANIZATIONS o on c.HUSEORGID = o.HItemID " +
                        "left join Gy_Currency cur on c.HCurID = cur.HItemID " + 
                        "where c.HNumber = '" + HCusNumber + "' " +
                        "and o.HNumber = '" + ds.Tables[0].Rows[0]["HNumber"] + "' " +
                        "and o.HName = '" + ds.Tables[0].Rows[0]["HName"] + "'";
                        ds = oCN.RunProcReturn(sql, "Gy_Customer");
                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            err += "该组织下客户不存在;";
                            HCusID = "0";
                            tb2.Rows[i - 1]["客户内码"] = "0";
                            tb2.Rows[i - 1]["货币内码"] = "0";
                        }
                        else
                        {
                            tb2.Rows[i - 1]["客户内码"] = ds.Tables[0].Rows[0]["HItemID"];
                            tb2.Rows[i - 1]["客户代码"] = ds.Tables[0].Rows[0]["HNumber"];
                            tb2.Rows[i - 1]["客户名称"] = ds.Tables[0].Rows[0]["HName"];
                            tb2.Rows[i - 1]["货币内码"] = ds.Tables[0].Rows[0]["HCurID"];
                            tb2.Rows[i - 1]["货币名称"] = ds.Tables[0].Rows[0]["HCurName"];
                            HCusID = ds.Tables[0].Rows[0]["HItemID"].ToString();
                        }
                    }
                    //判定该客户是否已经存在期初余额
                    sql = "select * from YSYF_ContactBal where HCusID = " + HCusID;
                    ds = oCN.RunProcReturn(sql, "YSYF_ContactBal");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        err += "该客户已经存在期初余额;";
                    }
                    tb2.Rows[i - 1]["判定结果"] = err;
                    error += err;
                    i++;
                }
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = (error.Length > 0 ? "0" : "1");
                objJsonResult.data = tb2;
                return objJsonResult;
            }
            catch (Exception e)
            {
                LogService.Write(e);
                oCN.RollBack();
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region 期初余额报表 导入(保存)
        [Route("YS_ContactBal/YS_ContactBalReport_ImportByExcel_Save")]
        [HttpPost]
        public object YS_ContactBalReport_ImportByExcel_Save([FromBody] JObject sMainSub)
        {
            var _value = sMainSub["sMainSub"].ToString();
            string msg1 = _value.ToString();
            string[] sArray = msg1.Split(new string[] { "&和" }, StringSplitOptions.RemoveEmptyEntries);
            string msg2 = sArray[0].ToString();
            string user = sArray[1].ToString();
            string saveType = sArray[2].ToString();
            try
            {
                if (!DBUtility.ClsPub.Security_Log("YS_ContactBalReport_ExcelImport", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无导入权限!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                List Excel = Newtonsoft.Json.JsonConvert.DeserializeObject>(msg2);
                List> list = new List>();
                foreach (JObject item in Excel)
                {
                    Dictionary dic = new Dictionary();
                    foreach (var itm in item.Properties())
                    {
                        dic.Add(itm.Name, itm.Value.ToString());
                    }
                    list.Add(dic);
                }
                if (saveType == "1")
                {
                    oCN.BeginTran();
                    string err = "";
                    int i = 1;
                    string sql = "";
                    foreach (Dictionary item in list)
                    {
                        string HFRP = item["类型"].ToString();
                        string HCusID = item["客户内码"].ToString();
                        string HCusNumber = item["客户代码"].ToString();
                        string HCusName = item["客户名称"].ToString();
                        string HCurID = item["货币内码"].ToString();
                        string HCurName = item["货币名称"].ToString();
                        string HBeginBalance = item["期初余额"].ToString();
                        string HOrgNumber = item["组织代码"].ToString();
                        string HOrgName = item["组织名称"].ToString();
                        //校验类型是否符合规定的类型
                        if (HFRP != "0" && HFRP != "1")
                        {
                            err += "第" + i + "行:类型不正确,请输入(0:应收款 或 1:应付款);";
                        }
                        sql = "select * from YSYF_ContactBal where HCusID = " + HCusID;
                        ds = oCN.RunProcReturn(sql, "YSYF_ContactBal");
                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            sql = "insert into YSYF_ContactBal(HYear,HPeriod,HRP,HCusID,HCurID,HBeginBalance) " +
                                "values(" +
                                "YEAR(getdate())" +
                                ",Month(getdate())" +
                                "," + HFRP + "" +
                                "," + HCusID + "" +
                                "," + HCurID + "" +
                                "," + HBeginBalance + "" +
                                ")";
                            oCN.RunProc(sql);
                        }
                        else
                        {
                            sql = "update YSYF_ContactBal set " +
                                "HBeginBalance = " + HBeginBalance + " " +
                                "where HCusID = " + HCusID;
                            oCN.RunProc(sql);
                        }
                        i++;
                    }
                }
                else if (saveType == "2")
                {
                    oCN.BeginTran();
                    string err = "";
                    int i = 1;
                    string sql = "";
                    foreach (Dictionary item in list)
                    {
                        string HFRP = item["类型"].ToString();
                        string HCusID = item["客户内码"].ToString();
                        string HCusNumber = item["客户代码"].ToString();
                        string HCusName = item["客户名称"].ToString();
                        string HCurID = item["货币内码"].ToString();
                        string HCurName = item["货币名称"].ToString();
                        string HBeginBalance = item["期初余额"].ToString();
                        string HOrgNumber = item["组织代码"].ToString();
                        string HOrgName = item["组织名称"].ToString();
                        //校验类型是否符合规定的类型
                        if (HFRP != "0" && HFRP != "1")
                        {
                            err += "第" + i + "行:类型不正确,请输入(0:应收款 或 1:应付款);";
                        }
                        sql = "select * from YSYF_ContactBal where HCusID = " + HCusID;
                        ds = oCN.RunProcReturn(sql, "YSYF_ContactBal");
                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            sql = "insert into YSYF_ContactBal(HYear,HPeriod,HRP,HCusID,HCurID,HBeginBalance) " +
                                "values(" +
                                "YEAR(getdate())" +
                                ",Month(getdate())" +
                                "," + HFRP + "" +
                                "," + HCusID + "" +
                                "," + HCurID + "" +
                                "," + HBeginBalance + "" +
                                ")";
                            oCN.RunProc(sql);
                        }
                        else
                        {
                            err += "第" + i + "行:该客户已经存在期初余额;!";
                        }
                        i++;
                    }
                    //判断是否存在错误
                    if (err.Length > 0)
                    {
                        oCN.RollBack();
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "导入错误:" + err;
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
                }
                oCN.Commit();
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "导入成功!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                LogService.Write(e);
                oCN.RollBack();
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
    }
}