/* =============================================
-- Author:		<Author,,zhangkun>
-- Create date: <Create Date,,20200713>
-- 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;
using Utility;

namespace TVShoppingCallCenter_ZLJ.Controllers.Order
{
    [Route("api/[controller]")]
    public class AfterSaleController : BaseController
    {
        private readonly IBus_OrderDetailRepository bus_OrderDetailRepository;
        private readonly IBus_OrderRepository bus_OrderRepository;
        private readonly OrderFunctionController busOrderFunctionController;
        private readonly IBus_ProductRepository bus_productRepository;
        private readonly ICus_VipInfoRepository cus_vip_infoRepository;
        private readonly IBus_OrderMergeRepository busOrderMergeRepository;
        private readonly ICus_ScoreSetRepository cus_score_setRepository;
        private readonly IBus_AfterSaleRepository busAfterSaleRepository;
        public AfterSaleController(OrderFunctionController _OrderFunctionController, ICus_ScoreSetRepository _cus_score_setRepository, IBus_OrderMergeRepository _busOrderMergeRepository, IBus_OrderRepository _bus_OrderRepository, IBus_OrderDetailRepository _bus_OrderDetailRepository, IBus_ProductRepository _productRepository, ICus_VipInfoRepository _cus_vip_infoRepository, IBus_AfterSaleRepository _busAfterSaleRepository)
        {
            bus_OrderDetailRepository = _bus_OrderDetailRepository;
            bus_OrderRepository = _bus_OrderRepository;
            busOrderFunctionController = _OrderFunctionController;
            bus_productRepository = _productRepository;
            cus_vip_infoRepository = _cus_vip_infoRepository;
            busOrderMergeRepository = _busOrderMergeRepository;
            cus_score_setRepository = _cus_score_setRepository;
            busAfterSaleRepository = _busAfterSaleRepository;
        }

        #region 销售操作

        ///// <summary>
        ///// 销售申请售后
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost("addaftersalexs")]
        //public async Task<IActionResult> AddAfterSaleXS(AfterSaleInput input)
        //{
        //    try
        //    {
        //        #region 验证参数 必填项  

        //        if (string.IsNullOrEmpty(input.F_OrderId))
        //            return Error("请选择订单");

        //        if (input.F_Type <= 0)
        //            return Error("申请类型不符合售后");

        //        #endregion

        //        #region 验证逻辑
        //        if (input.F_Type == 1)
        //        { }
        //        else if (input.F_Type == 2)
        //        { }
        //        else if (input.F_Type == 3)
        //        { }
        //        else if (input.F_Type == 4)
        //        { }
        //        #endregion
        //        T_Bus_Order modeOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == input.F_OrderId);
        //        if (modeOrder == null)
        //        {
        //            return Error("订单不存在");
        //        }
        //        else if (modeOrder.F_Status == -1)
        //        {
        //            //物流状态0 未发出 1物流运送中2签收3改代收4拒收
        //            return Error("状态不符合售后");
        //        }
        //        T_Bus_AfterSale modelAfterSale = new T_Bus_AfterSale();
        //        modelAfterSale.F_AddTime = DateTime.Now;
        //        modelAfterSale.F_CheckTimeXS = DateTime.Now;
        //        modelAfterSale.F_CheckStateXS = input.F_CheckStateXS;
        //        modelAfterSale.F_CheckUserXS = UserLogin.UserId.ObjToInt();
        //        modelAfterSale.F_CheckUserNameXS = UserLogin.UserName;

        //        modelAfterSale.F_DetailList = input.F_DetailList;
        //        modelAfterSale.F_Type = input.F_Type;
        //        modelAfterSale.F_Money = input.F_Money;
        //        modelAfterSale.F_OrderId = input.F_OrderId;
        //        modelAfterSale.F_AboutOrderId = "";
        //        modelAfterSale.F_Id = Guid.NewGuid().ToString().Replace("-", "");
        //        //modelAfterSale.F_OurTrackingNo = input.F_OurTrackingNo;
        //        //modelAfterSale.F_OurTrackDes = input.F_OurTrackDes;
        //        //modelAfterSale.F_TrackingNo = input.F_TrackingNo;
        //        //modelAfterSale.F_TrackDes = input.F_TrackDes;
        //        if (!string.IsNullOrEmpty(input.F_Remark))
        //            modelAfterSale.F_Remark = " 销售：" + input.F_Remark;

        //        if (await busAfterSaleRepository.AddReturnCount(modelAfterSale))
        //        {
        //            if (input.F_State == 0)
        //                return Success("售后申请已保存");
        //            else if (input.F_State == 1)
        //            { return Success("售后申请已提交审核"); }
        //        }
        //        return Error("申请失败,请重试！");
        //    }
        //    catch (Exception ex)
        //    { return Error(ex.Message); }


        //}

        ///// <summary>
        ///// 销售编辑售后
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost("editaftersalexs")]
        //public async Task<IActionResult> EditAfterSaleXS(AfterSaleInput input)
        //{
        //    try
        //    {
        //        #region 验证参数 必填项  

        //        if (string.IsNullOrEmpty(input.F_Id))
        //            return Error("参数缺失Id");

        //        if (string.IsNullOrEmpty(input.F_OrderId))
        //            return Error("请选择订单");

        //        if (input.F_Type <= 0)
        //            return Error("申请类型不符合售后");

        //        #endregion

        //        #region 验证逻辑
        //        if (input.F_Type == 1)
        //        { }
        //        else if (input.F_Type == 2)
        //        { }
        //        else if (input.F_Type == 3)
        //        { }
        //        else if (input.F_Type == 4)
        //        { }
        //        #endregion

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

        //        if (modelAfterSale.F_CheckStateSH == 1 && modelAfterSale.F_CheckStateXS == 1)
        //        {
        //            return Error("双审核通过不能编辑");
        //        }
        //        modelAfterSale.F_CheckTimeXS = DateTime.Now;
        //        modelAfterSale.F_CheckStateXS = input.F_CheckStateXS;
        //        modelAfterSale.F_CheckUserXS = UserLogin.UserId.ObjToInt();
        //        modelAfterSale.F_CheckUserNameXS = UserLogin.UserName;

        //        modelAfterSale.F_DetailList = input.F_DetailList;
        //        modelAfterSale.F_Type = input.F_Type;
        //        modelAfterSale.F_Money = input.F_Money;

        //        modelAfterSale.F_CheckStateSH = 0;//需要售后重新审核
        //        //modelAfterSale.F_OurTrackingNo = input.F_OurTrackingNo;
        //        //modelAfterSale.F_OurTrackDes = input.F_OurTrackDes;
        //        //modelAfterSale.F_TrackingNo = input.F_TrackingNo;
        //        //modelAfterSale.F_TrackDes = input.F_TrackDes;
        //        if (!string.IsNullOrEmpty(input.F_Remark))
        //            modelAfterSale.F_Remark = modelAfterSale.F_Remark + "\\r\\n 销售：" + input.F_Remark;



        //        if (await busAfterSaleRepository.AddReturnCount(modelAfterSale))
        //        {
        //            if (input.F_State == 0)
        //                return Success("售后申请已保存");
        //            else if (input.F_State == 1)
        //            { return Success("售后申请已提交审核"); }
        //        }
        //        return Error("申请失败,请重试！");
        //    }
        //    catch (Exception ex)
        //    { return Error(ex.Message); }


        //}

        ///// <summary>
        ///// 销售删除
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost("deleteaftersalexs")]
        //public async Task<IActionResult> DeleteAfterSaleXS(string ids)
        //{
        //    try
        //    {
        //        if (string.IsNullOrEmpty(ids))
        //        {
        //            return Error("参数缺失：" + ids);
        //        }
        //        string[] idlist = ids.Split(',');

        //        if (await busAfterSaleRepository.Delete(q => idlist.Contains(q.F_Id) && new[] { 0, 2 }.Contains(q.F_CheckStateXS)))
        //        {
        //            return Success("删除成功/已审核通过不能删除");
        //        }
        //        return Error("删除失败,请重试！");
        //    }
        //    catch (Exception ex)
        //    { return Error(ex.Message); }
        //}

        ///// <summary>
        ///// 根据分页获取列表
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost("getaftersalebypagexs")]
        //public async Task<IActionResult> GetAfterSaleByPageXS(AfterSaleInput input)
        //{

        //    #region  拼接条件

        //    Expression<Func<T_Bus_AfterSale, bool>> eq = a => a.F_CheckUserXS == UserLogin.UserId.ObjToInt();


        //    if (input.F_CheckStateXS > -1)
        //    {
        //        eq = eq.And(a => a.F_CheckStateXS == input.F_CheckStateXS);
        //    }
        //    if (input.F_CheckStateSH > -1)
        //    {
        //        eq = eq.And(a => a.F_CheckStateSH == input.F_CheckStateSH);
        //    }
        //    if (input.F_Type > -1)
        //    {
        //        eq = eq.And(a => a.F_Type == input.F_Type);
        //    }
        //    if (!string.IsNullOrEmpty(input.F_Id))
        //    {
        //        eq = eq.And(a => a.F_Id == input.F_Id);
        //    }
        //    if (input.F_State >= -1)
        //    {
        //        eq = eq.And(a => a.F_State == input.F_State);
        //    }

        //    #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);

        //}

        #endregion

        /// <summary>
        /// 获取订单分页列表（所有订单都可查，与来电相关）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getorderlistbypage")]
        public async Task<IActionResult> GetOrderListByPage(OrderInput input)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选

            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = "6" });
            

            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 (input.F_PayState > -1)
            {
                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") });
            }




            #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);

        }

        #region 售后操作

        /// <summary>
        /// 添加售后
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addaftersalesh")]
        public async Task<IActionResult> AddAfterSaleSH(AfterSaleInput input)
        {
            try
            {
                bool dgs = false;//代改收标识

                #region 验证参数 必填项  

                if (string.IsNullOrEmpty(input.F_OrderId))
                    return Error("请选择订单");

                if (input.F_Type <= 0)
                    return Error("请选择售后类型");

                if (string.IsNullOrEmpty(input.F_ReturnType))
                    return Error("请选择售后原因类型");

                #endregion


                T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == input.F_OrderId);
                if (modelOrder == null)
                {
                    return Error("订单不存在");
                }
                else if (!(modelOrder.F_Status == 3|| modelOrder.F_Status == 2||(modelOrder.F_Status <2&& input.F_ReturnType== "改代收")))
                {
                    //物流状态0 未发出 1物流运送中2签收3改代收4拒收
                    return Error("状态不符合售后");
                }
                if(input.F_ReturnType == "改代收"&& input.F_Type!=3)
                {
                    return Error("改代收只能选择部分退货");
                }
                T_Bus_AfterSale modelAfterSale = new T_Bus_AfterSale();


                #region 退回商品展示 更新售后流程的退货商品
                List<T_Bus_OrderDetail> modelOldDetailList = new List<T_Bus_OrderDetail>();
                if (input.F_CheckStateSH == 2)
                {
                    //从0开始，相当于添加  目前不会出现
                }
                else
                {
                    if (!string.IsNullOrEmpty(input.F_OldDetailList))
                    {

                        foreach (string product in input.F_OldDetailList.Split('|'))
                        {
                            string productid = product.Split(',')[0];
                            int count = product.Split(',')[1].ObjToInt();
                            T_Bus_OrderDetail modelDetail = await bus_OrderDetailRepository.GetSingle(q => q.F_OrderId == modelOrder.F_Id && q.F_ProductId == productid);
                            if (count > (modelDetail.F_Count - modelDetail.F_State))
                            {
                                return Error("此商品部分已参加售后:" + modelDetail.F_ProductName);
                            }
                            modelDetail.F_State = modelDetail.F_State + count;
                            modelOldDetailList.Add(modelDetail);
                        }

                    }
                }
                #endregion

                if (input.F_ReturnType.Contains("仓库错发") || input.F_ReturnType.Contains("仓库漏发"))
                {
                    modelAfterSale.F_AboutUserId = modelOrder.F_SendUser;
                    modelAfterSale.F_AboutName = modelOrder.F_SendUserName;
                }
                else
                {
                    modelAfterSale.F_AboutUserId = modelOrder.F_AddUser;
                    modelAfterSale.F_AboutName = modelOrder.F_AddUserName;
                }
                if (!string.IsNullOrEmpty(input.F_Customer))
                { modelAfterSale.F_CustomerPhone = input.F_CustomerPhone; }
                else
                { modelAfterSale.F_CustomerPhone = modelOrder.F_CustomerPhone; }

                if (!string.IsNullOrEmpty(input.F_Customer))
                { modelAfterSale.F_Customer = input.F_Customer; }
                else
                { modelAfterSale.F_Customer = modelOrder.F_Customer; }
                 
                if (!string.IsNullOrEmpty(input.F_ReturnDes))
                { modelAfterSale.F_ReturnDes = input.F_ReturnDes; }
                if (!string.IsNullOrEmpty(input.F_ReturnType))
                { modelAfterSale.F_ReturnType = input.F_ReturnType; }

                if (!string.IsNullOrEmpty(input.F_ProductStatus))
                { modelAfterSale.F_ProductStatus = input.F_ProductStatus; }
                if (!string.IsNullOrEmpty(input.F_DetailList))
                { modelAfterSale.F_DetailList = input.F_DetailList; }
                if (!string.IsNullOrEmpty(input.F_OldDetailList))
                { modelAfterSale.F_OldDetailList = input.F_OldDetailList; }

                modelAfterSale.F_AddTime = DateTime.Now;
                modelAfterSale.F_CheckTimeSH = DateTime.Now;
                modelAfterSale.F_CheckStateSH = input.F_CheckStateSH;
                modelAfterSale.F_CheckUserSH = UserLogin.UserId.ObjToInt();
                modelAfterSale.F_CheckUserNameSH = UserLogin.UserName;

                modelAfterSale.F_CheckUserXS = modelOrder.F_AddUser;


                modelAfterSale.F_Type = input.F_Type;
                modelAfterSale.F_Money = input.F_Money;

                modelAfterSale.F_OrderId = input.F_OrderId;
                modelAfterSale.F_AboutOrderId = "";
                modelAfterSale.F_Id = Guid.NewGuid().ToString().Replace("-", "");

                modelAfterSale.F_TrackingNo = input.F_TrackingNo;
                modelAfterSale.F_TrackDes = input.F_TrackDes;
                if (!string.IsNullOrEmpty(input.F_Remark))
                    modelAfterSale.F_Remark = " 售后：" + input.F_Remark;

                if (new int[] { 1, 2, 3, 4 }.Contains(input.F_Type))
                {
                    //客户需要发货  
                    if (modelOldDetailList == null || modelOldDetailList.Count == 0)
                    {
                        //但是客户没发货
                        return Error("请选择客户退回商品");
                    }
                }
                if (new int[] { 1,5, 4 }.Contains(input.F_Type))
                {
                    //我们需要发货  
                    if (string.IsNullOrEmpty(modelAfterSale.F_DetailList))
                    {
                        //但是我们没发
                        return Error("请选择新/补发商品");
                    }

                }


                if (input.F_Type == 4)
                {
                    if (input.F_CheckStateSH == 1)
                    {
                        modelAfterSale.F_AboutOrderId = "BJ" + UserLogin.UserCode + "T" + DateTimeConvert.ToTimetag(DateTime.Now);
                        string addResult = await AddOrder(modelAfterSale, modelOrder);
                        if (addResult != "1")
                        {
                            return Error("订单无法创建:" + addResult);
                        }
                    }
                }
                else if (input.F_Type == 2 )
                {

                }
                else if (input.F_Type == 3)
                {
                    //售后提交
                    if (input.F_CheckStateSH == 1)
                    {
                        //如果是改代收
                        if (input.F_ReturnType == "代改收")
                        {
                            dgs = true;
                            decimal tempShouldPrice = modelOrder.F_ShouldPrice;
                            modelOrder.F_ShouldPrice = modelOrder.F_ShouldPrice + input.F_Money;
                            modelOrder.F_Tag += ",代改收";
                            modelOrder.F_Tag = modelOrder.F_Tag.Trim(',');
                            if (tempShouldPrice > 0)
                            {
                                if (modelOrder.F_ShouldPrice == modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 1;
                                }
                                if (modelOrder.F_ShouldPrice > modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 0;
                                }
                                if (modelOrder.F_ShouldPrice < modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 2;
                                }
                            }
                            else
                            {
                                if (modelOrder.F_ShouldPrice == modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 3;
                                }
                                if (modelOrder.F_ShouldPrice > modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 0;
                                }
                                if (modelOrder.F_ShouldPrice < modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 2;
                                }
                            }

                            modelAfterSale.F_Money = 0;
                        }
                    }
                }
                else if (input.F_Type == 1)
                {

                }

                if (modelOldDetailList != null && modelOldDetailList.Count > 0&& new int[] { 1, 2, 3, 4 }.Contains(input.F_Type))
                {
                    //批量更新售后的数量状态
                    await bus_OrderDetailRepository.UpdateListToColumns(modelOldDetailList,s=> new{ s.F_State});
                }
                 
                if (await busAfterSaleRepository.AddReturnCount(modelAfterSale))
                {

                    if (input.F_CheckStateSH == 1)
                    {
                        string dgsstr = "";
                        if (dgs)
                        {
                            if (await bus_OrderRepository.UpdateListToColumns(new List<T_Bus_Order>() { modelOrder }, s => new { s.F_PayState, s.F_ShouldPrice, s.F_Tag }))
                            {
                                dgsstr = ":改代收修改成功";
                            }
                            else { dgsstr = ":改代收修改失败，请记录手动修改原订单 应付金额值/实际支付"; }
                        }
                        return Success("售后已提交"+ dgsstr); 
                    }
                    else
                    {
                        return Success("售后已保存"); 
                    }
                }
                return Error("申请失败,请重试！");
            }
            catch (Exception ex)
            { return Error(ex.Message + "===" + ex.StackTrace); }

        }

        /// <summary>
        /// 售后编辑售后
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("editaftersalesh")]
        public async Task<IActionResult> EditAfterSaleSH(AfterSaleInput input)
        {
            try
            {
                bool dgs = false;//代改收标识
                #region 验证参数 必填项  

                if (string.IsNullOrEmpty(input.F_OrderId))
                    return Error("请选择订单");
                if (string.IsNullOrEmpty(input.F_Id))
                    return Error("请选择售后单");
                if (input.F_Type <= 0)
                    return Error("申请类型不符合售后");

                #endregion


                T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == input.F_OrderId);
                if (modelOrder == null)
                {
                    return Error("订单不存在");
                }
                else if (!(modelOrder.F_Status == 3 || modelOrder.F_Status == 2 || (modelOrder.F_Status < 2 && input.F_ReturnType == "改代收")))
                {
                    //物流状态0 未发出 1物流运送中2签收3改代收4拒收
                    return Error("状态不符合售后");
                }
                if (input.F_ReturnType == "改代收" && input.F_Type != 3)
                {
                    return Error("改代收只能选择部分退货");
                }

                T_Bus_AfterSale modelAfterSale = await busAfterSaleRepository.GetSingle(q => q.F_Id == input.F_Id);
                if (modelAfterSale.F_CheckStateSH == 1)
                {
                    return Error("审核通过的不能操作");
                }
                if (input.F_ReturnType.Contains("仓库错发") || input.F_ReturnType.Contains("仓库漏发"))
                {
                    modelAfterSale.F_AboutUserId = modelOrder.F_SendUser;
                    modelAfterSale.F_AboutName = modelOrder.F_SendUserName;
                }
                else
                {
                    modelAfterSale.F_AboutUserId = modelOrder.F_AddUser;
                    modelAfterSale.F_AboutName = modelOrder.F_AddUserName;
                }

                if (!string.IsNullOrEmpty(input.F_Customer))
                { modelAfterSale.F_CustomerPhone = input.F_CustomerPhone; }
                else
                { modelAfterSale.F_CustomerPhone = modelOrder.F_CustomerPhone; }

                if (!string.IsNullOrEmpty(input.F_Customer))
                { modelAfterSale.F_Customer = input.F_Customer; }
                else
                { modelAfterSale.F_Customer = modelOrder.F_Customer; }

                if (!string.IsNullOrEmpty(input.F_ReturnDes))
                { modelAfterSale.F_ReturnDes = input.F_ReturnDes; }
                if (!string.IsNullOrEmpty(input.F_ReturnType))
                { modelAfterSale.F_ReturnType = input.F_ReturnType; }

                if (!string.IsNullOrEmpty(input.F_ProductStatus))
                { modelAfterSale.F_ProductStatus = input.F_ProductStatus; }
                if (!string.IsNullOrEmpty(input.F_DetailList))
                { modelAfterSale.F_DetailList = input.F_DetailList; }



                if (!string.IsNullOrEmpty(input.F_TrackingNo))
                { modelAfterSale.F_TrackingNo = input.F_TrackingNo; }
                if (!string.IsNullOrEmpty(input.F_TrackDes))
                { modelAfterSale.F_TrackDes = input.F_TrackDes; }

                if (!string.IsNullOrEmpty(input.F_Remark))
                    modelAfterSale.F_Remark = " 售后：" + input.F_Remark;


                List<T_Bus_OrderDetail> modelOldDetailList = new List<T_Bus_OrderDetail>();

                #region 退回商品展示 更新售后流程的退货商品
                if (modelAfterSale.F_CheckStateSH == 2)
                { 
                    //从0开始，相当于添加
                    if (input.F_CheckStateSH == 2)
                    { }
                    else
                    {                       
                        if (!string.IsNullOrEmpty(input.F_OldDetailList))
                        {

                            foreach (string product in input.F_OldDetailList.Split('|'))
                            {
                                string productid = product.Split(',')[0];
                                int count = product.Split(',')[1].ObjToInt();
                                T_Bus_OrderDetail modelDetail = await bus_OrderDetailRepository.GetSingle(q => q.F_OrderId == modelOrder.F_Id && q.F_ProductId == productid);
                                if (count > (modelDetail.F_Count - modelDetail.F_State))
                                {
                                    return Error("此商品部分已参加售后:" + modelDetail.F_ProductName);
                                }
                                modelDetail.F_State = modelDetail.F_State+ count;
                                modelOldDetailList.Add(modelDetail);
                            }

                        }
                    }
                }
                else
                {
                    if (input.F_CheckStateSH == 2)
                    {
                        //解锁之前的
                        if (string.IsNullOrEmpty(modelAfterSale.F_OldDetailList))
                        {

                            foreach (string product in modelAfterSale.F_OldDetailList.Split('|'))
                            {
                                string productid = product.Split(',')[0];
                                int count = product.Split(',')[1].ObjToInt();
                                T_Bus_OrderDetail modelDetail = await bus_OrderDetailRepository.GetSingle(q => q.F_OrderId == modelOrder.F_Id && q.F_ProductId == productid);
                                modelDetail.F_State = modelDetail.F_State- count;
                                modelOldDetailList.Add(modelDetail);
                            }

                        }

                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(input.F_OldDetailList))
                        {

                            foreach (string product in input.F_OldDetailList.Split('|'))
                            {
                                string productid = product.Split(',')[0];
                                int count = product.Split(',')[1].ObjToInt();
                                T_Bus_OrderDetail modelDetail = await bus_OrderDetailRepository.GetSingle(q => q.F_OrderId == modelOrder.F_Id && q.F_ProductId == productid);
                                foreach (string productold in modelAfterSale.F_OldDetailList.Split('|'))
                                {
                                    string productidold = product.Split(',')[0];
                                    if (productidold == productid)
                                    {
                                        int countold = product.Split(',')[1].ObjToInt();
                                        count = count - countold;
                                    }
                                }
                                if (count > (modelDetail.F_Count - modelDetail.F_State))
                                {
                                    return Error("此商品部分已参加售后:" + modelDetail.F_ProductName);
                                }
                                modelDetail.F_State = modelDetail.F_State + count;
                                modelOldDetailList.Add(modelDetail);
                            }


                        }
                    }
                }

                #endregion
                if (!string.IsNullOrEmpty(input.F_OldDetailList))
                { modelAfterSale.F_OldDetailList = input.F_OldDetailList; }

                modelAfterSale.F_CheckTimeSH = DateTime.Now;
                modelAfterSale.F_CheckStateSH = input.F_CheckStateSH;
                modelAfterSale.F_CheckUserSH = UserLogin.UserId.ObjToInt();
                modelAfterSale.F_CheckUserNameSH = UserLogin.UserName;

                modelAfterSale.F_CheckUserXS = modelOrder.F_AddUser;

                modelAfterSale.F_Type = input.F_Type;
                modelAfterSale.F_Money = input.F_Money;

                modelAfterSale.F_OrderId = input.F_OrderId;
                if (new int[] { 1, 2, 3, 4 }.Contains(input.F_Type))
                {
                    //客户需要发货  
                    if (modelOldDetailList == null || modelOldDetailList.Count == 0)
                    {
                        //但是客户没发货
                        return Error("请选择客户退回商品");
                    }
                }
                if (new int[] { 1, 5, 4 }.Contains(input.F_Type))
                {
                    //我们需要发货  
                    if (string.IsNullOrEmpty(modelAfterSale.F_DetailList))
                    {
                        //但是我们没发
                        return Error("请选择新/补发商品");
                    }

                }
                #region 不通售后类型的处理
                if (modelAfterSale.F_Type == 4)
                {
                    if (modelAfterSale.F_CheckStateSH == 1)
                    {
                        modelAfterSale.F_AboutOrderId = "BJ" + UserLogin.UserCode + "T" + DateTimeConvert.ToTimetag(DateTime.Now);
                        string addResult = await AddOrder(modelAfterSale, modelOrder);
                        if (addResult != "1")
                        {
                            return Error("订单无法创建:" + addResult);
                        }
                    }
                }
                else if (input.F_Type == 2)
                {

                }
                else if (input.F_Type == 3)
                {
                    //售后提交
                    if (input.F_CheckStateSH == 1)
                    {
                        //如果是改代收
                        if (input.F_ReturnType == "代改收")
                        {
                            dgs = true;
                            decimal tempShouldPrice = modelOrder.F_ShouldPrice;
                            modelOrder.F_ShouldPrice = modelOrder.F_ShouldPrice + input.F_Money;
                            modelOrder.F_Tag += ",代改收";
                            modelOrder.F_Tag = modelOrder.F_Tag.Trim(',');
                            if (tempShouldPrice > 0)
                            {
                                if (modelOrder.F_ShouldPrice == modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 1;
                                }
                                if (modelOrder.F_ShouldPrice > modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 0;
                                }
                                if (modelOrder.F_ShouldPrice < modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 2;
                                }
                            }
                            else
                            {
                                if (modelOrder.F_ShouldPrice == modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 3;
                                }
                                if (modelOrder.F_ShouldPrice > modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 0;
                                }
                                if (modelOrder.F_ShouldPrice < modelOrder.F_RealPrice)
                                {
                                    modelOrder.F_PayState = 2;
                                }
                            }

                            modelAfterSale.F_Money = 0;
                        }
                    }
                }
                else if (input.F_Type == 1)
                {

                }
                #endregion
                if (modelOldDetailList != null && modelOldDetailList.Count > 0 && new int[] { 1, 2, 3, 4 }.Contains(input.F_Type))
                {
                    //批量更新状态 数量
                    await bus_OrderDetailRepository.UpdateListToColumns(modelOldDetailList, s => new { s.F_State });
                }
                if (await busAfterSaleRepository.Update(modelAfterSale))
                {
                    if (input.F_CheckStateSH == 0)
                        return Success("售后已保存");
                    else if (input.F_CheckStateSH == 1)
                    {
                        string dgsstr = "";
                        if (dgs)
                        {
                            if (await bus_OrderRepository.UpdateListToColumns(new List<T_Bus_Order>() { modelOrder }, s => new { s.F_PayState, s.F_ShouldPrice, s.F_Tag }))
                            {
                                dgsstr = ":改代收修改成功";
                            }
                            else { dgsstr = ":改代收修改失败，请记录手动修改原订单 应付金额值/实际支付"; }
                        }
                        return Success("售后已提交" + dgsstr);
                    }

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


        }

        /// <summary>
        /// 售后删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("deleteaftersalesh")]
        public async Task<IActionResult> DeleteAfterSaleSH(string ids)
        {
            try
            {
                if (string.IsNullOrEmpty(ids))
                {
                    return Error("参数缺失：" + ids);
                }
                string[] idlist = ids.Split(',');
                //TODO 删除售后 暂时还未还原之前状态 暂时不能删除

                foreach (string id in idlist)
                {

               T_Bus_AfterSale modelAfterSale   =  await busAfterSaleRepository.GetSingle(q => q.F_Id == id);
                    if (modelAfterSale.F_CheckStateSH > 1)
                    {
                        return Error("此售后的状态不允许删除:" + modelAfterSale.F_Id);
                    }
                    if (new int[] { 1, 2, 3, 4 }.Contains(modelAfterSale.F_Type))
                    {
                        if (!string.IsNullOrEmpty(modelAfterSale.F_OldDetailList))
                        {
                            List<T_Bus_OrderDetail> modelOldDetailList = new List<T_Bus_OrderDetail>();
                            foreach (string product in modelAfterSale.F_OldDetailList.Split('|'))
                            {
                                string productid = product.Split(',')[0];
                                int count = product.Split(',')[1].ObjToInt();
                                T_Bus_OrderDetail modelDetail = await bus_OrderDetailRepository.GetSingle(q => q.F_OrderId == modelAfterSale.F_OrderId && q.F_ProductId == productid);

                                if (count > modelDetail.F_State)
                                {
                                    modelDetail.F_State = 0;
                                }
                                else {
                                    modelDetail.F_State = modelDetail.F_State - count;
                                }

                                modelOldDetailList.Add(modelDetail);
                            }
                            if(!await bus_OrderDetailRepository.UpdateListToColumns(modelOldDetailList,s=>new { s.F_State}))
                            {
                                return Error("更新售后商品数量失败，请手工操作："+ modelAfterSale.F_Id);
                            }
                        }
                    }

                    if (await busAfterSaleRepository.Update(s => new T_Bus_AfterSale { F_State = -1 }, q => q.F_Id == id && q.F_CheckStateSH != 1))
                    {
                        return Success("删除成功");
                    }
                }


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

        /// <summary>
        /// 根据分页获取列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getaftersalebypagesh")]
        public async Task<IActionResult> GetAfterSaleByPageSH(AfterSaleInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_AfterSale, bool>> eq = a => a.F_CheckUserSH == UserLogin.UserId.ObjToInt()&&a.F_State>-1;


            //if (input.F_CheckStateXS > -2)
            //{
            //    eq = eq.And(a => a.F_CheckStateXS == input.F_CheckStateXS);
            //}
            if (input.F_CheckStateSH > -2)
            {
                eq = eq.And(a => a.F_CheckStateSH == input.F_CheckStateSH);
            }
            if (input.F_State > -2)
            {
                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_Id))
            {
                eq = eq.And(a => a.F_Id == input.F_Id);            }

            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("getshdetail")]
        public async Task<IActionResult> GetSHDetail(AfterSaleInput input)
        {
            if (string.IsNullOrEmpty(input.F_Id))
            {
                return Error("请选择售后单");
            }

            T_Bus_AfterSale model = await busAfterSaleRepository.GetSingle(a =>a.F_Id== input.F_Id&& a.F_CheckUserSH == UserLogin.UserId.ObjToInt() && a.F_State > -1);
            if (model != null)
            {
                if (!string.IsNullOrEmpty(model.F_DetailList))
                {
                    string[] F_DetailList = model.F_DetailList.Split("|");
                    model.F_DetailList = "";
                    foreach (string a1 in F_DetailList)
                    {
                        string[] F_Detail= a1.Split(",");
                        string productid = F_Detail[0];
                        string count = F_Detail[1];
                      var modelProduct =await bus_productRepository.GetSingle(q => q.F_ProductId == productid);
                        if (modelProduct != null)
                        {
                            model.F_DetailList = $"{model.F_DetailList}|{productid},{count},{modelProduct.F_ProductName}";
                        }
                        else
                        {
                            model.F_DetailList = $"{model.F_DetailList}|{productid},{count},空货";
                        }
                    }
                }
                //if (!string.IsNullOrEmpty(model.F_OldDetailList))
                //{
                //    string[] F_OldDetailList = model.F_OldDetailList.Split("|");
                //    model.F_OldDetailList = "";
                //    foreach (string a1 in F_OldDetailList)
                //    {
                //        string[] F_OldDetail = a1.Split(",");
                //        string productid = F_OldDetail[0];
                //        string count = F_OldDetail[1];
                //        var modelProduct = await bus_productRepository.GetSingle(q => q.F_ProductId == productid);
                //        if (modelProduct != null)
                //        {
                //            model.F_OldDetailList = $"{model.F_DetailList}|{productid},{count},{modelProduct.F_ProductName}";
                //        }
                //        else
                //        {
                //            model.F_OldDetailList = $"{model.F_DetailList}|{productid},{count},空货";
                //        }
                //    }
                //}
            }
            return Success("成功", model);

        }


        /// <summary>
        /// 获取订单分页列表 售后
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getorderlistbyshpage")]
        public async Task<IActionResult> GetSHOrderListByPage(OrderInput input)
        {

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


            conModels.Add(new ConditionalModel() { FieldName = "F_Type", ConditionalType = ConditionalType.Equal, FieldValue = "售后订单" });

            //状态
            if (input.F_State > -2)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = input.F_State.ToString() });
            }
            //根据角色展示列表
            if (UserLogin.RoleCode == "SH")
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId });
            }
            else if (UserLogin.RoleCode == "KF" && input.F_State != 1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_CheckUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId });
            }
            else if (UserLogin.RoleCode == "KG" && input.F_State != 3)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_StockUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId });
                //OR  conModels.Add(new ConditionalModel() { FieldName = "F_SendUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId });
            }
            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)
            {
                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") });
            }




            #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("editorder")]
        public async Task<IActionResult> EditOrder([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[] { 0, 2 }.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;

            modelOrder.F_Customer = input.F_Customer;
            modelOrder.F_CustomerPhone = input.F_CustomerPhone;
            //选填 快递属性
            modelOrder.F_TrackingNo = input.F_TrackingNo;
            modelOrder.F_Addressee = input.F_Addressee;
            modelOrder.F_AddPhone = input.F_AddPhone;
            modelOrder.F_AddProvince = input.F_AddProvince;
            modelOrder.F_AddCity = input.F_AddCity;
            modelOrder.F_AddArea = input.F_AddArea;
            modelOrder.F_AddTown = input.F_AddTown;
            modelOrder.F_AddDes = input.F_AddDes;
            modelOrder.F_Address = input.F_Address;
            modelOrder.F_PostalCode = input.F_PostalCode;
            modelOrder.F_Express = input.F_Express;

            modelOrder.F_PayType = input.F_PayType;
            modelOrder.F_Stock = input.F_Stock;
            modelOrder.F_Remark = input.F_Remark;

            modelOrder.F_RealPrice = input.F_RealPrice;
            modelOrder.F_UseScore = input.F_UseScore;
            //选填 关联属性
            modelOrder.F_VipId = input.F_VipId;



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


            //必须属性 系统生成
            modelOrder.F_AddTime = DateTime.Now;
            modelOrder.F_AddUser = UserLogin.UserId.ObjToInt();
            modelOrder.F_AddUserName = UserLogin.UserName;

            #endregion
            List<T_Bus_OrderDetail> modelDetailList = new List<T_Bus_OrderDetail>();
            foreach (var  product in input.OrderDetailList)
            {
                int Count = product.ObjToInt();
                T_Bus_Product modelProduct = await bus_productRepository.GetSingle(b => b.F_ProductId == product .F_ProductId );
                if (modelProduct == null)
                    return Error ( "商品不存在:" + product.F_ProductId);
                T_Bus_OrderDetail modelDetail = new T_Bus_OrderDetail();
                modelDetail.F_ProductName = modelProduct.F_ProductName;
                modelDetail.F_ProductId = modelProduct.F_ProductId;
                modelDetail.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                modelDetail.F_OrderId = modelOrder.F_Id;
                modelDetail.F_Count = Count;
                modelDetail.F_Price = modelProduct.F_MemberPrice;

                modelDetail.F_DealPrice = modelProduct.F_MemberPrice;
                modelDetail.F_Remark = input.F_Remark;


                modelDetail.F_Sort = modelDetail.F_Sort;
                modelDetail.F_AddTime = DateTime.Now;

                modelDetail.F_AddUser = modelOrder.F_AddUser;
                modelDetail.F_AddUserName = modelOrder.F_AddUserName;
                modelDetail.F_TotlePrice = modelDetail.F_DealPrice * modelDetail.F_Count;
                modelDetail.F_Activity = 0;
                modelDetailList.Add(modelDetail);
                
            }
            //直接提交  锁库存

            #region 提交 更改状态   库存  积分


            if (input.F_State == 1)
            {
                if (string.IsNullOrEmpty(input.F_Stock))
                {
                    return Error("请选择货仓");
                }
                modelOrder.F_FlowNum = DateTime.Now.ToString("yyMMddHHmmss") + "U" + UserLogin.UserId + "R" + new Random().Next(9);
                string strStock = await busOrderFunctionController.ChangeStockOne(modelOrder, 1, modelDetailList);
                if (strStock != "1")
                { return Error(strStock); }
                modelOrder.F_SubmitTime = DateTime.Now;

            }
            #endregion



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

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


        }


        #endregion

        #region 仓库操作

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

                if (string.IsNullOrEmpty(input.F_Id))
                    return Error("请选择售后单");

                #endregion

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

                T_Bus_Order modeOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == modelAfterSale.F_OrderId);
                if (modeOrder == null)
                {
                    return Error("订单不存在");
                }

                if (modelAfterSale.F_CheckStateKG == 1 || modelAfterSale.F_CheckStateKG == 2)
                {
                    //1收到货（根据状态自动创建订单）2货物不符3未收到货
                    return Error("不能重复审核提交");
                }
                modelAfterSale.F_CheckStateKG = input.F_CheckStateKG;

                modelAfterSale.F_CheckTimeKG = DateTime.Now;
                modelAfterSale.F_CheckUserKG = UserLogin.UserId.ObjToInt();
                modelAfterSale.F_CheckUserNameKG = UserLogin.UserName;
                modelAfterSale.F_CheckUserXS = modeOrder.F_AddUser;
                List<T_Bus_OrderDetail> modelOldDetailList = new List<T_Bus_OrderDetail>();

                //1收到货（根据状态自动创建订单）2货物不符3未收到货
                if (modelAfterSale.F_CheckStateKG == 1)
                {

                    if (modelAfterSale.F_Type == 4)
                    {

                        modelAfterSale.F_State = 1;

                    }
                    else if (modelAfterSale.F_Type == 2 || modelAfterSale.F_Type == 3)
                    {

                    }
                    else if (modelAfterSale.F_Type == 1)
                    {
                        modelAfterSale.F_AboutOrderId = "BJ" + UserLogin.UserCode + "T" + DateTimeConvert.ToTimetag(DateTime.Now);
                        string addResult = await AddOrder(modelAfterSale, modeOrder);
                        if (addResult != "1")
                        {
                            return Error("订单无法创建:" + addResult);
                        }
                        modelAfterSale.F_State = 1;
                    }
                }
                else if (modelAfterSale.F_CheckStateKG == 2)
                {
                    //时间长自动作废
                    //如果没有对发货  货物不符则标记为无效
                    #region 更新用户快递商品
                    if (modelAfterSale.F_Type != 1)
                    {
                        if (string.IsNullOrEmpty(modelAfterSale.F_OldDetailList))
                        {
                            foreach (string product in modelAfterSale.F_DetailList.Split('|'))
                            {
                                string productid = product.Split(',')[0];
                                int count = product.Split(',')[1].ObjToInt();
                                T_Bus_OrderDetail modelDetail = await bus_OrderDetailRepository.GetSingle(q => q.F_OrderId == modeOrder.F_Id && q.F_ProductId == productid);

                                modelDetail.F_State = modelDetail.F_State - count;
                                modelOldDetailList.Add(modelDetail);
                            }
                        }
                    }
                    #endregion
                }
                else if (modelAfterSale.F_CheckStateKG == 3)
                {     //时间长自动作废
                    //如果没有对发货  未收到货则标记为无效
                }

                if (modelOldDetailList != null && modelOldDetailList.Count > 0)
                {
                    //批量更新状态 为已售后
                    await bus_OrderDetailRepository.UpdateList(modelOldDetailList);
                }

                if (await busAfterSaleRepository.Update(modelAfterSale))
                {
                    if (input.F_CheckStateSH == 0)
                        return Success("售后已保存");
                    else if (input.F_CheckStateSH == 1)
                    { return Success("售后已提交"); }
                }
                return Error("申请失败,请重试！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }



        /// <summary>
        /// 根据分页获取列表(库管)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getaftersalebypagekg")]
        public async Task<IActionResult> GetAfterSaleByPageKG(AfterSaleInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_AfterSale, bool>> eq = a => a.F_CheckStateSH == 1;
            eq = eq.And(a=>(a.F_CheckStateKG > 0 && a.F_CheckUserKG == UserLogin.UserId.ObjToInt()) || a.F_CheckStateKG == 0);
            if (input.F_CheckStateKG > -2)
            {
                eq = eq.And(a => a.F_CheckStateKG == input.F_CheckStateKG);              
            }
            if (input.F_Type > 0)
            {
                eq = eq.And(a => a.F_Type == input.F_Type);
            }
            if (!string.IsNullOrEmpty(input.F_Id))
            {
                eq = eq.And(a => a.F_Id == input.F_Id);
            }
            if (input.F_State > -2)
            {
                eq = eq.And(a => a.F_State == input.F_State);
            }

            #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);

        }

        #endregion

        #region 方法
        /// <summary>
        /// 仓库确认后创建订单  对发货直接创建订单
        /// </summary>
        /// <param name="newOrderlist">12,3|</param>
        /// <param name="OldModelOrder"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        private async Task<string> AddOrder(T_Bus_AfterSale ModelAfterSale, T_Bus_Order OldModelOrder)
        {
            try
            {
                string newOrderlist = ModelAfterSale.F_DetailList;
                T_Bus_Order modelOrder = OldModelOrder;
                #region 订单属性
                //必填

                modelOrder.F_Type = "售后订单";
                modelOrder.F_Id = ModelAfterSale.F_AboutOrderId;
                modelOrder.F_TrackingNo = "";

                //选填 快递属性

                modelOrder.F_ExpressFee = 0;
                //modelOrder.F_Stock = input.F_Stock;
                modelOrder.F_Remark = "售后订单";

                modelOrder.F_RealPrice = 0.00M;
                modelOrder.F_UseScore = 0.00M;
                //选填 关联属性

                modelOrder.F_State = 0;
                modelOrder.F_Status = 0;


                //必须属性 系统生成
                modelOrder.F_AddTime = DateTime.Now;
                modelOrder.F_AddUser = UserLogin.UserId.ObjToInt();
                modelOrder.F_AddUserName = UserLogin.UserName;
                modelOrder.F_Belong = OldModelOrder.F_Belong;
                modelOrder.F_BelongName = OldModelOrder.F_BelongName;
                #endregion

                //计算属性  商品计算


                decimal totle = 0.00M;

                List<T_Bus_OrderDetail> modelDetailList = new List<T_Bus_OrderDetail>();

                #region 订单详情列表核算
                if (!string.IsNullOrEmpty(newOrderlist))
                {
                    int n = 1;

                    #region 商品核算
                    foreach (string product in newOrderlist.Split('|'))
                    {
                        string productid = product.Split(',')[0];
                        int Count = product.Split(',')[1].ObjToInt();
                        T_Bus_Product modelProduct = await bus_productRepository.GetSingle(b => b.F_ProductId == productid);
                        if (modelProduct == null)
                            return "商品不存在:" + productid;
                        T_Bus_OrderDetail modelDetail = new T_Bus_OrderDetail();
                        modelDetail.F_ProductName = modelProduct.F_ProductName;
                        modelDetail.F_ProductId = modelProduct.F_ProductId;
                        modelDetail.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                        modelDetail.F_OrderId = modelOrder.F_Id;
                        modelDetail.F_Count = Count;
                        modelDetail.F_Price = modelProduct.F_MemberPrice;

                        modelDetail.F_DealPrice = modelProduct.F_MemberPrice;
                        modelDetail.F_Remark = "售后订单：";


                        modelDetail.F_Sort = n;
                        modelDetail.F_AddTime = DateTime.Now;

                        modelDetail.F_AddUser = modelOrder.F_AddUser;
                        modelDetail.F_AddUserName = modelOrder.F_AddUserName;
                        modelDetail.F_TotlePrice = modelDetail.F_DealPrice * modelDetail.F_Count;
                        modelDetail.F_Activity = 0;
                        modelDetailList.Add(modelDetail);
                        totle += modelDetail.F_TotlePrice;
                        n++;
                    }
                    #endregion

                    modelOrder.F_TotlePrice = totle;
                    modelOrder.F_ActivityMoney = 0.00M;
                    modelOrder.F_UseActivity = "";
                }
                else
                {
                    return "0";
                }
                #endregion




                #region 直接提交  锁库存log  锁积分log



                modelOrder.F_FlowNum = DateTime.Now.ToString("yyMMddHHmmss") + "U" + UserLogin.UserId + "R" + new Random().Next(9);
                string strStock = await busOrderFunctionController.ChangeStockOne(modelOrder, 1, modelDetailList);
                if (strStock != "1")
                { modelOrder.F_State = 0; }
                else
                { modelOrder.F_SubmitTime = DateTime.Now; }





                #endregion
                //计算结果  积分有规则            
                modelOrder.F_ShouldPrice = ModelAfterSale.F_Money;

                modelOrder.F_RealPrice = 0.00M;


                if (await bus_OrderRepository.AddReturnCount(modelOrder))
                {
                    if (await bus_OrderDetailRepository.AddMany(modelDetailList))
                        return "1";
                    else
                        return "订单添加失败,请重试！";
                }
                else
                {
                    return "订单添加失败,请重试！";
                }
            }
            catch (Exception ex)
            { return ex.Message; }
        }


        /// <summary>
        /// 获取未售后的订单详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getorderdetail")]
        public async Task<IActionResult> GetOrderDetail(string orderid)
        {
            if (string.IsNullOrEmpty(orderid))
                return Error("请输入订单号");

            List<T_Bus_OrderDetail> detaillist = await bus_OrderDetailRepository.GetListALL(q => q.F_OrderId == orderid, o => o.F_Sort, OrderByType.Asc);

            return Success("成功", detaillist);
        }
        #endregion


    }
}