using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Text;
using DSWeb.MvcShipping.Models.MsCodeServiceFeeTemplate;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DSWeb.EntityDA;
using DSWeb.Areas.CommMng.Models;
using HcUtility.Comm;
using org.junit.rules;

namespace DSWeb.MvcShipping.DAL.MsCodeServiceFeeTemplateDAL
{
    public class MsCodeServiceFeeTemplateDAL
    {
        #region Inquery DataList

        static public List<MsCodeServiceFeeTemplate> GetDataList(string strCondition, string userid, string usercode, string orgcode, string sort = null)
        {
/*
            var rangstr = GetRangDAStr("index", userid, usercode, orgcode);

            if (!string.IsNullOrEmpty(rangstr))
            {
                if (!string.IsNullOrEmpty(strCondition))
                {
                    strCondition = strCondition + " and " + rangstr;
                }
                else
                {
                    strCondition = rangstr;
                }
            }
*/
            var strSql = new StringBuilder();
            strSql.Append("SELECT ");
            strSql.Append("GID,OPTYPE,CORPID,CUSTOMERNAME,[NAME],[DESCRIPTION],CREATEUSER");
            strSql.Append(",(select EnumValueName from tSysEnumValue where LangId=0 and EnumTypeID=96005 and EnumValueID=code_servcie_fee_template.OpType) as OpTyperef");
            strSql.Append(" from code_servcie_fee_template  ");

            if (!string.IsNullOrEmpty(strCondition))
            {
                strSql.Append(" where " + strCondition);
            }
            var sortstring = DatasetSort.Getsortstring(sort);
            if (!string.IsNullOrEmpty(sortstring))
            {
                strSql.Append(" order by " + sortstring);
            }
            else
            {
                strSql.Append(" order by OPTYPE,CUSTOMERNAME");

            }

            return SetData(strSql);
        }

        static public MsCodeServiceFeeTemplate GetData(string condition)
        {

            var strSql = new StringBuilder();
            strSql.Append("SELECT ");
            strSql.Append("GID,OPTYPE,CORPID,CUSTOMERNAME,[NAME],[DESCRIPTION],CREATEUSER");
            strSql.Append(",(select EnumValueName from tSysEnumValue where LangId=0 and EnumTypeID=96005 and EnumValueID=code_servcie_fee_template.OpType) as OpTyperef");
            strSql.Append(" from code_servcie_fee_template  ");

            if (!string.IsNullOrEmpty(condition))
            {
                strSql.Append(" where " + condition);
            }


            var list = SetData(strSql);
            if (list.Count > 0)
                return list[0];

            return new MsCodeServiceFeeTemplate();
        }


        private static List<MsCodeServiceFeeTemplate> SetData(StringBuilder strSql)
        {
            var headList = new List<MsCodeServiceFeeTemplate>();
            Database db = DatabaseFactory.CreateDatabase();
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    MsCodeServiceFeeTemplate data = new MsCodeServiceFeeTemplate();
                    #region Set DB data to Object
                    data.GID = Convert.ToString(reader["GID"]);
                    data.OPTYPE = Convert.ToString(reader["OPTYPE"]);
                    data.OPTYPEREF = Convert.ToString(reader["OpTyperef"]);
                    data.CORPID = Convert.ToString(reader["CORPID"]);
                    data.CUSTOMERNAME = Convert.ToString(reader["CUSTOMERNAME"]);
                    data.NAME = Convert.ToString(reader["NAME"]);
                    data.DESCRIPTION = Convert.ToString(reader["DESCRIPTION"]);
                    data.CREATEUSER = Convert.ToString(reader["CREATEUSER"]);


                    #endregion
                    headList.Add(data);
                }
                reader.Close();
            }
            return headList;
        }
        #endregion


        #region 明细表

        static public List<MsCodeServiceFeeTemplateDetail> GetBodyList(string strCondition)
        {
            var strSql = new StringBuilder();
            strSql.Append("SELECT ");
            strSql.Append("GID,TEMPLATEID,OPField");
            strSql.Append(",FEENAME,CUSTOMERNAME,CLIENT,UNIT,CURRENCY,UNITPRICE,TAXRATE");
            strSql.Append(",CustomerType");
            strSql.Append(",(select SERVICENAME from code_op_service where  OPField=code_service_fee_templatedetail.OPField and OPTYPE=(select top 1 OPTYPE from code_servcie_fee_template where GID=code_service_fee_templatedetail.TEMPLATEID)) as SERVICENAME");
            strSql.Append(",REMARK,SORT,CREATEUSER,CREATETIME,MODIFIEDUSER,MODIFIEDTIME,FEETYPE,EXCHANGERATE");
            strSql.Append(" from code_service_fee_templatedetail  ");
            if (strCondition.Trim() != String.Empty)
            {
                strSql.Append(" where " + strCondition);
            }
            return SetBodyData(strSql);
        }

        private static List<MsCodeServiceFeeTemplateDetail> SetBodyData(StringBuilder strSql)
        {
            var bodyList = new List<MsCodeServiceFeeTemplateDetail>();
            Database db = DatabaseFactory.CreateDatabase();
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    MsCodeServiceFeeTemplateDetail data = new MsCodeServiceFeeTemplateDetail();
                    #region Set DB data to Object
                    data.GID = Convert.ToString(reader["GID"]);
                    data.TemplateID = Convert.ToString(reader["TEMPLATEID"]);
                    data.FeeName = Convert.ToString(reader["FEENAME"]);
                    data.CustomerName = Convert.ToString(reader["CUSTOMERNAME"]);
                    data.SERVICENAME= Convert.ToString(reader["SERVICENAME"]);
                    data.OPField = Convert.ToString(reader["OPField"]);
                    if (reader["CLIENT"] != DBNull.Value)
                    data.Client = Convert.ToInt16(reader["CLIENT"]);
                    data.CustomerType = Convert.ToString(reader["CustomerType"]);
                    data.Unit = Convert.ToString(reader["UNIT"]);
                    if (reader["UNITPRICE"] != DBNull.Value)
                    data.UnitPrice = Convert.ToDecimal(reader["UNITPRICE"]);
                    if (reader["TAXRATE"] != DBNull.Value)
                        data.TAXRATE = Convert.ToDecimal(reader["TAXRATE"]);
                    if (reader["SORT"] != DBNull.Value)
                    data.Sort = Convert.ToInt16(reader["SORT"]);
                    if (reader["FeeType"] != DBNull.Value)
                        data.FeeType = Convert.ToInt16(reader["FeeType"]);
                    data.Currency = Convert.ToString(reader["CURRENCY"]);
                    if (reader["EXCHANGERATE"] != DBNull.Value)
                        data.ExchangeRate = Convert.ToDecimal(reader["EXCHANGERATE"]);
                    data.CreateUser = Convert.ToString(reader["CreateUser"]);
                    data.ModifiedUser = Convert.ToString(reader["ModifiedUser"]);
                    data.Remark = Convert.ToString(reader["Remark"]);
      

                    #endregion

                    bodyList.Add(data);
                }
                reader.Close();
            }

            return bodyList;
        }

        static public List<MsCodeServiceFeeTemplateDetail> GetBodyListtran(string strCondition, Database db, DbTransaction tran)
        {
            var strSql = new StringBuilder();
            strSql.Append("SELECT ");
            strSql.Append("GID,TEMPLATEID,OPField");
            strSql.Append(",FEENAME,CUSTOMERNAME,CLIENT,UNIT,CURRENCY,UNITPRICE,TAXRATE");
            strSql.Append(",CustomerType");
            strSql.Append(",(select SERVICENAME from code_op_service where  OPField=code_service_fee_templatedetail.OPField and OPTYPE=(select top 1 OPTYPE from code_servcie_fee_template where GID=code_service_fee_templatedetail.TEMPLATEID)) as SERVICENAME");
            strSql.Append(",REMARK,SORT,CREATEUSER,CREATETIME,MODIFIEDUSER,MODIFIEDTIME,FEETYPE,EXCHANGERATE");
            strSql.Append(" from code_service_fee_templatedetail  ");
            if (strCondition.Trim() != String.Empty)
            {
                strSql.Append(" where " + strCondition);
            }
            return SetBodyDataTran(strSql, db, tran);
        }

        private static List<MsCodeServiceFeeTemplateDetail> SetBodyDataTran(StringBuilder strSql, Database db, DbTransaction tran)
        {
            var bodyList = new List<MsCodeServiceFeeTemplateDetail>();
            using (IDataReader reader = db.ExecuteReader(tran,CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    MsCodeServiceFeeTemplateDetail data = new MsCodeServiceFeeTemplateDetail();
                    #region Set DB data to Object
                    data.GID = Convert.ToString(reader["GID"]);
                    data.TemplateID = Convert.ToString(reader["TEMPLATEID"]);
                    data.FeeName = Convert.ToString(reader["FEENAME"]);
                    data.CustomerName = Convert.ToString(reader["CUSTOMERNAME"]);
                    data.SERVICENAME = Convert.ToString(reader["SERVICENAME"]);
                    data.OPField = Convert.ToString(reader["OPField"]);
                    if (reader["CLIENT"] != DBNull.Value)
                        data.Client = Convert.ToInt16(reader["CLIENT"]);
                    data.CustomerType = Convert.ToString(reader["CustomerType"]);
                    data.Unit = Convert.ToString(reader["UNIT"]);
                    if (reader["UNITPRICE"] != DBNull.Value)
                        data.UnitPrice = Convert.ToDecimal(reader["UNITPRICE"]);
                    if (reader["TAXRATE"] != DBNull.Value)
                        data.TAXRATE = Convert.ToDecimal(reader["TAXRATE"]);
                    if (reader["SORT"] != DBNull.Value)
                        data.Sort = Convert.ToInt16(reader["SORT"]);
                    if (reader["FeeType"] != DBNull.Value)
                        data.FeeType = Convert.ToInt16(reader["FeeType"]);
                    data.Currency = Convert.ToString(reader["CURRENCY"]);
                    if (reader["EXCHANGERATE"] != DBNull.Value)
                        data.ExchangeRate = Convert.ToDecimal(reader["EXCHANGERATE"]);
                    data.CreateUser = Convert.ToString(reader["CreateUser"]);
                    data.ModifiedUser = Convert.ToString(reader["ModifiedUser"]);
                    data.Remark = Convert.ToString(reader["Remark"]);


                    #endregion

                    bodyList.Add(data);
                }
                reader.Close();
            }

            return bodyList;
        }


        #endregion


        public static DBResult SaveDetail(MsCodeServiceFeeTemplate headData, List<MsCodeServiceFeeTemplateDetail> bodyList)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {
                    var cmdInsert =
                        db.GetSqlStringCommand(
                            @"insert into code_service_fee_templatedetail (GID, TEMPLATEID,FEENAME,CUSTOMERNAME,OPField,CustomerType,UNIT,CURRENCY,UNITPRICE,
                               REMARK,SORT,CREATEUSER,MODIFIEDUSER,FEETYPE,EXCHANGERATE,TAXRATE) 
                                   values (@GID, @TEMPLATEID,@FEENAME,@CUSTOMERNAME,@OPField,@CustomerType,@UNIT,@CURRENCY,@UNITPRICE,
                               @REMARK,@SORT,@CREATEUSER,@MODIFIEDUSER,@FEETYPE,@EXCHANGERATE,@TAXRATE) ");
                    var cmdUpdate =
                        db.GetSqlStringCommand(
                            @"update code_service_fee_templatedetail set FEENAME=@FEENAME,CUSTOMERNAME=@CUSTOMERNAME,OPField=@OPField,CustomerType=@CustomerType
                              ,UNIT=@UNIT,CURRENCY=@CURRENCY,UNITPRICE=@UNITPRICE,REMARK=@REMARK,SORT=@SORT,MODIFIEDUSER=@MODIFIEDUSER,FEETYPE=@FEETYPE
                               ,EXCHANGERATE=@EXCHANGERATE,TAXRATE=@TAXRATE where GID=@GID ");

                    if (bodyList != null)
                    {
                        foreach (var enumValue in bodyList)
                        {
                            if (enumValue.TemplateID == "" || enumValue.TemplateID == "*")
                            {

                                cmdInsert.Parameters.Clear();

                                db.AddInParameter(cmdInsert, "@GID", DbType.String, enumValue.GID);
                                db.AddInParameter(cmdInsert, "@TEMPLATEID", DbType.String, headData.GID);
                                db.AddInParameter(cmdInsert, "@FEENAME", DbType.String, enumValue.FeeName);
                                db.AddInParameter(cmdInsert, "@CUSTOMERNAME", DbType.String, enumValue.CustomerName);
                                db.AddInParameter(cmdInsert, "@OPField", DbType.String, enumValue.OPField);
                                db.AddInParameter(cmdInsert, "@CustomerType", DbType.String, enumValue.CustomerType);
                                db.AddInParameter(cmdInsert, "@UNIT", DbType.String, enumValue.Unit);
                                db.AddInParameter(cmdInsert, "@CURRENCY", DbType.String, enumValue.Currency);
                                db.AddInParameter(cmdInsert, "@UNITPRICE", DbType.Decimal, enumValue.UnitPrice);
                                db.AddInParameter(cmdInsert, "@REMARK", DbType.String, enumValue.Remark);
                                db.AddInParameter(cmdInsert, "@SORT", DbType.Int32, enumValue.Sort);
                                db.AddInParameter(cmdInsert, "@CREATEUSER", DbType.String, enumValue.CreateUser);
                                db.AddInParameter(cmdInsert, "@MODIFIEDUSER", DbType.String, enumValue.ModifiedUser);
                                db.AddInParameter(cmdInsert, "@FEETYPE", DbType.Int32, enumValue.FeeType);
                                db.AddInParameter(cmdInsert, "@EXCHANGERATE", DbType.Decimal, enumValue.ExchangeRate);
                                db.AddInParameter(cmdInsert, "@TAXRATE", DbType.Decimal, enumValue.TAXRATE);

                                db.ExecuteNonQuery(cmdInsert, tran);
                            }
                            else {

                                cmdUpdate.Parameters.Clear();

                                db.AddInParameter(cmdUpdate, "@GID", DbType.String, enumValue.GID);
                                db.AddInParameter(cmdUpdate, "@FEENAME", DbType.String, enumValue.FeeName);
                                db.AddInParameter(cmdUpdate, "@CUSTOMERNAME", DbType.String, enumValue.CustomerName);
                                db.AddInParameter(cmdUpdate, "@OPField", DbType.String, enumValue.OPField);
                                db.AddInParameter(cmdUpdate, "@CustomerType", DbType.String, enumValue.CustomerType);
                                db.AddInParameter(cmdUpdate, "@UNIT", DbType.String, enumValue.Unit);
                                db.AddInParameter(cmdUpdate, "@CURRENCY", DbType.String, enumValue.Currency);
                                db.AddInParameter(cmdUpdate, "@UNITPRICE", DbType.Decimal, enumValue.UnitPrice);
                                db.AddInParameter(cmdUpdate, "@REMARK", DbType.String, enumValue.Remark);
                                db.AddInParameter(cmdUpdate, "@SORT", DbType.Int32, enumValue.Sort);
                                db.AddInParameter(cmdUpdate, "@MODIFIEDUSER", DbType.String, enumValue.ModifiedUser);
                                db.AddInParameter(cmdUpdate, "@FEETYPE", DbType.Int32, enumValue.FeeType);
                                db.AddInParameter(cmdUpdate, "@EXCHANGERATE", DbType.Decimal, enumValue.ExchangeRate);
                                db.AddInParameter(cmdUpdate, "@TAXRATE", DbType.Decimal, enumValue.TAXRATE);

                                db.ExecuteNonQuery(cmdUpdate, tran);                      
                            
                            
                            }
                        }
                    }

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "保存出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "保存成功";

            return result;
        }


        public static DBResult DeleteDetail(MsCodeServiceFeeTemplate headData)
        {
            var result = new DBResult();

            Database db = DatabaseFactory.CreateDatabase();
            using (var conn = db.CreateConnection())
            {
                conn.Open();
                var tran = conn.BeginTransaction();

                try
                {

                    var cmdDelete = db.GetSqlStringCommand("delete from code_service_fee_templatedetail where TEMPLATEID='" + headData.GID + "'");
                    db.ExecuteNonQuery(cmdDelete, tran);

                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();

                    result.Success = false;
                    result.Message = "删除出现错误,请重试或联系系统管理员";

                    return result;
                }
            }

            result.Success = true;
            result.Message = "保存成功";

            return result;
        }



        #region 参照部分

        public static string GetRangDAStr(string tb, string userid, string username, string companyid)
        {
            string str = "";
            var strSql = new StringBuilder();
            strSql.Append("SELECT ");
            strSql.Append(" VISIBLERANGE,OPERATERANGE ");
            strSql.Append("  from VW_User_Authority ");
            strSql.Append("  where [NAME]='modOpApplyService' and USERID='" + userid + "' and ISDELETE=0");

            string visiblerange = "4";
            string operaterange = "4";

            Database db = DatabaseFactory.CreateDatabase();
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (reader.Read())
                {
                    visiblerange = Convert.ToString(reader["VISIBLERANGE"]);
                    operaterange = Convert.ToString(reader["OPERATERANGE"]);
                    break;
                }
                reader.Close();
            }
            if (visiblerange == "4")
            {
                str = "S.OP='" + username + "'";
            }
            else if (visiblerange == "3")
            {
                str = "S.OP='" + username + "'";
            }
            else if (visiblerange == "2")
            {
                var rangeDa = new RangeDA();
                var deptname = rangeDa.GetDEPTNAME(userid);
                //str = " S.OP in (select showname from [user] where GID in (select USERID from user_company where COMPANYID='" + companyid + "') and GID in (select userid from user_baseinfo where DEPTNAME='" + deptname + "'))";
                str = $" exists(select 1 from vw_user where SHOWNAME =S.OP and COMPANYID='{companyid}' and DEPTNAME='{deptname}')";
            }
            else if (visiblerange == "1")
            {
                //str = " S.OP in (select showname from [user] where GID in (select USERID from user_company where COMPANYID='" + companyid + "')) ";
                str = $" exists(select 1 from vw_user where SHOWNAME =S.OP and COMPANYID='{companyid}' )";
            }
            else if (visiblerange == "0")
            {
                str = " 1=1 ";
            }

            return str;
        }


        #endregion
    }
}