/* =============================================
-- Author:		<Author,,zhangkun>
-- Create date: <Create Date,,20200618>
-- Description:	<Description,,订单相关操作）>
-- ============================================*/

using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
using System.Data;
using System.IRepositories;
using System.Linq;
using System.Linq.Expressions;
using System.Model;
using System.Repositories;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Utility.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.Order
{
    [Route("api/[controller]")]
    public class KFOrderController : BaseController
    {
        private readonly IBus_OrderDetailRepository bus_OrderDetailRepository;
        private readonly IBus_OrderRepository bus_OrderRepository;
        private readonly ISys_MarketingRepository bus_MarketingRepository;
        private readonly IBus_ProductRepository bus_productRepository;
        private readonly ICus_VipInfoRepository cus_vip_infoRepository;
        private readonly IBus_StockLogRepository bus_StockLogRepository;
        private readonly ICus_ScoreSetRepository cus_score_setRepository;
        private readonly IBus_OrderMoneyRepository busOrderMoneyRepository;
        private readonly IConfiguration config;
        private readonly OrderFunctionController busOrderFunctionController;
        private readonly IBus_AfterSaleRepository busAfterSaleRepository;
        public KFOrderController(IBus_AfterSaleRepository _busAfterSaleRepository, IBus_OrderMoneyRepository _busOrderMoneyRepository, OrderFunctionController _OrderFunctionController, ICus_ScoreSetRepository _cus_score_setRepository, IBus_StockLogRepository _bus_StockLogRepository, IBus_OrderRepository _bus_OrderRepository, IBus_OrderDetailRepository _bus_OrderDetailRepository, ISys_MarketingRepository _bus_MarketingRepository, IBus_ProductRepository _productRepository, ICus_VipInfoRepository _cus_vip_infoRepository, IConfiguration _configuration)
        {
            busAfterSaleRepository = _busAfterSaleRepository;
            bus_OrderDetailRepository = _bus_OrderDetailRepository;
            bus_OrderRepository = _bus_OrderRepository;
            bus_MarketingRepository = _bus_MarketingRepository;
            bus_productRepository = _productRepository;
            cus_vip_infoRepository = _cus_vip_infoRepository;
            bus_StockLogRepository = _bus_StockLogRepository;
            cus_score_setRepository = _cus_score_setRepository;
            busOrderMoneyRepository = _busOrderMoneyRepository;
            config = _configuration;
            busOrderFunctionController = _OrderFunctionController;
        }






        /// <summary>
        /// 导入订单跟踪
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("importordertrack")]
        public async Task<IActionResult> ImportOrderTrack()
        {
            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");

            //将数据导入数据库
            int headrow = 0;
            NPOIHelper npoi = new NPOIHelper();
            DataTable dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            if (dtExcel.Rows.Count > 0)
            {
                Dictionary<string, string> dirList = new Dictionary<string, string>();
                string[] arrykey = config["Import:ordertrackkey"].ToString().ToLower().Split(',');
                string[] arryvalue = config["Import:ordertracktvalue"].ToString().Split(',');
                for (int i = 0; i < arrykey.Length; i++)
                {
                    dirList.Add(arrykey[i], arryvalue[i]);
                }
                IList<T_Bus_Order> IModels = ModelConvertHelper<T_Bus_Order>.ConvertToModelByColumns(dtExcel, dirList);
                List<T_Bus_Order> models = ModelConvertHelper<T_Bus_Order>.ConvertIListToList(IModels);


                if (models != null && models.Count > 0)
                {
                    int num = models.Count;

                    //foreach (T_Bus_Order model in models)
                    //{
                    //状态如果需要更新 下面加F_State  如果需要验证之前状态，这里要循环查询
                    //}

                    if (await bus_OrderRepository.UpdateListToColumns(models, s => new { s.F_TrackingNo, s.F_Status }))
                    {
                        return Success("成功");
                    }
                }
                else
                {
                    return Success("内容为空");
                }

            }
            return Success("请选择要导入的文件");
        }



        /// <summary>
        /// 订单二审 审完 走发货
        /// </summary>
        /// <param name="orderid">订单号</param>
        /// <param name="state">订单状态 -1无效 0暂存 1提交  2KF退回  3通过 4KG退回 5已分拣 6已发货</param>
        /// <param name="remark">客服备注</param>
        /// <returns></returns>
        [HttpPost("/api/order/checkorderbykf")]
        public async Task<IActionResult> CheckOrderKF(string orderid, int state, string remark)
        {
            try
            {
                //状态变化  积分变化  处理时间人变化  库存变化  备注
                T_Cus_VipInfo modelvip = new T_Cus_VipInfo();
                #region 验证参数 必填项  

                if (string.IsNullOrEmpty(orderid))
                    return Error("请输入订单号");
                if (state <= 0)
                    return Error("请选择操作类型");

                #endregion


                T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == orderid && q.F_State == 1);

                if (modelOrder == null)
                {
                    return Error("只有提交订单才可以审核");
                }
                if (state == 3)
                {
                    if (string.IsNullOrEmpty(modelOrder.F_Stock))
                    {
                        return Error("出货仓不能为空");
                    }
                    if (string.IsNullOrEmpty(modelOrder.F_Express))
                    {
                        return Error("快递不能为空");
                    }
                    if (string.IsNullOrEmpty(modelOrder.F_AddPhone))
                    {
                        return Error("收件人电话不能为空");
                    }
                    if (string.IsNullOrEmpty(modelOrder.F_AddTown))
                    {
                        return Error("收件人地址不能为空");
                    }
                    if (string.IsNullOrEmpty(modelOrder.F_Address))
                    {
                        return Error("收件人详细地址不能为空");
                    }
                }
                modelOrder.F_CheckTime = DateTime.Now;
                modelOrder.F_CheckUser = UserLogin.UserId.ObjToInt();
                modelOrder.F_CheckUserName = UserLogin.UserName;
                if (!string.IsNullOrEmpty(remark))
                    modelOrder.F_CheckRemark = remark;
                if (state == 2)
                {
                    string strStock = await busOrderFunctionController.ChangeStockOne(modelOrder, 2, null);
                    modelOrder.F_State = 2;
                    modelOrder.F_Score = 0.00M;
                }
                else if (state == 3)
                {
                    #region 判断积分
                    bool blScore = false;
                    if (modelOrder.F_UseScore > 0)
                    {
                        //退回积分  查询批次号核算积分是否已经解冻
                        modelvip = await cus_vip_infoRepository.GetSingle(q => q.F_ID == modelOrder.F_VipId);
                        modelvip.F_Score = modelvip.F_Score + modelOrder.F_UseScore;
                        if (await cus_vip_infoRepository.Update(modelvip))
                        {
                            //log 或者解冻积分
                            blScore = true;
                        }
                    }
                    else
                    {
                        blScore = true;
                    }
                    if (!blScore)
                    {
                        return Error("积分处理失败");
                    }
                    #endregion
                    //库存不做处理
                    modelOrder.F_State = 3;
                }
                if (await bus_OrderRepository.Update(modelOrder))
                    return Success("订单成功审核！");
                return Error("订单审核失败,请汇报技术支持！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }


        /// <summary>
        /// 获取订单分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/order/getorderlistbykfpage")]
        public async Task<IActionResult> GetOrderListByKFPage(OrderInput input,int PayState=0)
        {

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选


           // conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.GreaterThan, FieldValue = "0" });

            //状态
            if (input.F_State > -2)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = input.F_State.ToString() });
            }
            //根据角色展示列表
            if (UserLogin.RoleCode == "XS")
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId });
            }
            else if (UserLogin.RoleCode == "KF")
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.And , new ConditionalModel() { FieldName = "F_CheckUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = "1" })
                     }
                });
                // conModels.Add(new ConditionalModel() { FieldName = "", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId });
            }
            else if (UserLogin.RoleCode == "KG")
            {
                //conModels.Add(new ConditionalModel() { FieldName = "F_StockUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId });

                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.And , new ConditionalModel() { FieldName = "F_StockUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_SendUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = "3" })
                     }
                });
            }
            if (!string.IsNullOrEmpty(input.F_ADFrom))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ADFrom", ConditionalType = ConditionalType.Equal, FieldValue = input.F_ADFrom });
            }
            if (!string.IsNullOrEmpty(input.F_Type))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Type", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Type });
            }
            if (!string.IsNullOrEmpty(input.F_Id))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Id", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Id });
            }
            if (!string.IsNullOrEmpty(input.F_Customer))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Customer", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Customer });
            }
            if (!string.IsNullOrEmpty(input.F_CustomerPhone))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_CustomerPhone", ConditionalType = ConditionalType.Equal, FieldValue = input.F_CustomerPhone });
            }
            if (!string.IsNullOrEmpty(input.F_TrackingNo))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_TrackingNo", ConditionalType = ConditionalType.Equal, FieldValue = input.F_TrackingNo });
            }
            if (!string.IsNullOrEmpty(input.F_AddProvince))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddProvince", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddProvince });
            }
            if (!string.IsNullOrEmpty(input.F_AddCity))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddCity", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddCity });
            }
            if (!string.IsNullOrEmpty(input.F_AddArea))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddArea", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddArea });
            }
            if (!string.IsNullOrEmpty(input.F_AddTown))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTown", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddTown });
            }
            if (!string.IsNullOrEmpty(input.F_Express))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Express", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Express });
            }
            if (!string.IsNullOrEmpty(input.F_PayType))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_PayType", ConditionalType = ConditionalType.Equal, FieldValue = input.F_PayType });
            }
            if (!string.IsNullOrEmpty(input.F_Stock))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Stock", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Stock });
            }
            if (input.F_PayState > -1)
            {
                if (PayState>0)
                {
                    conModels.Add(new ConditionalModel() { FieldName = "F_PayState", ConditionalType = ConditionalType.Equal, FieldValue = input.F_PayState.ToString() });
                }
                else
                {
                    if (input.F_PayState == 1 || input.F_PayState == 3)
                    {
                        conModels.Add(new ConditionalCollections()
                        {
                            ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.And , new ConditionalModel() { FieldName = "F_PayState", ConditionalType = ConditionalType.Equal, FieldValue = "1" }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_PayState", ConditionalType = ConditionalType.Equal, FieldValue ="3" })
                     }
                        });
                    }
                    else
                    {
                        conModels.Add(new ConditionalModel() { FieldName = "F_PayState", ConditionalType = ConditionalType.Equal, FieldValue = input.F_PayState.ToString() });
                    }
                }
              
            }
            if (input.SearchEndTime != null)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThan, FieldValue = input.SearchEndTime.GetValueOrDefault().ToString("yyyy-MM-dd 23:59:59") });
            }
            if (input.SearchStartTime != null)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThan, FieldValue = input.SearchStartTime.GetValueOrDefault().ToString("yyyy-MM-dd 00:00:01") });
            }
            if (input.F_IsExpress > -1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_IsExpress", ConditionalType = ConditionalType.Equal, FieldValue = input.F_IsExpress.ToString() });
            }




            #endregion
            RefAsync<int> recordCount = 0;
            PageData<T_Bus_Order> list = await bus_OrderRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = input.pageindex, PageSize = input.pagesize, PageCount = recordCount }, " F_AddTime DESC");
            PageData<OrderInput> returnobj = new PageData<OrderInput>() { Totals = list.Totals };
            List<OrderInput> returnlist = new List<OrderInput>();
            foreach (T_Bus_Order t in list.Rows)
            {
                OrderInput m = new OrderInput();
                ModelConvertHelper<OrderInput, T_Bus_Order>.ModeToModel(m, t);

                List<OrderDetailInput> orderDetailInputs = new List<OrderDetailInput>();
                #region 遍历订单商品
                List<T_Bus_OrderDetail> orderDetails = await bus_OrderDetailRepository.GetListALL(q => q.F_OrderId == t.F_Id);
                if (orderDetails != null)
                {
                    foreach (T_Bus_OrderDetail t1 in orderDetails)
                    {
                        OrderDetailInput m1 = new OrderDetailInput();
                        ModelConvertHelper<OrderDetailInput, T_Bus_OrderDetail>.ModeToModel(m1, t1);
                        orderDetailInputs.Add(m1);
                    }
                }
                #endregion
                m.OrderDetailList = orderDetailInputs;

                returnlist.Add(m);
            }
            returnobj.Rows = returnlist;

            return Success("成功", returnobj);


        }

        /// <summary>
        /// 修改订单 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/order/editorderkf")]
        public async Task<IActionResult> EditOrderKF([FromBody]OrderInput input)
        {
            T_Cus_VipInfo modelvip = new T_Cus_VipInfo();
            #region 验证参数 必填项  

            if (string.IsNullOrEmpty(input.F_ADFrom))
                return Error("请输入选择广告来源");
            if (string.IsNullOrEmpty(input.F_Type))
                return Error("请输入选择订单类型");
            if (string.IsNullOrEmpty(input.F_Id))
                return Error("请输入订单编号");
            if (string.IsNullOrEmpty(input.F_Customer))
                return Error("请输入客户姓名");
            if (string.IsNullOrEmpty(input.F_CustomerPhone))
                return Error("请输入客户电话");
            #endregion


            T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == input.F_Id);
            if (modelOrder == null)
            {
                return Error("此订单号不存在");
            }
            //保存 审退回 仓退回
            if (!(new int[] { 1, 3 ,4}.Contains(modelOrder.F_State)))
            {
                return Error("此状态订单不允许修改，先撤回订单");
            }

                #region 数据绑定
                //必填
                modelOrder.F_ADFrom = input.F_ADFrom;
            modelOrder.F_Type = input.F_Type;
            modelOrder.F_Id = input.F_Id;


            if (input.F_CustomerType > 0)
            { modelOrder.F_CustomerType = input.F_CustomerType; }
            if (!string.IsNullOrEmpty(input.F_CustomerTel))
            { modelOrder.F_CustomerTel = input.F_CustomerTel; }
            //选填 快递属性
            if (!string.IsNullOrEmpty(input.F_TrackingNo))
            { modelOrder.F_TrackingNo = input.F_TrackingNo; }
            if (!string.IsNullOrEmpty(input.F_Addressee))
            { modelOrder.F_Addressee = input.F_Addressee; }
            if (!string.IsNullOrEmpty(input.F_AddPhone))
            { modelOrder.F_AddPhone = input.F_AddPhone; }

            if (!string.IsNullOrEmpty(input.F_AddProvince))
            { modelOrder.F_AddProvince = input.F_AddProvince; }
            if (!string.IsNullOrEmpty(input.F_AddCity))
            { modelOrder.F_AddCity = input.F_AddCity; }
            if (!string.IsNullOrEmpty(input.F_AddArea))
            { modelOrder.F_AddArea = input.F_AddArea; }
            if (!string.IsNullOrEmpty(input.F_AddTown))
            { modelOrder.F_AddTown = input.F_AddTown; }

            if (!string.IsNullOrEmpty(input.F_AddDes))
            { modelOrder.F_AddDes = input.F_AddDes; }
            if (!string.IsNullOrEmpty(input.F_Address))
            { modelOrder.F_Address = input.F_Address; }
            if (!string.IsNullOrEmpty(input.F_PostalCode))
            { modelOrder.F_PostalCode = input.F_PostalCode; }
            if (!string.IsNullOrEmpty(input.F_Express))
            { modelOrder.F_Express = input.F_Express; }
            if (!string.IsNullOrEmpty(input.F_Remark))
            { modelOrder.F_Remark = input.F_Remark; }
            if (!string.IsNullOrEmpty(input.F_PayType))
            { modelOrder.F_PayType = input.F_PayType; }

            if (input.F_VipId > 0)
            { modelOrder.F_VipId = input.F_VipId; }
            if (!string.IsNullOrEmpty(modelOrder.F_Express))
                modelOrder.F_IsExpress = 1;
            //选填 关联属性



            modelOrder.F_ExpressFee = input.F_ExpressFee;
            modelOrder.F_State = input.F_State;
            modelOrder.F_Status = 0;


            //必须属性 系统生成
            modelOrder.F_CheckTime = DateTime.Now;
            modelOrder.F_CheckUser = UserLogin.UserId.ObjToInt();
            modelOrder.F_CheckUserName = UserLogin.UserName;

            if (string.IsNullOrEmpty(modelOrder.F_Express))
            {
                return Error("快递不能为空");
            }
            if (string.IsNullOrEmpty(modelOrder.F_AddPhone))
            {
                return Error("收件人电话不能为空");
            }
            if (string.IsNullOrEmpty(modelOrder.F_AddTown))
            {
                return Error("收件人地址不能为空");
            }
            if (string.IsNullOrEmpty(modelOrder.F_Address))
            {
                return Error("收件人详细地址不能为空");
            }
            #endregion

            modelOrder.F_ShouldPrice = modelOrder.F_TotlePrice - modelOrder.F_ActivityMoney + modelOrder.F_ExpressFee + modelOrder.F_MergeMoney;

            if (await bus_OrderRepository.Update(modelOrder))
            {
                return Success("成功");
            }

            return Error("订单添加失败,请重试！");


        }


        /// <summary>
        /// 订单打标签 
        /// </summary>
        /// <param name="orderids"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        [HttpPost("addordertag")]
        public async Task<IActionResult> AddOrderTag(string orderids, string tags)
        {

            #region 验证参数 必填项  

            if (string.IsNullOrEmpty(orderids))
                return Error("请选择订单号");
            if (string.IsNullOrEmpty(tags))
                return Error("请选择标签");
            #endregion
            string[] ids = orderids.Split(',');
            if (await bus_OrderRepository.Update(s => new T_Bus_Order() { F_Tag = tags }, q => ids.Contains(q.F_Id)))
            {
                return Success("成功");
            }

            return Error("失败,请重试！");

        }


        /// <summary>
        /// 更新物流状态 
        /// </summary>
        /// <param name="orderids"></param>
        /// <param name="status">0 未发出 1未签收2签收3改代收4拒收</param>
        /// <returns></returns>
        [HttpPost("updatestatus")]
        public async Task<IActionResult> UpdateStatus(string orderids, int status)
        {

            #region 验证参数 必填项  

            if (string.IsNullOrEmpty(orderids))
                return Error("请选择订单号");
            if (status == 0)
                return Error("请选择状态");
            #endregion
            string[] ids = orderids.Split(',');
            if (await bus_OrderRepository.Update(s => new T_Bus_Order() { F_Status = status }, q => ids.Contains(q.F_Id)))
            {
                return Success("成功");
            }

            return Error("失败,请重试！");

        }


        [HttpPost("updateexpress")]
        public async Task<IActionResult> UpdateExpress(string orderids, string express)
        {

            #region 验证参数 必填项  

            if (string.IsNullOrEmpty(orderids))
                return Error("请选择订单号");
            if (string.IsNullOrEmpty(express))
                return Error("请选择快递");
            #endregion
            //更新所选订单的快递，并标记为客服已分配快递
            string[] ids = orderids.Split(',');
            if (await bus_OrderRepository.Update(s => new T_Bus_Order() { F_Express = express, F_IsExpress = 1 }, q => ids.Contains(q.F_Id)))
            {
                return Success("成功");
            }

            return Error("失败,请重试！");

        }


        [HttpPost("checkordermoney")]
        public async Task<IActionResult> CheckOrderMoney(OrderMoneyInput input)
        {
            try
            {
                #region 验证参数 必填项  

                if (string.IsNullOrEmpty(input.F_Id))
                    return Error("请选择条目");

                if (string.IsNullOrEmpty(input.F_RemarkKF))
                    input.F_RemarkKF = "";
                if (string.IsNullOrEmpty(input.F_RemarkXS))
                    input.F_RemarkXS = "";
                if (input.F_Money <= 0)
                    return Error("请输入金额");

                #endregion

                T_Bus_OrderMoney modelOrderMoeny = await busOrderMoneyRepository.GetSingle(q => q.F_Id == input.F_Id);

                modelOrderMoeny.F_CheckUserId = UserLogin.UserId.ObjToInt();
                modelOrderMoeny.F_CheckUserName = UserLogin.UserName;
                modelOrderMoeny.F_Money = modelOrderMoeny.F_Money;
                modelOrderMoeny.F_State = input.F_State;
                modelOrderMoeny.F_RemarkKF = input.F_RemarkKF;
                if (modelOrderMoeny.F_State == 1)
                {
                    T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == modelOrderMoeny.F_OrderId);
                    if (modelOrder.F_PayState == 1 || modelOrder.F_PayState == 3)
                    {
                        return Error("此单已结算！");
                    }
                    modelOrder.F_RealPrice = modelOrder.F_RealPrice + modelOrderMoeny.F_Money;
                    if (modelOrder.F_PayState == 0)
                    {
                        if (modelOrder.F_ShouldPrice <= modelOrder.F_RealPrice)
                        {
                            //0待回款1已支付 2待退款3已退款
                            modelOrder.F_PayState = 1;
                        }
                    }
                    else if (modelOrder.F_PayState == 2)
                    {
                        if (modelOrder.F_ShouldPrice <= modelOrder.F_RealPrice)
                        {
                            //0待回款1已支付 2待退款3已退款
                            modelOrder.F_PayState = 3;
                        }
                    }
                    await bus_OrderRepository.UpdateListToColumns(new List<T_Bus_Order>() { modelOrder }, s => new { s.F_PayState, s.F_RealPrice });
                }

                if (await busOrderMoneyRepository.Update(modelOrderMoeny))
                    return Success("成功！");
                return Error("失败！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }

        [HttpPost("ordermoney")]
        public async Task<IActionResult> OrderMoney(OrderMoneyInput input)
        {
            try
            {
                #region 验证参数 必填项  

                if (string.IsNullOrEmpty(input.F_OrderId))
                    return Error("请输入订单号");
                if (string.IsNullOrEmpty(input.F_PayUser))
                    return Error("请输入打款人");
                if (string.IsNullOrEmpty(input.F_PayType))
                    return Error("请输入打款方式");
                if (string.IsNullOrEmpty(input.F_RemarkKF))
                    input.F_RemarkKF = "";
                if (string.IsNullOrEmpty(input.F_RemarkXS))
                    input.F_RemarkXS = "";
                if (input.F_PayTime == null)
                    return Error("请输入打款时间");
                if (input.F_Money >= 0)
                    return Error("退款金额只能为负数");

                #endregion

                T_Bus_OrderMoney modelOrderMoeny = new T_Bus_OrderMoney();
                ModelConvertHelper<T_Bus_OrderMoney, OrderMoneyInput>.ModeToModelDefault(modelOrderMoeny, input);
                modelOrderMoeny.F_AddUserId = UserLogin.UserId.ObjToInt();
                modelOrderMoeny.F_UserName = UserLogin.UserName;
                modelOrderMoeny.F_Money = input.F_Money;
                modelOrderMoeny.F_MoneyBak = modelOrderMoeny.F_Money;
                modelOrderMoeny.F_State = 1;
                modelOrderMoeny.F_Id = Guid.NewGuid().ToString().Replace("-", "");

                T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == modelOrderMoeny.F_OrderId);
                if (modelOrder.F_PayState == 1 || modelOrder.F_PayState == 3)
                {
                    return Error("此单已结算！");
                }
                modelOrder.F_RealPrice = modelOrder.F_RealPrice + modelOrderMoeny.F_Money;
                if (modelOrder.F_PayState == 2)
                {
                    if (modelOrder.F_ShouldPrice >= modelOrder.F_RealPrice)
                    {
                        //0待回款1已支付 2待退款3已退款
                        modelOrder.F_PayState = 3;
                    }
                }
                await bus_OrderRepository.UpdateListToColumns(new List<T_Bus_Order>() { modelOrder }, s => new { s.F_PayState, s.F_RealPrice });

                if (await busOrderMoneyRepository.AddReturnCount(modelOrderMoeny))
                    return Success("成功！");
                return Error("失败！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }


        /// <summary>
        /// 根据分页获取售后列表 待退款   退货 仓库确认收到货    补差额 不需要仓库确认
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getaftersalebypage")]
        public async Task<IActionResult> GetAfterSaleByPage(AfterSaleInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_AfterSale, bool>> eq = a => a.F_Money < 0 && a.F_CheckStateSH == 1 && ((a.F_CheckStateKG == 1 && (a.F_Type == 2 || a.F_Type == 3)) || a.F_Type == 6);


            if (!string.IsNullOrEmpty(input.F_Id))
            {
                eq = eq.And(a => a.F_Id == input.F_Id);
            }
            if (input.F_State > 0)
            {
                eq = eq.And(a => a.F_State == input.F_State);
            }
            if (input.F_Type > 0)
            {
                eq = eq.And(a => a.F_Type == input.F_Type);
            }
            if (!string.IsNullOrEmpty(input.F_ReturnType))
            {
                eq = eq.And(a => a.F_ReturnType == input.F_ReturnType);
            }

            #endregion
            RefAsync<int> count = 0;
            PageData<T_Bus_AfterSale> list = await busAfterSaleRepository.GetListByPage(eq, new MyPageModel() { PageIndex = input.pageindex, PageSize = input.pagesize, PageCount = count }, " F_AddTime DESC");

            return Success("成功", list);

        }


        /// <summary>
        /// 更新售后退款状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatestate")]
        public async Task<IActionResult> UpdateState(AfterSaleInput input)
        {
            try
            {
                #region 验证参数 必填项  

                if (string.IsNullOrEmpty(input.F_Id))
                    return Error("请选择售后单");
                if (input.F_CheckTimeXS == null)
                    return Error("请选择退款时间");
                if (input.F_State == 0)
                    return Error("更新状态不正确");

                #endregion

                T_Bus_AfterSale modelAfterSale = await busAfterSaleRepository.GetSingle(q => q.F_Id == input.F_Id);

                if (modelAfterSale.F_State != 0)
                { return Error("此售后状态不支持退款"); }
                if (modelAfterSale.F_Type != 2 && modelAfterSale.F_Type != 3 && modelAfterSale.F_Type != 6)
                {
                    return Error("售后类型不支持退款");
                }
                //1收到货（根据状态自动创建订单）2货物不符3未收到货
                if ((modelAfterSale.F_Type == 2 || modelAfterSale.F_Type == 3) && modelAfterSale.F_CheckStateKG != 1)
                {
                    return Error("仓库暂未确认收到退货");
                }
                if (modelAfterSale.F_Money >= 0)
                {
                    return Error("此金额不需要退款");
                }
                modelAfterSale.F_CheckTimeXS = input.F_CheckTimeXS;
                modelAfterSale.F_State = 1;

                if (await busAfterSaleRepository.Update(modelAfterSale))
                {

                    return Success("成功");

                }
                return Error("失败,请重试！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }



        /// <summary>
        /// 根据订单获取相应支付记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getordermoney")]
        public async Task<IActionResult> GetOrderMoneyList(OrderMoneyInput input)
        {
            if (string.IsNullOrEmpty(input.F_OrderId))
            {
                return Error("请输入订单号");
            }

            #region  拼接条件

            Expression<Func<T_Bus_OrderMoney, bool>> eq = a => a.F_OrderId== input.F_OrderId;


            #endregion

            List<T_Bus_OrderMoney> list = await busOrderMoneyRepository.GetListALL(eq,o=>o.F_AddTime,OrderByType.Asc);

            return Success("成功", list);

        }



    }
}