using System;
using System.Linq;
using System.Web.Mvc;
using DSWeb.Areas.Account.DAL.Chfee_Hexiao;
using DSWeb.Areas.Import.DAL.CW;
using DSWeb.Areas.Account.Models.Chfee_Settlement;
using DSWeb.Areas.Account.Models.Chfee_do_detail;
using DSWeb.Areas.Account.Models.BillChfeeDetail;
using DSWeb.Areas.Account.Models.MsCwVouchersGl3;
using DSWeb.MvcShipping.Helper;
using DSWeb.MvcShipping.Comm.Cookie;
using DSWeb.Areas.CommMng.DAL;
using System.Collections.Generic;
using HcUtility.Comm;
using HcUtility.Core;
using DSWeb.EntityDA;
using DSWeb.Areas.Account.Models.Chfee_Exrate;
using DSWeb.MvcShipping.DAL.MsSysBillNoSet;
using DSWeb.MvcShipping.Models.MsSysBillNoSet;
using DSWeb.MvcShipping.DAL.ChMonthCloseDAL;
using DSWeb.TruckMng.Helper.Repository;
using System.Text;
using DSWeb.Areas.CommMng.Models;
using DSWeb.MvcShipping.DAL.MsSysParamSet;
using DSWeb.Areas.Account.DAL.Chfee_Settlement;
using DSWeb.Areas.Account.Models.ChfeeDetail;

namespace DSWeb.Areas.Account.Controllers
{
    [JsonRequestBehavior]
    public class Chfee_hexiaoController : Controller
    {
      
        // GET: 
        public ActionResult HexiaoIndex()
        {
            return View();
        }
        // GET: 
        public ActionResult HexiaoEdit()
        {
            return View();
        }

        //
        // GET:

        public ContentResult GetDataList(int start, int limit, string sort, string condition,string isload="0")
        {
            int total=0;
            var dataList = ChHexiaoDAL.GetHexiaoDataList(condition, start, limit, out total, CookieConfig.GetCookie_UserId(Request), CookieConfig.GetCookie_UserCode(Request), Convert.ToString(Session["COMPANYID"]), sort, isload);
            //var list = dataList.Skip(start).Take(limit);

            //var json = JsonConvert.Serialize(new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = list.ToList() });
            var json = JsonConvert.Serialize(new { Success = true, Message = "查询成功", totalCount = total, data = dataList.ToList() });
            return new ContentResult() { Content = json };
        }
        public ContentResult GetDataListStr(int start, int limit, string sort, string condition)
        {
            var dataListStr = ChHexiaoDAL.GetHexiaoDataListStr(condition, CookieConfig.GetCookie_UserId(Request), CookieConfig.GetCookie_UserCode(Request), Convert.ToString(Session["COMPANYID"]), sort);

            var json = JsonConvert.Serialize(new { Success = true, Message = "查询成功", data = dataListStr });
            return new ContentResult() { Content = json };
        }


        public ContentResult GetData(string handle, string condition)
        {
            ChfeeHexiao head = null;
            int total = 0;
            if (handle == "edit")
            {
                var list = ChHexiaoDAL.GetHexiaoDataList(condition, 0, 1, out total, CookieConfig.GetCookie_UserId(Request), CookieConfig.GetCookie_UserCode(Request), Convert.ToString(Session["COMPANYID"]));
                if (list.Count > 0)
                    head = list[0];
            }

            if (head == null)
            {
                head = new ChfeeHexiao();
                head.CREATEUSER = CookieConfig.GetCookie_UserId(Request);
                head.CREATEUSERREF = Convert.ToString(Session["SHOWNAME"]);
                head.CREATETIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                head.BILLDATE = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

            }

            if (handle == "add")
            {

            }

            var json = JsonConvert.Serialize(
               new { Success = true, Message = "查询成功", data = head });
            return new ContentResult() { Content = json };
        }


        public ContentResult GetBillList(string condition,string sort)
        {
            var dataList = ChHexiaoDAL.GetBodyList(condition, sort);


            var json = JsonConvert.Serialize(new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = dataList.ToList() });
            return new ContentResult() { Content = json };
        }

        public ContentResult GetBillSum(string condition)
        {
            var dataList = ChHexiaoDAL.GetBodySumList(condition);


            var json = JsonConvert.Serialize(new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = dataList.ToList() });
            return new ContentResult() { Content = json };
        }

        public ContentResult GetFeeDataList(int start, int limit, string sort, string condition, int billtype)
        {
            var dataList = ChHexiaoDAL.GetFeeDataList(condition, CookieConfig.GetCookie_UserId(Request), Convert.ToString(Session["SHOWNAME"]), Convert.ToString(Session["COMPANYID"]), sort, billtype);
            var list = dataList.Skip(start).Take(limit);
            var json = JsonConvert.Serialize(
             new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = list.ToList() });
            return new ContentResult() { Content = json };
        }

        public ContentResult GetBillDataList(int start, int limit, string sort, string condition, int billtype,string ShenNo="")
        {
            var dataList = new List<BillCustDetail>();
            if (ShenNo != "") {
                dataList = ChHexiaoDAL.GetShenAddBillList(condition, ShenNo, CookieConfig.GetCookie_UserId(Request), Convert.ToString(Session["SHOWNAME"]), Convert.ToString(Session["COMPANYID"]), sort, billtype);
           
            } else 
             dataList = ChHexiaoDAL.GetAddBillList(condition, CookieConfig.GetCookie_UserId(Request), Convert.ToString(Session["SHOWNAME"]), Convert.ToString(Session["COMPANYID"]), sort, billtype);
 //           var list = dataList.Skip(start).Take(limit);
            var json = JsonConvert.Serialize(
             new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = dataList.ToList() });
            return new ContentResult() { Content = json };
        }

        public ContentResult GetFeeDetailList(string sort, string condition, string ShenNo = "")
        {
            var dataList = new List<ChFeeDetail>();
            if (ShenNo != "")
            {
                dataList = ChHexiaoDAL.GetShenFeeDetailList(condition, ShenNo, sort);
            }
            else
                dataList = ChHexiaoDAL.GetFeeDetailList(condition, sort);
            var json = JsonConvert.Serialize(
             new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = dataList.ToList() });
            return new ContentResult() { Content = json };
        }

        public ContentResult GetAddSum(string condition, int billtype)
        {
            var dataList = ChHexiaoDAL.GetAddSum(condition, CookieConfig.GetCookie_UserId(Request), Convert.ToString(Session["SHOWNAME"]), Convert.ToString(Session["COMPANYID"]), billtype);


            var json = JsonConvert.Serialize(new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = dataList.ToList() });
            return new ContentResult() { Content = json };
        }

        public ContentResult Save(string opstatus, string data,string body)
         {
             var headData = JsonConvert.Deserialize<ChfeeHexiao>(data);
             var bodyList = JsonConvert.Deserialize<List<ChSettlement>>(body);
             if (headData.BILLNO != "" && headData.BILLNO != "*") opstatus = "edit";
                
            if (opstatus == "add")
            {
                headData.GID = Guid.NewGuid().ToString();
                if (headData.BILLNO == "" || headData.BILLNO == "*")
                {
                   var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='业务核销'", Convert.ToString(Session["COMPANYID"]));
                   if (billnoset.BILLTYPE != "")
                      headData.BILLNO = MsSysBillNoSetDAL.GetBillNo(billnoset, headData.BILLDATE.ToString().Trim(), headData.BILLDATE.ToString().Trim());
                   else
                     headData.BILLNO = PubSysDAL.GetBillNo("0612");

                }
                headData.COMPANYID = Convert.ToString(Session["COMPANYID"]);
                headData.DbOperationType = DbOperationType.DbotIns;
            }
            else if (opstatus == "edit")
            {
                headData.DbOperationType = DbOperationType.DbotUpd;
                headData.ModelUIStatus = "E";
            }
            else
            {
                headData.DbOperationType = DbOperationType.DbotDel;
            }
            var ct = ChHexiaoDAL.GetRdCount("GID<>'" + headData.GID + "' AND BILLNO='" + headData.BILLNO + "' ");
            if (ct != 0)
            {
                var jsonRespose0 = new JsonResponse
                {
                    Success = false,
                    Message = "核销编号重复,不允许保存!"
                };

                return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose0) };
            }


            var BILLNO = headData.BILLNO;
            if (bodyList != null) {
                T_ALL_DA T_ALL_DA = new EntityDA.T_ALL_DA();
                foreach (var enumValue in bodyList)
                {
                    if (enumValue.SETTLETIME == "") enumValue.SETTLETIME = DateTime.Now.ToString("yyyy-MM-dd");
                    if (enumValue.BILLNO == "" || enumValue.BILLNO == "*")
                    {
 //                       enumValue.GID = Guid.NewGuid().ToString();
                        enumValue.BILLDATE = DateTime.Now;
                        enumValue.HXBILLNO = headData.BILLNO;
                        enumValue.CREATETIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        enumValue.CREATEUSER = CookieConfig.GetCookie_UserId(Request);
                        enumValue.SETTLEUSER = CookieConfig.GetCookie_UserId(Request);
                        if (enumValue.BILLTYPE == 1)
                        {
                            var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='收费结算'", Convert.ToString(Session["COMPANYID"]));
                            if (billnoset.BILLTYPE != "")
                                enumValue.BILLNO = MsSysBillNoSetDAL.GetBillNo(billnoset, enumValue.SETTLETIME.ToString().Trim(), enumValue.BILLDATE.ToString().Trim());
                            else enumValue.BILLNO = PubSysDAL.GetBillNo("0305");
                        }
                        else {
                            var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='付费结算'", Convert.ToString(Session["COMPANYID"]));
                            if (billnoset.BILLTYPE != "")
                                enumValue.BILLNO = MsSysBillNoSetDAL.GetBillNo(billnoset, enumValue.SETTLETIME.ToString().Trim(), enumValue.BILLDATE.ToString().Trim());
                            else
                                enumValue.BILLNO = PubSysDAL.GetBillNo("0304");              
                        
                        }
                        enumValue.COMPANYID = Convert.ToString(Session["COMPANYID"]);
                        if (enumValue.CURR == "RMB")
                        {
                            enumValue.AMOUNTRMB = enumValue.AMOUNT;
                            enumValue.ACCOUNTRMB = enumValue.ACCOUNT;
                            enumValue.AMOUNTUSD = 0;
                            enumValue.ACCOUNTUSD = "";

                        }
                        else
                        {

                            enumValue.AMOUNTUSD = enumValue.AMOUNT;
                            enumValue.ACCOUNTUSD = enumValue.ACCOUNT;
                            enumValue.ACCOUNTRMB = "";
                            enumValue.AMOUNTRMB = 0;
                        }
                        if (enumValue.REMITTANCEAMOUNT == "") enumValue.REMITTANCEAMOUNT = "0";
                        if (enumValue.BUYRATE == "") enumValue.BUYRATE = "0";
                        if (enumValue.SELLRATE == "") enumValue.SELLRATE = "0";
                        if (enumValue.SETTLRATE == "") enumValue.SETTLRATE = "0";


                        enumValue.ACCOUNTS_CURRENCY = enumValue.CURR;//
                        var ct2 = ChsettlementDAL.GetRdCount("GID<>'" + enumValue.GID + "' AND BILLNO='" + enumValue.BILLNO + "' ");
                        if (ct2 != 0)
                        {
                            var jsonRespose0 = new JsonResponse
                            {
                                Success = false,
                                Message = "结算编号重复,不允许保存!",
                                Data = headData
                            };

                            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose0) };
                        }

                        enumValue.DbOperationType = DbOperationType.DbotIns;
                        var modbbody = new ModelObjectDB();
                        modbbody.Save(enumValue);

                    }
                    else {
                        if (enumValue.CURR == "RMB")
                        {
                            var blUpSQL = "update ch_fee_settlement set BILLTYPE='" + enumValue.BILLTYPE + "',SETTLETIME='" + enumValue.SETTLETIME + "',ACCOUNTRMB='" + enumValue.ACCOUNT + "',SETTLETYPE='" + enumValue.SETTLETYPE + "',FINANCIAL_MONEY='" + enumValue.FINANCIAL_MONEY + "',ADVANCE_MONEY=" + enumValue.ADVANCE_MONEY + ",STLAMOUNT=" + enumValue.STLAMOUNT + " where GID='" + enumValue.GID + "'";
                            var bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);
                        }
                        else {
                            var blUpSQL = "update ch_fee_settlement set BILLTYPE='" + enumValue.BILLTYPE + "',SETTLETIME='" + enumValue.SETTLETIME + "',ACCOUNTUSD='" + enumValue.ACCOUNT + "',SETTLETYPE='" + enumValue.SETTLETYPE + "',FINANCIAL_MONEY='" + enumValue.FINANCIAL_MONEY + "',ADVANCE_MONEY=" + enumValue.ADVANCE_MONEY + ",STLAMOUNT=" + enumValue.STLAMOUNT + " where GID='" + enumValue.GID + "'";
                            var bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);
                        }
                    
                    }



                }
            
            }

            var modb = new ModelObjectDB();
            DBResult result = modb.Save(headData);


            if (result.Success == true) { }
            else
            {
                MsSysBillNoSetDAL.DeleteBsNo(headData.BILLNO);
            }
            var jsonRespose = new JsonResponse
            {
                Success = result.Success,
                Message = result.Message,
                Data = ChHexiaoDAL.GetHexiaoData(" cm.BILLNO='" + BILLNO + "'", CookieConfig.GetCookie_UserId(Request), CookieConfig.GetCookie_UserCode(Request), Convert.ToString(Session["COMPANYID"]))
            };

            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };

        }

        public ContentResult MdStl(string data,decimal stlamount,string billno)
        {
            var headData = JsonConvert.Deserialize<ChSettlement>(data);
            var dataList = ChsettlementDAL.GetBodyList("BILLNO='" + headData.BILLNO+ "'");

            var enumValue = new ChSettlement();
//            enumValue = headData;
            enumValue.GID = Guid.NewGuid().ToString();
            enumValue.BILLDATE = DateTime.Now;
            enumValue.CREATETIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            enumValue.CREATEUSER = CookieConfig.GetCookie_UserId(Request);
            enumValue.HXBILLNO = billno;
            enumValue.BILLTYPE = headData.BILLTYPE;
            enumValue.CUSTOMERNAME = headData.CUSTOMERNAME;
            enumValue.SETTLETIME = headData.SETTLETIME;
            enumValue.SETTLEUSER = headData.SETTLEUSER;
            if (enumValue.BILLTYPE == 1)
            {
                var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='收费结算'", Convert.ToString(Session["COMPANYID"]));
                if (billnoset.BILLTYPE != "")
                    enumValue.BILLNO = MsSysBillNoSetDAL.GetBillNo(billnoset, enumValue.SETTLETIME.ToString().Trim(), enumValue.BILLDATE.ToString().Trim());
                else enumValue.BILLNO = PubSysDAL.GetBillNo("0305");
            }
            else
            {
                var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='付费结算'", Convert.ToString(Session["COMPANYID"]));
                if (billnoset.BILLTYPE != "")
                    enumValue.BILLNO = MsSysBillNoSetDAL.GetBillNo(billnoset, enumValue.SETTLETIME.ToString().Trim(), enumValue.BILLDATE.ToString().Trim());
                else
                    enumValue.BILLNO = PubSysDAL.GetBillNo("0304");

            }
            enumValue.CURR = headData.CURR;
            enumValue.SETTLETYPE = headData.SETTLETYPE;
            enumValue.ACCOUNTRMB = headData.ACCOUNTRMB;
            enumValue.ACCOUNTUSD = headData.ACCOUNTUSD;


            enumValue.COMPANYID = Convert.ToString(Session["COMPANYID"]);
            if (enumValue.CURR == "RMB")
            {
                enumValue.AMOUNTRMB = headData.AMOUNT-stlamount;
                enumValue.AMOUNTUSD = 0;
            }
            else
            {

                enumValue.AMOUNTUSD = headData.AMOUNT - stlamount;
                enumValue.ACCOUNTRMB = "";
                enumValue.AMOUNTRMB = 0;
            }
            
            if (enumValue.REMITTANCEAMOUNT == "") enumValue.REMITTANCEAMOUNT = "0";
            if (enumValue.BUYRATE == "") enumValue.BUYRATE = "0";
            if (enumValue.SELLRATE == "") enumValue.SELLRATE = "0";
            if (enumValue.SETTLRATE == "") enumValue.SETTLRATE = "0";

            enumValue.ACCOUNTS_CURRENCY = enumValue.CURR;//
            enumValue.DbOperationType = DbOperationType.DbotIns;
            var modbbody = new ModelObjectDB();
            DBResult result =modbbody.Save(enumValue);

            var isadd = false;
            if (dataList != null && stlamount!=0)
            {
                T_ALL_DA T_ALL_DA = new EntityDA.T_ALL_DA();
                decimal amount = 0;
                decimal doamount = 0;
                decimal orginamount = 0;
                foreach (var feedovalue in dataList)
                {
                    if (!isadd)
                    {
                        if (headData.BILLTYPE == 1)
                        {
                            if (feedovalue.FEETYPE == 1)
                                amount = amount + feedovalue.AMOUNT;
                            else
                                amount = amount - feedovalue.AMOUNT;

                        }
                        else
                        {
                            if (feedovalue.FEETYPE == 2)
                                amount = amount + feedovalue.AMOUNT;
                            else
                                amount = amount - feedovalue.AMOUNT;
                        }
                        if (amount >= stlamount)
                        {
                            if (amount > stlamount) {
                                if (headData.BILLTYPE == feedovalue.FEETYPE)
                                {
                                       doamount = feedovalue.AMOUNT-(amount-stlamount);
                                }
                                else
                                {
                                    doamount = feedovalue.AMOUNT - (amount - stlamount);
                                }

                                orginamount = Math.Round(feedovalue.ORIGAMOUNT * (doamount / feedovalue.AMOUNT),2, MidpointRounding.AwayFromZero);
                                if (doamount != 0) {
                                    var blUpSQL = "update ch_fee_do set AMOUNT=" + doamount + ",ORIGAMOUNT=" + orginamount + " where GID='" + feedovalue.FEEDOID + "'";
                                    var bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);
                                    blUpSQL = "insert into ch_fee_do (GID,BILLNO,BSNO,MBLNO,HBLNO,CUSTOMERNAME,BSTYPE,FEEID,FEENAME,CURRENCY"
                                     + ",AMOUNT,DOAMOUNT,FEETYPE,CATEGORY,BILLSTATUS,ISDELETED,CREATETIME"
                                     + ",EXCHANGERATE,ORIGCURRENCY,ORIGAMOUNT,INVOICESETTLENO,COMPANYID)"
                                     + "values (NEWID(),'" + enumValue.BILLNO + "','" + feedovalue.BSNO + "','" + feedovalue.MBLNO + "','" + feedovalue.HBLNO + "','" + feedovalue.FEEOBJNAME + "',1,'" + feedovalue.FEEID
                                     + "','" + feedovalue.FEENAME + "','" + feedovalue.CURRENCY + "'" + ","+(feedovalue.AMOUNT-doamount).ToString()+",0,'"+feedovalue.FEETYPE
                                     + "',8,1,0,'"+DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")+"'"
                                    + "," + feedovalue.EXCHANGERATE + ",'" + feedovalue.ORIGCURRENCY + "'," + (feedovalue.ORIGAMOUNT - orginamount).ToString() + ",'','" + Convert.ToString(Session["COMPANYID"]) + "')";
                                    bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);
                      
                                
                                }
                            }
                            isadd = true;
                        }
                    }
                    else {
                        var blUpSQL = "update ch_fee_do set BILLNO='" + enumValue.BILLNO + "' where GID='" + feedovalue.FEEDOID + "'";
                        var bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);               
                    
                    }

                }

                if (headData.CURR == "RMB")
                {
                    var blUpSQL = "update ch_fee_settlement set AMOUNTRMB=" + stlamount + " where BILLNO='" + headData.BILLNO + "'";
                    var bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);
                }
                else
                {
                    var blUpSQL = "update ch_fee_settlement set AMOUNTUSD=" + stlamount + " where BILLNO='" + headData.BILLNO + "'";
                    var bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);
                }
                ChsettlementDAL.p_update_Amount(headData.BILLNO, headData.BILLTYPE);
                ChsettlementDAL.p_update_Amount(enumValue.BILLNO, enumValue.BILLTYPE);
            }
            //var modb = new ModelObjectDB();
            //DBResult result = ChHexiaoDAL.AddDetail(bill, bodyList, curr, Convert.ToString(Session["COMPANYID"]));
            //if (result.Success) { ChHexiaoDAL.p_update_Amount(bill, billtype); }

            
            var jsonRespose = new JsonResponse { Success = result.Success, Message = result.Message };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }


        public ContentResult AddDetail(string bill, string data, string curr,int billtype)
        {
            var bodyList = JsonConvert.Deserialize<List<BillChfeeDetail>>(data);

            var modb = new ModelObjectDB();
            DBResult result = ChHexiaoDAL.AddDetail(bill, bodyList, curr, Convert.ToString(Session["COMPANYID"]));
            if (result.Success) { ChHexiaoDAL.p_update_Amount(bill, billtype); }


            var jsonRespose = new JsonResponse { Success = result.Success, Message = result.Message };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }

        public ContentResult AddBill(string billno, string billcust, string billcurr, string feesql, string storeCurrExrate, int billtype, bool custgroup = false)
        {
            var exrateList = JsonConvert.Deserialize<List<ChFeeExrate>>(storeCurrExrate);

            if ((exrateList == null) || (exrateList.Count == 0))
            {

                exrateList = ChHexiaoDAL.GetCurrExrateData(billcust, billcurr, feesql, custgroup);
                if (exrateList.Count == 0)
                {
                    var modb = new ModelObjectDB();
                    DBResult result = ChHexiaoDAL.AddBill(billno, billcust, billcurr, feesql, exrateList, Convert.ToString(Session["COMPANYID"]), custgroup);
                    if (result.Success) { ChHexiaoDAL.p_update_Amount(billno, billtype); }

                    var jsonRespose = new JsonResponse { Success = result.Success, Message = result.Message };
                    return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };


                }
                else
                {
                    var jsonRespose = new JsonResponse { Success = true, Message = "查询成功", Data = exrateList.ToList() };
                    return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };


                }

            }
            else
            {

                var modb = new ModelObjectDB();
                DBResult result = ChHexiaoDAL.AddBill(billno, billcust, billcurr, feesql, exrateList, Convert.ToString(Session["COMPANYID"]));
                if (result.Success) { ChHexiaoDAL.p_update_Amount(billno, billtype); }

                var jsonRespose = new JsonResponse { Success = result.Success, Message = result.Message };
                return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
            }

        }

        public ContentResult DelBill(string data, string billno,int billtype)
        {

            var bodyList = JsonConvert.Deserialize<List<Chfee_do_detail>>(data);

            DBResult result = ChHexiaoDAL.DelFeeDo(bodyList);
            int total = 0;
            var stllist = ChsettlementDAL.GetDataList(" HXBILLNO='" + billno + "'", 0, 100, out total, CookieConfig.GetCookie_UserId(Request), CookieConfig.GetCookie_UserCode(Request), Convert.ToString(Session["COMPANYID"]), "", 0);
            if (stllist != null)
            {
                foreach (var enumValue in stllist)
                {
                    ChHexiaoDAL.p_update_Amount(enumValue.BILLNO, enumValue.BILLTYPE); 

                }
            }
            var jsonRespose = new JsonResponse { Success = result.Success, Message = result.Message };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }



        //


        public ContentResult Delete(string data)
        {
            var headData = JsonConvert.Deserialize<ChfeeHexiao>(data);
            var result = new DBResult();

            var modb = new ModelObjectDB();
            result=modb.Delete(headData);
            MsSysBillNoSetDAL.DeleteBsNo(headData.BILLNO);
            if (result.Success) {
               int total = 0;
               var stllist=ChsettlementDAL.GetDataList(" HXBILLNO='"+headData.BILLNO+"'", 0,100, out total, CookieConfig.GetCookie_UserId(Request), CookieConfig.GetCookie_UserCode(Request), Convert.ToString(Session["COMPANYID"]),"", 0);
               if (stllist != null)
               {
                   foreach (var enumValue in stllist)
                   {

                       var dataList = ChsettlementDAL.GetPayDetailList(enumValue.BILLNO);
                       if (dataList.Count!=0)
                       {
                           result = ChsettlementDAL.DelAppStl(dataList, enumValue.BILLNO);
                       }

                       var dataListbody = ChsettlementDAL.GetBodyList("BILLNO='" + enumValue.BILLNO + "'");
                       if (dataListbody.Count != 0)
                       {
                           result =ChsettlementDAL.DelFeeDo(dataListbody);
                       }
                       if (result.Success)
                       {
                           var modb2 = new ModelObjectDB();
                           modb2.Delete(enumValue);
                           MsSysBillNoSetDAL.DeleteBsNo(enumValue.BILLNO);
                           ChsettlementDAL.DelRemit(enumValue.BILLNO);
                       }
                   }
               }
               T_ALL_DA T_ALL_DA = new EntityDA.T_ALL_DA();
               var blUpSQL = "  insert into sys_log(GID,NAME,LOGTYPE,LOGTIME,LOGCONTENT,CREATEUSER) values(NEWID(),'" + headData.BILLNO + "','删除核销','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + headData.BILLNO + '(' + headData.CUSTOMERNAME + ')' + "','" + Convert.ToString(Session["USERID"]) + "')";
               bool bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);
            }
             
            var jsonRespose = new JsonResponse { Success = result.Success, Message = result.Message };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }

   


        #region 锁定和撤销锁定

         public ContentResult Lock(string bill, string remark)
         {

             DBResult result = ChHexiaoDAL.Lock(bill, remark);

             var json = JsonConvert.Serialize(result);
             return new ContentResult() { Content = json };
         }

         public ContentResult UnLock(string bill)
         {

             DBResult result = ChHexiaoDAL.UnLock(bill);

             var json = JsonConvert.Serialize(result);
             return new ContentResult() { Content = json };
         }

         public ContentResult LockList(string bills)
         {

             DBResult result = ChHexiaoDAL.LockList(bills);

             var json = JsonConvert.Serialize(result);
             return new ContentResult() { Content = json };
         }

         public ContentResult UnLockList(string bills)
         {

             DBResult result = ChHexiaoDAL.UnLockList(bills);

             var json = JsonConvert.Serialize(result);
             return new ContentResult() { Content = json };
         }




        #endregion




        public ContentResult GetDefaulExrate(string billno,string curr)
        {
            T_ALL_DA T_ALL_DA = new EntityDA.T_ALL_DA();
            var EXCHANGERATE = T_ALL_DA.GetStrSQL("EXCHANGERATE", "select top 1  EXCHANGERATE FROM CH_FEE WHERE CURRENCY='" + curr + "' AND GID IN (SELECT FEEID FROM CH_FEE_DO WHERE BILLNO='" + billno + "')");

            var jsonRespose = new JsonResponse { Success = true, Message = "", Data = EXCHANGERATE };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }

        #region  自动核销冲抵费用

        public ContentResult AutoHeXiaoCD(string data)
        {
           var bodyList = JsonConvert.Deserialize<List<Chfee_do_detail>>(data);

           if (bodyList != null && bodyList.Count > 0) {

               var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='业务核销'", Convert.ToString(Session["COMPANYID"]));
               var crbillnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='付费结算'", Convert.ToString(Session["COMPANYID"]));
               var drbillnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='收费结算'", Convert.ToString(Session["COMPANYID"]));
               foreach (var enumValue in bodyList)
               {
                   var feesql = " f.FEESTATUS=0 and f.SETTLEMENT=0 and f.ORDERAMOUNT=0 and f.ORDERINVOICE=0 AND ISNULL(F.INVOICE,0)=0 AND F.AMOUNT<>0 "
                   + " and f.FEETYPE=" + enumValue.FEETYPE + " AND F.CUSTOMERNAME='" + enumValue.CUSTNAME + "' AND F.CURRENCY='"+enumValue.CURRENCY+"' "
                   + " and f.BSNO IN (SELECT BSNO FROM V_OP_BILL WHERE PARENTID='" + enumValue.PARENTID + "' AND PARENTID IN (SELECT PARENTID FROM V_CD_FEELIST)) ";
                   var FeeList = ChsettlementDAL.GetFeeDetailList(feesql,"",CookieConfig.GetCookie_UserId(Request), Convert.ToString(Session["SHOWNAME"]), Convert.ToString(Session["COMPANYID"]));
                   if (FeeList.Count != 0) {
                       var HEXIAOBILLNO = "";
                       if (billnoset.BILLTYPE != "")
                           HEXIAOBILLNO = MsSysBillNoSetDAL.GetBillNo(billnoset, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"));
                       else
                           HEXIAOBILLNO = PubSysDAL.GetBillNo("0612");
                       var BILLNO = "";
                       if (enumValue.FEETYPE == 1)
                       {
                           if (drbillnoset.BILLTYPE != "")
                               BILLNO = MsSysBillNoSetDAL.GetBillNo(drbillnoset, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"));
                           else BILLNO = PubSysDAL.GetBillNo("0305");
                       }
                       else {
                           if (crbillnoset.BILLTYPE != "")
                               BILLNO = MsSysBillNoSetDAL.GetBillNo(crbillnoset, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"));
                           else
                               BILLNO = PubSysDAL.GetBillNo("0304");                
                       }

                       DBResult result = ChsettlementDAL.AddBill(BILLNO,"", enumValue.CUSTNAME, enumValue.CURRENCY, feesql,null, Convert.ToString(Session["USERID"]), CookieConfig.GetCookie_UserCode(Request), Convert.ToString(Session["COMPANYID"]),false);
                       if (result.Success)
                       {

                           var ChStl = new ChSettlement();
                           //            enumValue = headData;
                           ChStl.GID = Guid.NewGuid().ToString();
                           ChStl.BILLDATE = DateTime.Now;
                           ChStl.CREATETIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                           ChStl.CREATEUSER = CookieConfig.GetCookie_UserId(Request);
                           ChStl.BILLNO = BILLNO;
                           ChStl.BILLTYPE = enumValue.FEETYPE;
                           ChStl.CUSTOMERNAME = enumValue.CUSTNAME;
                           ChStl.SETTLETIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                           ChStl.SETTLEUSER = CookieConfig.GetCookie_UserId(Request);
                           ChStl.CURR = enumValue.CURRENCY;
                           ChStl.SETTLETYPE = 8;
                           ChStl.ACCOUNTRMB = "";
                           ChStl.ACCOUNTUSD = "";
                           ChStl.COMPANYID = Convert.ToString(Session["COMPANYID"]);
                           ChStl.HXBILLNO = HEXIAOBILLNO;
                           if (ChStl.CURR == "RMB")
                           {
                               ChStl.AMOUNTRMB = 0;
                               ChStl.AMOUNTUSD = 0;
                           }
                           else
                           {

                               ChStl.AMOUNTUSD = 0;
                               ChStl.ACCOUNTRMB = "";
                               ChStl.AMOUNTRMB = 0;
                           }

                           if (ChStl.REMITTANCEAMOUNT == "") ChStl.REMITTANCEAMOUNT = "0";
                           if (ChStl.BUYRATE == "") ChStl.BUYRATE = "0";
                           if (ChStl.SELLRATE == "") ChStl.SELLRATE = "0";
                           if (ChStl.SETTLRATE == "") ChStl.SETTLRATE = "0";

                           ChStl.ACCOUNTS_CURRENCY = ChStl.CURR;//
                           ChStl.DbOperationType = DbOperationType.DbotIns;
                           var modbbody = new ModelObjectDB();
                           result = modbbody.Save(ChStl);
                           ChsettlementDAL.p_update_Amount(BILLNO, enumValue.FEETYPE);


                           var headData = new ChfeeHexiao();
                           headData.GID = Guid.NewGuid().ToString();
                           headData.BILLNO = HEXIAOBILLNO;
                           headData.COMPANYID = Convert.ToString(Session["COMPANYID"]);
                           headData.DbOperationType = DbOperationType.DbotIns;
                           headData.CREATEUSER = CookieConfig.GetCookie_UserId(Request);
                           headData.CREATEUSERREF = Convert.ToString(Session["SHOWNAME"]);
                           headData.CREATETIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                           headData.BILLDATE = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                           headData.CUSTOMERNAME = enumValue.CUSTNAME;
                           headData.REMARK = "冲抵自动核销";

                           var modb = new ModelObjectDB();
                           result = modb.Save(headData);


                           T_ALL_DA T_ALL_DA = new EntityDA.T_ALL_DA();
                           var blUpSQL = " update ch_fee set ISINVOICE=1 where GID IN (SELECT GID FROM CH_FEE F WHERE " + feesql + ")";
                           bool bl = T_ALL_DA.GetExecuteSqlCommand(blUpSQL);


                       }
                       else {
                           var jsonRespose2 = new JsonResponse { Success = false, Message = "生成核销出错" };
                           return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose2) };                       
                       
                       }

                   
                   }

               }
           
           }

           var jsonRespose = new JsonResponse { Success = true, Message = "查询成功", Data ="" };
           return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }
        #endregion


        #region 生成接口凭证
        public ContentResult onAddCwVouchersJK(string strGids, string dataDiv, string jsonBody)
        {
            DBResult result2 = ChHexiaoDAL.GetIsVoucherJK(strGids);
            if (!result2.Success)
            {
                var jsonRespose2 = new JsonResponse { Success = result2.Success, Message = result2.Message, Data = "" };
                return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose2) };
            }
            //
            var headData = JsonConvert.Deserialize<MsCwVouchersGl3>(dataDiv);

            List<MsCwVouchersGl4> bodyList = new List<MsCwVouchersGl4>();
            if (jsonBody != null)
            {
                bodyList = JsonConvert.Deserialize<List<MsCwVouchersGl4>>(jsonBody);
            }
            DBResult result = ChHexiaoDAL.onAddCwVouchersJK(strGids, headData,bodyList, CookieConfig.GetCookie_UserId(Request), Convert.ToString(Session["SHOWNAME"]), Convert.ToString(Session["COMPANYID"]));
            //
            string sGids = "'" + strGids.Trim().Replace(",", "','") + "'";
            T_ALL_DA T_ALL_DA = new EntityDA.T_ALL_DA();
            string sVOUNO = T_ALL_DA.GetStrSQL("VOUNO", "select top 1 VOUNO from ch_fee_settlement where gid in (" + sGids + ")");
            //
            var jsonRespose = new JsonResponse { Success = result.Success, Message = result.Message, Data = sVOUNO };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }

        public ContentResult GetIsVoucherJK(string strGids)
        {
            DBResult result = ChHexiaoDAL.GetIsVoucherJK(strGids);
            var jsonRespose = new JsonResponse{ Success = result.Success, Message = result.Message, Data = "" };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }

        public ContentResult GetCodeCurrencyListJK(string sVOUDATE)
        {
            var dataList = ChHexiaoDAL.GetCodeCurrencyListJK(sVOUDATE, Convert.ToString(Session["COMPANYID"]));
            var json = JsonConvert.Serialize(new { Success = true, Message = "查询成功", totalCount = dataList.Count, data = dataList.ToList() });
            return new ContentResult() { Content = json };
        }

        /// <summary>
        /// 是否自动弹出结算接口凭证
        /// </summary>
        /// <returns></returns>
        public ContentResult onIsSettlementsopenJK()
        {
            DBResult result = ChHexiaoDAL.onIsSettlementsopenJK();
            var jsonRespose = new JsonResponse{ Success = result.Success, Message = result.Message, Data = "" };
            return new ContentResult() { Content = JsonConvert.Serialize(jsonRespose) };
        }
        #endregion
    }
}