/* =============================================
-- 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.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 OrderController : 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;

        public OrderController(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)
        {
            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;
            config = _configuration;
            busOrderFunctionController = _OrderFunctionController;
            busOrderMoneyRepository = _busOrderMoneyRepository;
        }


  

        /// <summary>
        /// 创建订单 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addorder")]
        public async Task<IActionResult> AddOrder([FromBody]OrderInput input)
        {
            try {
                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("请输入客户电话");
                if (input.F_Type=="售后订单")
                    return Error("售后订单只能根据售后单自动创建");
                #endregion


                int exist = await bus_OrderRepository.GetCount(q => q.F_Id == input.F_Id);
                if (exist > 0)
                {
                    return Error("此订单号已存在");
                }

                T_Bus_Order modelOrder = new T_Bus_Order();
                #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;

                if (input.F_RecommendId>0)
                {
                    modelOrder.F_RecommendId = input.F_RecommendId;
                    modelOrder.F_RecommendName = input.F_RecommendName;
                }
                if (input.F_CustomerType > 0)
                { modelOrder.F_CustomerType = input.F_CustomerType; }
                if (!string.IsNullOrEmpty(input.F_CustomerTel))
                { modelOrder.F_CustomerTel = input.F_CustomerTel; }
                //选填 快递属性
                 modelOrder.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 (input.F_Belong > 0)
                { 
                    modelOrder.F_Belong = input.F_Belong;
                    modelOrder.F_BelongName = input.F_BelongName;
                }
                else 
                { 
                    modelOrder.F_Belong = UserLogin.UserId.ObjToInt();
                    modelOrder.F_BelongName = UserLogin.UserName;
                }


                modelOrder.F_ExpressFee = input.F_ExpressFee;
                modelOrder.F_Stock = input.F_Stock;
                

                modelOrder.F_RealPrice = input.F_RealPrice;
                modelOrder.F_UseScore = input.F_UseScore;
                //选填 关联属性
                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

                if (input.F_State == 1)
                {
                    if (input.OrderDetailList != null && input.OrderDetailList.Count > 0)
                    { }
                    else
                    { return Error("请选择订购商品"); }
                        if (string.IsNullOrEmpty(input.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("收件人详细地址不能为空");
                    }
                }

                decimal totle = 0.00M;
                decimal ActivityMoney = 0.00M;
                string UseActivity = "";
                string UseActivity4 = ",";
                string UseActivity2 = ",";
                List<T_Bus_OrderDetail> modelDetailList = new List<T_Bus_OrderDetail>();

                #region 订单详情列表核算
                if (input.OrderDetailList != null && input.OrderDetailList.Count > 0)
                {
                    int n = 1;
                    int n2 = input.OrderDetailList.Count + 1;
                    #region 活动核算
                    if (input.UseActList != null && input.UseActList.Count > 0)
                    {
                        //遍历所有选中的活动
                        foreach (UseActInput act in input.UseActList)
                        {
                            UseActivity += act.id + ",";
                            //满赠
                            if (act.type == 1)
                            {
                                string[] productidlist = act.gift.Split(',');
                                foreach (string giftid in productidlist)
                                {
                                    T_Bus_Product m = await bus_productRepository.GetSingle(b => ("," + giftid + ",").Contains("," + b.F_ProductId + ",") && b.F_IsSale == 0);
                                    if (m != null)
                                    {
                                        T_Bus_OrderDetail modelDetail = new T_Bus_OrderDetail();
                                        modelDetail.F_ProductName = m.F_ProductName;
                                        modelDetail.F_ProductId = m.F_ProductId;
                                        modelDetail.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                                        modelDetail.F_OrderId = input.F_Id;
                                        modelDetail.F_Count = 1;
                                        modelDetail.F_Price = 0.00M;
                                        modelDetail.F_DealPrice = 0.00M;
                                        modelDetail.F_Sort = n2;
                                        modelDetail.F_Remark = "赠品-活动：" + act.id;
                                        modelDetail.F_AddUser = modelOrder.F_AddUser;
                                        modelDetail.F_AddUserName = modelOrder.F_AddUserName;
                                        modelDetail.F_TotlePrice = 0.00M;
                                        modelDetail.F_Activity = act.id;
                                        modelDetail.F_AddTime = DateTime.Now;
                                        modelDetailList.Add(modelDetail);
                                        n2++;
                                    }
                                }

                            }
                            //生日赠
                            else if (act.type == 2)
                            {
                                UseActivity2 += act.gift + ",";
                            }
                            //满减
                            else if (act.type == 3)
                            {
                                ActivityMoney += act.money;
                            }
                            else if (act.type == 4)
                            {
                                UseActivity4 += act.gift + ",";
                            }
                        }
                        UseActivity = UseActivity.Trim(',');
                    }
                    #endregion

                    #region 商品核算
                    foreach (OrderDetailInput m in input.OrderDetailList)
                    {
                        T_Bus_Product modelProduct = await bus_productRepository.GetSingle(b => b.F_ProductId == m.F_ProductId);
                        if (modelProduct == null)
                            return Error("商品不存在:" + m.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 = input.F_Id;
                        modelDetail.F_Count = m.F_Count;
                        modelDetail.F_Price = modelProduct.F_MemberPrice;
                        //参加活动特价
                        if (UseActivity4.Contains("," + modelProduct.F_ProductId + ","))
                            modelDetail.F_DealPrice = modelProduct.F_SpecialPrice;
                        else
                            modelDetail.F_DealPrice = modelProduct.F_MemberPrice;
                        //参加生日
                        if (UseActivity2.Contains("," + modelProduct.F_ProductId + ","))
                        {
                            modelDetail.F_DealPrice = 0.00M;
                            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;
                        if (modelProduct.F_Tag.IndexOf(".") > -1&& !string.IsNullOrEmpty(UseActivity))
                        {
                            string[] tagarry = modelProduct.F_Tag.Split(',');
                            string[] actlist = UseActivity.Split(',');
                            string tag = tagarry.First(a => a.StartsWith(".")).ToString();
                            T_Sys_Marketing modelactive = await bus_MarketingRepository.GetFirst(b => actlist.Contains(b.F_ID.ToString())&& b.F_EndTime >= DateTime.Now && b.F_StartTime <= DateTime.Now && b.F_IsDelete == 0 && ("," + b.F_Commodity + ",").Contains(("," + tag + ",")));


                            //此商品参加活动
                            if (modelactive != null)
                            {
                                modelDetail.F_Activity = modelactive.F_ID;
                            }
                        }
                        else { modelDetail.F_Activity = 0; }

                        totle += modelDetail.F_TotlePrice;
                        modelDetailList.Add(modelDetail);

                        n++;
                    }
                    #endregion

                    modelOrder.F_TotlePrice = totle;
                    modelOrder.F_ActivityMoney = ActivityMoney;
                    modelOrder.F_UseActivity = UseActivity;
                }
                else
                {
                    //不改变订单
                }
                #endregion

                //订单完成后也不计算积分
                modelOrder.F_Score = 0.00M;
                T_Cus_ScoreSet modelscore = await cus_score_setRepository.GetSingle(x => x.F_State == 1);
                if (modelscore == null)
                {
                    modelscore = new T_Cus_ScoreSet();
                    modelscore.F_Start = 0;
                    modelscore.F_StartDebit = 1;
                    modelscore.F_DebitPercent = 1000;
                }


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

                if (input.F_State == 1)
                {

                    if (modelscore.F_StartDebit == 1)
                    {
                        modelOrder.F_UseScore = 0;
                    }
                    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); }
                    if (modelscore.F_Start == 1)
                    {
                        //订单完成后计算积分
                        modelOrder.F_Score = -0.01M;
                    }

                    modelOrder.F_SubmitTime = DateTime.Now;
                }

                #endregion
                //计算结果  积分有规则            
                modelOrder.F_ShouldPrice = modelOrder.F_TotlePrice - ActivityMoney + modelOrder.F_ExpressFee- modelOrder.F_UseScore / modelscore.F_DebitPercent;


                    modelOrder.F_PayState = 0;
                



                if (await bus_OrderRepository.AddReturnCount(modelOrder))
                {
                    if (modelDetailList != null && modelDetailList.Count > 0)
                    {
                        if (await bus_OrderDetailRepository.AddMany(modelDetailList))
                            return Success("订单添加成功2");
                        else
                            return Error("订单添加失败,请重试！1");
                    }
                    return Success("订单添加成功1");
                }
                else
                {
                    return Error("订单添加失败,请重试！2");
                }
            }
            catch (Exception ex)
            { return Error(ex.Message); }
        }

        /// <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("请输入客户电话");
            if (input.F_Type == "售后订单")
                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_Customer = input.F_Customer;
            modelOrder.F_CustomerPhone = input.F_CustomerPhone;
            if (input.F_RecommendId > 0)
            {
                modelOrder.F_RecommendId = input.F_RecommendId;
                modelOrder.F_RecommendName = input.F_RecommendName;
            }
            if (input.F_CustomerType > 0)
            { modelOrder.F_CustomerType = input.F_CustomerType; }
            if (!string.IsNullOrEmpty(input.F_CustomerTel))
            { modelOrder.F_CustomerTel = input.F_CustomerTel; }
            //选填 快递属性
            modelOrder.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_Belong > 0)
            {
                modelOrder.F_Belong = input.F_Belong;
                modelOrder.F_BelongName = input.F_BelongName;
            }
            else
            {
                modelOrder.F_Belong = UserLogin.UserId.ObjToInt();
                modelOrder.F_BelongName = UserLogin.UserName;
            }

            modelOrder.F_ExpressFee = input.F_ExpressFee;
            modelOrder.F_Stock = input.F_Stock;

            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

            //计算属性  商品计算

            decimal totle = 0.00M;
            decimal ActivityMoney = 0.00M;
            string UseActivity = "";
            string UseActivity4 = ",";
            string UseActivity2 = ",";
            List<T_Bus_OrderDetail> modelDetailList = new List<T_Bus_OrderDetail>();

            if (input.OrderDetailList != null && input.OrderDetailList.Count > 0)
            {
                #region 核算活动

                int n2 = input.OrderDetailList.Count + 1;
                if (input.UseActList != null && input.UseActList.Count > 0)
                {
                    //遍历所有选中的活动
                    foreach (UseActInput act in input.UseActList)
                    {
                        UseActivity += act.id + ",";
                        //满赠
                        if (act.type == 1)
                        {
                            string[] productidlist = act.gift.Split(',');
                            foreach (string giftid in productidlist)
                            {
                                T_Bus_Product m = await bus_productRepository.GetSingle(b => ("," + giftid + ",").Contains("," + b.F_ProductId + ",") && b.F_IsSale == 0);
                                if (m != null)
                                {
                                    T_Bus_OrderDetail modelDetail = new T_Bus_OrderDetail();
                                    modelDetail.F_ProductName = m.F_ProductName;
                                    modelDetail.F_ProductId = m.F_ProductId;
                                    modelDetail.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                                    modelDetail.F_OrderId = input.F_Id;
                                    modelDetail.F_Count = 1;
                                    modelDetail.F_Price = 0.00M;
                                    modelDetail.F_DealPrice = 0.00M;
                                    modelDetail.F_Sort = n2;
                                    modelDetail.F_Remark = "赠品-活动：" + act.id;
                                    modelDetail.F_AddUser = modelOrder.F_AddUser;
                                    modelDetail.F_AddUserName = modelOrder.F_AddUserName;
                                    modelDetail.F_TotlePrice = 0.00M;
                                    modelDetail.F_Activity = act.id;
                                    modelDetail.F_AddTime = DateTime.Now.AddSeconds(30);
                                    modelDetailList.Add(modelDetail);
                                    n2++;
                                }
                            }

                        }
                        //生日赠
                        else if (act.type == 2)
                        {
                            UseActivity2 += act.gift + ",";
                        }
                        //满减
                        else if (act.type == 3)
                        {
                            ActivityMoney += act.money;
                        }
                        else if (act.type == 4)
                        {
                            UseActivity4 += act.gift + ",";
                        }
                    }
                    UseActivity = UseActivity.Trim(',');
                }

                #endregion

                #region  核算商品

                int n = 1;
                foreach (OrderDetailInput m in input.OrderDetailList)
                {
                    T_Bus_Product modelProduct = await bus_productRepository.GetSingle(b => b.F_ProductId == m.F_ProductId);
                    if (modelProduct == null) return Error("在售商品不存在");
                    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 = input.F_Id;
                    modelDetail.F_Count = m.F_Count;
                    modelDetail.F_Price = modelProduct.F_MemberPrice;
                    //参加活动特价
                    if (UseActivity4.Contains("," + modelProduct.F_ProductId + ","))
                        modelDetail.F_DealPrice = modelProduct.F_SpecialPrice;
                    else
                        modelDetail.F_DealPrice = modelProduct.F_MemberPrice;
                    //参加生日
                    if (UseActivity2.Contains("," + modelProduct.F_ProductId + ","))
                    {
                        modelDetail.F_DealPrice = 0.00M;
                        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;
                    if (modelProduct.F_Tag.IndexOf(".") > -1 && !string.IsNullOrEmpty(UseActivity))
                    {
                        string[] tagarry = modelProduct.F_Tag.Split(',');
                        string[] actlist = UseActivity.Split(',');
                        string tag = tagarry.First(a => a.StartsWith(".")).ToString();
                        T_Sys_Marketing modelactive = await bus_MarketingRepository.GetFirst(b => actlist.Contains(b.F_ID.ToString()) && b.F_EndTime >= DateTime.Now && b.F_StartTime<=DateTime.Now && b.F_IsDelete==0&&("," + b.F_Commodity + ",").Contains(("," + tag + ",")));

                        //此商品参加活动
                        if (modelactive != null)
                        {
                            modelDetail.F_Activity = modelactive.F_ID;
                        }
                    }

                    totle += modelDetail.F_TotlePrice;
                    modelDetailList.Add(modelDetail);

                    n++;
                }

                #endregion
                modelOrder.F_TotlePrice = totle;
                modelOrder.F_ActivityMoney = ActivityMoney;
                modelOrder.F_UseActivity = UseActivity;
            }
            else
            {
                //不传商品 表明不修改商品信息 不重新计算商品
            }


            //直接提交  锁库存
            T_Cus_ScoreSet modelscore = await cus_score_setRepository.GetSingle(x => x.F_State == 1);
            if (modelscore == null)
            {
                modelscore = new T_Cus_ScoreSet();
                modelscore.F_Start = 0;
                modelscore.F_StartDebit = 1;
                modelscore.F_DebitPercent = 1000;
            }
            #region 提交 更改状态   库存  积分

             
            if (input.F_State == 1)
            {
                if (string.IsNullOrEmpty(input.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_FlowNum = DateTime.Now.ToString("yyMMddHHmmss") + "U" + UserLogin.UserId + "R" + new Random().Next(9);

                if (modelscore.F_Start == 1)
                {
                    //订单完成后计算积分
                    modelOrder.F_Score = -0.01M;
                }
                else
                {  //订单完成后也不计算积分
                    modelOrder.F_Score = 0.00M;
                }
                if (modelscore.F_StartDebit == 1)
                {
                    modelOrder.F_UseScore = 0;
                }

                string strStock = await busOrderFunctionController.ChangeStockOne(modelOrder, 1, modelDetailList);
                if (strStock != "1")
                { return Error(strStock); }
                modelOrder.F_SubmitTime = DateTime.Now;
            }
            #endregion

            if (!modelOrder.F_Type.Contains("售后"))
            { modelOrder.F_ShouldPrice = modelOrder.F_TotlePrice - modelOrder.F_ActivityMoney + modelOrder.F_ExpressFee - modelOrder.F_UseScore / modelscore.F_DebitPercent;
        }
            DataTable dt=await busOrderMoneyRepository.GetTableSugar(string.Format("SELECT IFNULL(SUM(F_Money),0) FROM T_Bus_OrderMoney WHERE F_OrderId='{0}' AND F_State=1", modelOrder.F_Id));
            modelOrder.F_RealPrice = dt.Rows[0][0].ObjToDecimal() ;
            if (modelOrder.F_ShouldPrice > 0)
            {
                if (modelOrder.F_ShouldPrice <= modelOrder.F_RealPrice)
                     modelOrder.F_PayState = 1;
                else
                     modelOrder.F_PayState = 0;
            }
            else
            {
                if (modelOrder.F_ShouldPrice >= modelOrder.F_RealPrice)
                    modelOrder.F_PayState = 3;
                else 
                    modelOrder.F_PayState = 2;                 

            }
            //待付款 客服审核付款情况后改为已付款


            if (await bus_OrderRepository.Update(modelOrder))
            {
                if (input.OrderDetailList != null && input.OrderDetailList.Count > 0)
                {
                    //删除之前订单商品，重新添加
                    if (await bus_OrderDetailRepository.Delete(q => q.F_OrderId == modelOrder.F_Id))
                    {
                        
                        if (await bus_OrderDetailRepository.AddMany(modelDetailList))
                            return Success("订单生成成功");
                        else
                            return Error("订单操作失败,请重试1！");
                    }
                    else {
                        if (await bus_OrderDetailRepository.AddMany(modelDetailList))
                            return Success("订单生成成功2");
                        else
                            return Error("订单操作失败,请重试2！");
                       }
                }
                else { return Success("成功"); }
            }

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


        }

        /// <summary>
        /// 根据商品组合 获取符合的所有活动
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getact")]
        public async Task<IActionResult> GetAct([FromBody]List<OrderDetailInput> input)
        {
            decimal def = 0.00M;
            if (input.Count < 1)
                return Error("请选择商品/数量");

            //统计活动金额是否符合条件 满减
            Dictionary<int, decimal> acttype3 = new Dictionary<int, decimal>();
            //内部计算
            Dictionary<int, decimal> innerCompute = new Dictionary<int, decimal>();

            //选择活动
            Dictionary<int, string> chooseact = new Dictionary<int, string>();
            List<UseActInput> actlist = new List<UseActInput>();
            foreach (OrderDetailInput m in input)
            {
                T_Bus_Product modelProduct = await bus_productRepository.GetSingle(b => b.F_ProductId == m.F_ProductId);
                if (modelProduct != null)
                {
                    //是否有活动标签
                    if (modelProduct.F_Tag.IndexOf(".") > -1)
                    {
                        string[] tagarry = modelProduct.F_Tag.Split(',');
                        string tag = tagarry.First(a => a.StartsWith(".")).ToString();
                        //标签内有效期
                        var Marketing = await bus_MarketingRepository.GetListALL(b => ("," + b.F_Commodity + ",").Contains("," + tag + ",") && b.F_StartTime <= DateTime.Now && b.F_EndTime >= DateTime.Now && b.F_IsDelete == 0);

                        //此商品参加活动
                        if (Marketing != null)
                        {
                            T_Sys_Marketing modelactive = Marketing.FirstOrDefault();
                            if (modelactive.F_Type == 1)
                            {
                                //满赠
                                //判断此人是否有参与活动的资格  默认暂不筛选
                                if (chooseact.ContainsKey(modelactive.F_ID))
                                    continue;
                                if (innerCompute.ContainsKey(modelactive.F_ID))
                                {
                                    innerCompute[modelactive.F_ID] = (decimal)modelProduct.F_MemberPrice * m.F_Count + innerCompute[modelactive.F_ID].ObjToDecimal();
                                }
                                else
                                {
                                    innerCompute.Add(modelactive.F_ID, (decimal)modelProduct.F_MemberPrice * m.F_Count);
                                }
                                if (modelactive.F_Money.ObjToDecimal() <= (decimal)innerCompute[modelactive.F_ID])
                                {
                                    chooseact.Add(modelactive.F_ID, "1_" + modelactive.F_Gift);
                                    actlist.Add(new UseActInput { id = modelactive.F_ID, type = 1, gift = modelactive.F_Gift, money = def, actname = modelactive.F_Name, actdes = modelactive.F_PromotionRules });
                                }
                            }
                            else if (modelactive.F_Type == 2)
                            {
                                //  生日
                                //TODO 判断此人是否有参与活动的资格  默认暂不筛选  
                                if (chooseact.ContainsKey(modelactive.F_ID))
                                    continue;
                                chooseact.Add(modelactive.F_ID, "2_" + modelactive.F_Commodity);
                                actlist.Add(new UseActInput { id = modelactive.F_ID, type = 2, gift = modelactive.F_Gift, money = def, actname = modelactive.F_Name, actdes = modelactive.F_PromotionRules });
                            }
                            else if (modelactive.F_Type == 3)
                            {
                                //满减
                                //判断此人是否有参与活动的资格  默认暂不筛选

                                if (innerCompute.ContainsKey(modelactive.F_ID))
                                {
                                    innerCompute[modelactive.F_ID] = (decimal)modelProduct.F_MemberPrice * m.F_Count + innerCompute[modelactive.F_ID];
                                }
                                else
                                {
                                    innerCompute.Add(modelactive.F_ID, (decimal)modelProduct.F_MemberPrice * m.F_Count);
                                }
                                string[] AmountRange = modelactive.F_AmountRange.Split(',');
                                for (int i = 0; i < AmountRange.Length; i++)
                                {
                                    //符合满减某个条件
                                    if (innerCompute[modelactive.F_ID] >= AmountRange[i].ObjToDecimal())
                                    {
                                        if (acttype3.ContainsKey(modelactive.F_ID))
                                        {
                                            //当前减免金额大于之前发赋值，替换掉
                                            if (modelactive.F_Money.Split(',')[i].ObjToDecimal() > acttype3[modelactive.F_ID])
                                            {
                                                acttype3[modelactive.F_ID] = modelactive.F_Money.Split(',')[i].ObjToDecimal();
                                                actlist.ForEach(q => { if (q.id == modelactive.F_ID) { q.money = modelactive.F_Money.Split(',')[i].ObjToDecimal(); } });
                                            }
                                        }
                                        else
                                        {
                                            //满足条件，赋值满减金额 减的金额
                                            acttype3.Add(modelactive.F_ID, modelactive.F_Money.Split(',')[i].ObjToDecimal());
                                            actlist.Add(new UseActInput { id = modelactive.F_ID, type = 3, gift = "", money = modelactive.F_Money.Split(',')[i].ObjToDecimal(), actname = modelactive.F_Name, actdes = modelactive.F_PromotionRules });
                                        }
                                    }
                                }

                            }
                            else if (modelactive.F_Type == 4)
                            {
                                //限时特惠
                                //判断此人是否有参与活动的资格  默认暂不筛选
                                if (chooseact.ContainsKey(modelactive.F_ID))
                                {
                                    chooseact[modelactive.F_ID] = chooseact[modelactive.F_ID] + "," + m.F_ProductId.ToString();
                                    actlist.ForEach(q => { if (q.id == modelactive.F_ID) { q.gift = q.gift + m.F_ProductId.ToString(); } });
                                }
                                else
                                {
                                    chooseact.Add(modelactive.F_ID, "4_" + m.F_ProductId.ToString());
                                    actlist.Add(new UseActInput { id = modelactive.F_ID, type = 4, gift = m.F_ProductId.ToString(), money = modelactive.F_Money.ObjToDecimal(), actname = modelactive.F_Name, actdes = modelactive.F_PromotionRules });
                                }


                            }
                        }
                    }
                }
            }

            return Success("参与活动", actlist);


        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getorderdetail")]
        public async Task<IActionResult> GetOrderDetail(string orderid)
        {
            if (string.IsNullOrEmpty(orderid))
                return Error("请输入订单号");
            T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == orderid);
            OrderInput modelreturn = new OrderInput();
            if (modelOrder != null)
            {
                ModelConvertHelper<OrderInput, T_Bus_Order>.ModeToModel(modelreturn, modelOrder);

                List<OrderDetailInput> modeldetailreturn = new List<OrderDetailInput>();
                List<T_Bus_OrderDetail> detaillist = await bus_OrderDetailRepository.GetListALL(q => q.F_OrderId == modelOrder.F_Id, o => o.F_Sort, OrderByType.Asc);
                if (detaillist != null)
                {
                    foreach (T_Bus_OrderDetail m in detaillist)
                    {
                        OrderDetailInput model = new OrderDetailInput();
                        model.F_ProductName = m.F_ProductName;
                        model.F_ProductId = m.F_ProductId;
                        model.F_Id = m.F_Id;
                        model.F_OrderId = m.F_OrderId;
                        model.F_Count = m.F_Count;
                        model.F_Price = m.F_Price;

                        model.F_DealPrice = m.F_DealPrice;
                        model.F_Sort = m.F_Sort;
                        model.F_AddTime = m.F_AddTime;
                        model.F_Remark = m.F_Remark;
                        model.F_AddUser = m.F_AddUser;
                        model.F_AddUserName = m.F_ProductName;
                        model.F_TotlePrice = m.F_TotlePrice;
                        model.F_Activity = m.F_Activity;
                        modeldetailreturn.Add(model);
                    }
                }
                modelreturn.OrderDetailList = modeldetailreturn;

                List<UseActInput> actlist = new List<UseActInput>();
                List<T_Sys_Marketing> modelactiveList = await bus_MarketingRepository.GetListALL(b => ("," + modelOrder.F_UseActivity + ",").Contains(("," + b.F_ID.ToString() + ",")));


                if (modelactiveList != null && modelactiveList.Count > 0)
                {
                    foreach (T_Sys_Marketing modelactive in modelactiveList)
                    {
                        actlist.Add(new UseActInput { id = modelactive.F_ID, type = modelactive.F_Type, gift = modelactive.F_Gift, money = modelactive.F_Money.ObjToDecimal(), actname = modelactive.F_Name, actdes = modelactive.F_PromotionRules });
                    }
                }
                modelreturn.UseActList = actlist;

            }


            return Success("成功", modelreturn);


        }


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

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


            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.GreaterThanOrEqual, 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 ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.And , new ConditionalModel() { FieldName = "F_AddUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_Belong", 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="orderid">订单号</param>
        /// <param name="state">订单状态 -1无效 0暂存 1提交  2KF退回  3通过 4KG退回 5已分拣 6已发货</param>
        /// <param name="remark">客服备注</param>
        /// <returns></returns>
        [HttpPost("cancelorder")]
        public async Task<IActionResult> CancelOrder(string orderid, int state = 0)
        {
            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 &&new int[] { 1,3,4}.Contains(q.F_State));

                if (modelOrder == null)
                {
                    return Error("订单已审核");
                }


                string strStock = await busOrderFunctionController.ChangeStockOne(modelOrder, 0, null);
                if (strStock != "1")
                    return Error(strStock);
                modelOrder.F_State = 0;
                modelOrder.F_Score = 0.00M;



                if (await bus_OrderRepository.Update(modelOrder))
                    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_MoneyBak= modelOrderMoeny.F_Money;
                modelOrderMoeny.F_State= 0;
                modelOrderMoeny.F_Id = Guid.NewGuid().ToString().Replace("-","");
                if (await busOrderMoneyRepository.AddReturnCount(modelOrderMoeny))
                    return Success("成功！");
                return Error("失败！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }




    }
}