using APT.BaseData.Domain.ApiModel.OP;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.OP;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.OP;
using APT.Infrastructure.Api;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace APT.OP.WebApi.Controllers.Api
{
    [Route("api/OP/Client")]
    public class ClientInfoController : APTApiController<T_OP_CLIENT>
    {
        /// <summary>
        ///更新用户信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdateClient")]
        public JsonActionResult<dynamic> UpdateClient([FromBody] WeiUserUpdateModel entity)
        {
            return SafeExecute<dynamic>(() =>
            {
                dynamic result = new ExpandoObject();
                var userInfo = this.GetEntity<T_OP_CLINET_OPENID>(x => x.OPEN_ID == entity.openid, "NavClient");
                if (userInfo != null && userInfo.NavClient != null)
                {
                    var user = userInfo.NavClient;
                    user.NICK_NAME = entity.UserInfo.nickName;
                    user.ID_CARD = entity.UserInfo.idcard;
                    user.NAME = entity.UserInfo.name;
                    user.TEL = entity.UserInfo.tel;
                    user.EMAIL = entity.UserInfo.email;
                    user.ADDR = entity.UserInfo.addr;
                    user.AVATAURL = entity.UserInfo.avatarUrl;
                    this.UpdateEntity(user);
                }
                else
                {
                    throw (new Exception("更新用户信息失败！"));
                }
                result = entity;
                return result;
            });
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>

        [HttpGet, Route("GetClient")]
        public JsonActionResult<WeiUserUpdateModel> GetClient(string openid)
        {
            return base.SafeExecute(() =>
            {
                WeiUserUpdateModel result = new WeiUserUpdateModel();
                if (string.IsNullOrEmpty(openid))
                    throw (new Exception("参数openid为空"));
                var weChatOpen = this.GetEntity<T_OP_CLINET_OPENID>(x => x.OPEN_ID == openid, "NavClient");
                if (weChatOpen == null)
                    throw (new Exception("用户不存在"));
                var user = weChatOpen.NavClient;
                result.openid = openid;
                UserInfo userInfo = new UserInfo()
                {
                    id = user.ID.ToString(),
                    name = user.NAME,
                    nickName = user.NICK_NAME,
                    tel = user.TEL,
                    email = user.EMAIL,
                    idcard = user.ID_CARD,
                    addr = user.ADDR,
                    avatarUrl = user.AVATAURL
                };
                result.UserInfo = userInfo;
                return result;
            });
        }
        /// <summary>
        /// 获取用户手机号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost, Route("GetPhone")]
        public JsonActionResult<WeiUserUpdateModel> GetPhone([FromBody] GetPhone getPhone)
        {
            return base.SafeExecute(() =>
            {
                WeiUserUpdateModel result = new WeiUserUpdateModel();
                var session_key = CsRedisManager.StringGet<string>("WX_session_key");
                byte[] encryData = Convert.FromBase64String(getPhone.encryptedData);
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(session_key);
                rijndaelCipher.IV = Convert.FromBase64String(getPhone.iv);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string res = Encoding.Default.GetString(plainText);

                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(res) as dynamic;
                string phoneNumber = model.phoneNumber;
                result.openid = getPhone.openid;
                var weChatOpen = this.GetEntity<T_OP_CLINET_OPENID>(x => x.OPEN_ID == getPhone.openid, "NavClient");
                if (weChatOpen == null)
                    throw (new Exception("用户不存在"));
                var user = weChatOpen.NavClient;
                result.openid = getPhone.openid;
                UserInfo userInfo = new UserInfo()
                {
                    id = user.ID.ToString(),
                    name = user.NAME,
                    nickName = user.NICK_NAME,
                    tel = user.TEL,
                    email = user.EMAIL,
                    idcard = user.ID_CARD,
                    addr = user.ADDR,
                    avatarUrl = user.AVATAURL
                };
                if (!string.IsNullOrEmpty(phoneNumber))
                {
                    userInfo.tel = phoneNumber;
                }
                result.UserInfo = userInfo;
                return result;
            });
        }


        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PhoneVerifyCode")]
        public JsonActionResult<bool> PhoneVerifyCode([FromBody] WeChatPhone entity)
        {
            return SafeExecute<bool>(() =>
            {

                string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode, 6);
                Dictionary<string, string> dicNCode = new Dictionary<string, string>();
                dicNCode.Add("time", DateTime.Now.AddSeconds(600).ToString());
                dicNCode.Add("code", code);
                var redisManage = ServiceLocator.Instance.GetService<RedisManager>();
                CsRedisManager.StringSet(entity.openid, dicNCode);
                var serice = ServiceLocator.Instance.GetService<IOPSmsService>();
                return serice.SendMessage(entity.phone, code);
            });
        }
        /// <summary>
        /// 验证手机验证码
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        [HttpPost, Route("CheckPhoneCode")]
        public JsonActionResult<bool> CheckPhoneCode([FromBody] WeChatPhone entity)
        {
            return SafeExecute<bool>(() =>
            {
                var verCode = CsRedisManager.StringGet<Dictionary<string, string>>(entity.openid.ToString());
                if (verCode == null)
                    throw new Exception("手机验证码不存在!");
                if (Convert.ToDateTime(verCode["time"]) < DateTime.Now)
                    throw new Exception("手机验证码已失效，请重新获取!");
                if (entity.code.ToUpper() != verCode["code"].ToUpper())
                    throw new Exception("手机验证码不正确!");
                return true;
            });
        }

        /// <summary>
        /// 获取我的电卡列表/购买电卡列表(ignore)
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        [HttpPost, Route("GetElectricCard")]

        public PagedActionResult<dynamic> GetElectricCard([FromBody] SearchMemberCard searchMemberCard)
        {
            return SafeGetPagedData<dynamic>((res) =>
            {
                //dynamic result = new ExpandoObject();
                BasePageFilter filter = new BasePageFilter();
                filter.PageIndex = searchMemberCard.pageIndex;
                filter.Limit = searchMemberCard.limit;
                filter.IsMultipleDb = true;
                filter.Sort = "CODE";
                filter.Order = DbOrder.DESC;
                filter.IgnoreOrgRule = true;
                var members = this.GetOrderPageEntities<T_FC_MEMBER>(x => x.OPENID == searchMemberCard.openid
                                      && x.TENANT_NAME.Contains(searchMemberCard.keyword), filter, "Nav_RechargeCard");//会员卡
                var cards = new List<RechargeCard>();
                BaseFilter baseFilter = new BaseFilter();
                baseFilter.IsMultipleDb = true;
                baseFilter.IgnoreOrgRule = true;
                var fullminus = this.GetEntities<T_FC_MEMBER_ACTIVITY>(x => x.START_TIME <= DateTime.Now
                      && x.END_TIME >= DateTime.Now, baseFilter, "Nav_ActivityDetail");//满减活动表
                var stations = this.GetEntities<T_CP_CHARGING_STATION>(null, baseFilter);//充电站
                if (!searchMemberCard.isbuy)//购买电卡列表
                {
                    var existTenants = this.GetEntities<T_FC_MEMBER>(x => x.OPENID == searchMemberCard.openid, baseFilter).Select(x => x.TENANT_CODE);
                    var baseFilter1 = new BasePageFilter();
                    baseFilter1.PageIndex = searchMemberCard.pageIndex;
                    baseFilter1.Limit = searchMemberCard.limit;
                    baseFilter1.IsSpecifyDb = true;
                    baseFilter1.IgnoreOrgRule = true;
                    var tenants = this.GetOrderPageEntities<T_OP_TENANT>(x => !existTenants.Contains(x.CODE)
                               && x.NAME.Contains(searchMemberCard.keyword)&& x.PROJECT_TYPE ==(int)OPProjectTypeEnum.充电桩, baseFilter1);//未购买运营商
                    foreach (var tenant in tenants.Data)
                    {
                        List<Fullminus> actities = new List<Fullminus>();
                        List<string> useRange = new List<string>();
                        var tenantStations = stations.Where(x => x.ORG_ID == tenant.ID);
                        var memberActivity = fullminus.FirstOrDefault(x => x.ORG_ID == tenant.ID);
                        if (memberActivity != null && memberActivity.Nav_ActivityDetail != null)
                        {
                            foreach (var detail in memberActivity.Nav_ActivityDetail)
                            {
                                var actity = new Fullminus()
                                {
                                    full = detail.RECHARGE_AMOUNT,
                                    reduce = detail.DISCOUNTED_AMOUNT
                                };
                                actities.Add(actity);
                            }
                        }
                        var card = new RechargeCard()
                        {
                            tenantName = tenant.NAME,
                            tenantCode = tenant.CODE,
                            fullminus = actities,
                        };
                        if (tenantStations != null && tenantStations.Any())
                            useRange = tenantStations.Select(x => x.NAME).ToList();//电卡适用充电站  
                        card.useRange = useRange;
                        cards.Add(card);
                    }
                    res.Data = cards;
                    res.TotalCount = tenants.TotalCount;
                }
                else
                {
                    foreach (var member in members.Data)//会员卡列表
                    {
                        var tenantStations = stations.Where(x => x.ORG_ID == member.ORG_ID);
                        var memberActivity = fullminus.FirstOrDefault(x => x.ORG_ID == member.ORG_ID);
                        List<Fullminus> actities = new List<Fullminus>();
                        foreach (var detail in memberActivity.Nav_ActivityDetail)
                        {
                            var actity = new Fullminus()
                            {
                                full = detail.RECHARGE_AMOUNT,
                                reduce = detail.DISCOUNTED_AMOUNT
                            };
                            actities.Add(actity);
                        }
                        var card = new RechargeCard()
                        {
                            cardNo = member.Nav_RechargeCard.CODE,
                            balance = member.Nav_RechargeCard.BALANCE,
                            tenantName = member.TENANT_NAME,
                            tenantCode = member.TENANT_CODE,
                            fullminus = actities,
                            useRange = tenantStations.Select(x => x.NAME).ToList()//电卡适用充电站
                        };
                        cards.Add(card);
                    }
                    res.Data = cards;
                    res.TotalCount = members.TotalCount;
                }
            });
        }

        /// <summary>
        /// 购买电卡
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        [HttpPost, Route("BuyMemberCard")]

        public JsonActionResult<dynamic> BuyMemberCard([FromBody] BuyCard buyCard)
        {
            return SafeExecute<dynamic>(() =>
            {
                var tenant = this.GetEntity<T_OP_TENANT>(x => x.CODE == buyCard.tenantCode);//查找运营商
                var filter = new BaseFilter();
                filter.IsSpecifyDb = true;
                filter.SpecifyTenant = buyCard.tenantCode;
                //filter.IgnoreOrgRule = true;
                filter.OrgId = tenant.ID;
                var member = this.GetEntity<T_FC_MEMBER>(x => x.OPENID == buyCard.openid, filter, "Nav_RechargeCard");//查找会员  
                RechargeCard rechargeCard = new RechargeCard();
                if (member == null)//创建会员
                {
                    //var org = this.GetEntity<T_FM_ORGANIZATION>(x => x.TENANT_CODE == buyCard.tenantCode, filter);
                    var codeRuleService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFCodeRuleService>();
                    SystemCodeFilter codeFilter = new SystemCodeFilter();
                    codeFilter.CodeType = (int)PFCodeRuleType.充值卡编码;
                    codeFilter.Count = 1;
                    codeFilter.OrgId = tenant.ID;
                    T_FC_RECHARGE_CARD czk = new T_FC_RECHARGE_CARD()
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = tenant.ID,
                        CODE = codeRuleService.NewGenSerialByTenant(codeFilter, buyCard.tenantCode),
                        BALANCE = 0,
                    };
                    SystemCodeFilter codeMember = new SystemCodeFilter();
                    codeMember.CodeType = (int)PFCodeRuleType.会员编码;
                    codeMember.Count = 1;
                    codeMember.OrgId = tenant.ID;
                    member = new T_FC_MEMBER()
                    {
                        ORG_ID = tenant.ID,
                        OPENID = buyCard.openid,
                        CODE = codeRuleService.NewGenSerialByTenant(codeMember, buyCard.tenantCode),
                        RECHARGE_CARD_ID = czk.ID,
                        TENANT_CODE = buyCard.tenantCode,
                        TENANT_NAME = tenant.NAME
                    };
                    rechargeCard.cardNo = czk.CODE;
                    rechargeCard.balance = czk.BALANCE;
                    rechargeCard.tenantName = tenant.NAME;
                    rechargeCard.tenantCode = buyCard.tenantCode;

                    List<Fullminus> actities = new List<Fullminus>();
                    List<string> useRange = new List<string>();
                    var tenantStations = this.GetEntities<T_CP_CHARGING_STATION>(null, filter);//充电站
                    var memberActivity = this.GetEntity<T_FC_MEMBER_ACTIVITY>(x => x.START_TIME <= DateTime.Now
                          && x.END_TIME >= DateTime.Now, filter, "Nav_ActivityDetail");//满减活动表   
                    if (memberActivity != null && memberActivity.Nav_ActivityDetail != null)
                    {
                        foreach (var detail in memberActivity.Nav_ActivityDetail)
                        {
                            var actity = new Fullminus()
                            {
                                full = detail.RECHARGE_AMOUNT,
                                reduce = detail.DISCOUNTED_AMOUNT
                            };
                            actities.Add(actity);
                        }
                    }
                    rechargeCard.fullminus = actities;
                    if (tenantStations != null && tenantStations.Any())
                        useRange = tenantStations.Select(x => x.NAME).ToList();//电卡适用充电站  
                    rechargeCard.useRange = useRange;
                    this.UnifiedCommit(() =>
                    {
                        this.AddEntityByTenant(czk, buyCard.tenantCode);
                        this.AddEntityByTenant(member, buyCard.tenantCode);
                    });
                }
                else
                {
                    rechargeCard.cardNo = member.Nav_RechargeCard.CODE;
                    rechargeCard.balance = member.Nav_RechargeCard.BALANCE;
                    rechargeCard.tenantName = tenant.NAME;
                    rechargeCard.tenantCode = buyCard.tenantCode;
                    List<Fullminus> actities = new List<Fullminus>();
                    List<string> useRange = new List<string>();
                    var tenantStations = this.GetEntities<T_CP_CHARGING_STATION>(null, filter);//充电站
                    var memberActivity = this.GetEntity<T_FC_MEMBER_ACTIVITY>(x => x.START_TIME <= DateTime.Now
                          && x.END_TIME >= DateTime.Now, filter, "Nav_ActivityDetail");//满减活动表   
                    if (memberActivity != null && memberActivity.Nav_ActivityDetail != null)
                    {
                        foreach (var detail in memberActivity.Nav_ActivityDetail)
                        {
                            var actity = new Fullminus()
                            {
                                full = detail.RECHARGE_AMOUNT,
                                reduce = detail.DISCOUNTED_AMOUNT
                            };
                            actities.Add(actity);
                        }
                    }
                    rechargeCard.fullminus = actities;
                    if (tenantStations != null && tenantStations.Any())
                        useRange = tenantStations.Select(x => x.NAME).ToList();//电卡适用充电站  
                    rechargeCard.useRange = useRange;
                }
                return rechargeCard;
            });
        }

        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("Recharge")]
        public JsonActionResult<dynamic> Recharge([FromBody] MemberInfo entity)
        {
            return SafeExecute<dynamic>(() =>
            {
                var tenant = this.GetEntity<T_OP_TENANT>(x => x.CODE == entity.tenantCode);//查找运营商
                BaseFilter filter = new BaseFilter();
                filter.IsSpecifyDb = true;
                filter.SpecifyTenant = entity.tenantCode;
                //filter.IgnoreOrgRule = true;
                filter.OrgId = tenant.ID;
                var member = this.GetEntity<T_FC_MEMBER>(x => x.OPENID == entity.openid && x.TENANT_CODE == entity.tenantCode,
                      filter, "Nav_RechargeCard");
                var recharge = member.Nav_RechargeCard;
                var orgId = member.ORG_ID;
                var codeRuleService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFCodeRuleService>();
                SystemCodeFilter codeFilter = new SystemCodeFilter();
                codeFilter.CodeType = (int)PFCodeRuleType.电卡充值订单号;
                codeFilter.Count = 1;
                codeFilter.OrgId = orgId;
                var code = codeRuleService.NewGenSerialByTenant(codeFilter, entity.tenantCode);
                var macId = string.Empty;
                var wxPaykey = string.Empty;
                if (tenant != null && tenant.MCH_ID != null && tenant.WXPAYKEY != null)
                {
                    macId = tenant.MCH_ID;
                    wxPaykey = tenant.WXPAYKEY;
                }
                else
                    throw new Exception("商户ID或支付Key未配置!");
                var res = WeChatPayHelper.Unifiedorder(entity.openid, (int)(Convert.ToDouble(entity.rechargeAmount) * (double)100), code, "DK", macId, wxPaykey);
                var newOrder = new T_SO_RECHARGE_ORDER()
                {
                    ORG_ID = orgId,
                    RECHARGE_CARD_ID = recharge.ID,
                    AMOUNT = entity.fullAmount,
                    TIME = DateTime.Now,
                    ORDER_STATUS = 0,
                    CODE = code
                };
                this.AddEntityByTenant(newOrder, entity.tenantCode);
                return res;
            });
        }


        /// <summary>
        /// 获取充值金额
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpGet, Route("GetRechargeAmount")]
        public JsonActionResult<dynamic> GetRechargeAmount(string tenantCode)
        {
            return SafeExecute<dynamic>(() =>
            {
                List<TextValue> textValues = new List<TextValue>();
                BaseFilter filter = new BaseFilter();
                filter.IsSpecifyDb = true;
                filter.IgnoreOrgRule = true;
                var rechargeSets = this.GetEntities<T_OP_RECHARGE_SETTING>(null, filter).OrderBy(x => x.AMOUNT);
                var tenant = this.GetEntity<T_OP_TENANT>(x => x.CODE == tenantCode);//查找运营商
                filter.SpecifyTenant = tenantCode;
                filter.IgnoreOrgRule = false;
                filter.OrgId = tenant.ID;//切换运营商
                var activities = this.GetEntity<T_FC_MEMBER_ACTIVITY>(x => x.START_TIME <= DateTime.Now
                      && x.END_TIME >= DateTime.Now, filter, "Nav_ActivityDetail");
                foreach (var rechargeSet in rechargeSets)
                {
                    var data = new TextValue()
                    {
                        text = rechargeSet.AMOUNT.ToString() + "元",
                        value = rechargeSet.AMOUNT
                    };
                    if (activities != null && activities.Nav_ActivityDetail != null)
                    {
                        var detail = activities.Nav_ActivityDetail.OrderByDescending(x => x.RECHARGE_AMOUNT)
                                    .FirstOrDefault(x => x.RECHARGE_AMOUNT <= rechargeSet.AMOUNT);
                        if (detail != null)
                        {
                            data.text = rechargeSet.AMOUNT.ToString() + "元";
                            data.value = (rechargeSet.AMOUNT - detail.DISCOUNTED_AMOUNT);
                            data.full = detail.RECHARGE_AMOUNT;
                            data.reduce = detail.DISCOUNTED_AMOUNT;
                        }
                    }
                    textValues.Add(data);
                }
                return textValues;
            });
        }
        /// <summary>
        /// 小程序首页
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetHomePage")]
        public JsonActionResult<dynamic> GetHomePage()
        {
            return SafeExecute<dynamic>(() =>
            {
                dynamic result = new ExpandoObject();
                BaseFilter filter = new BaseFilter(new Guid(LibUtils.ToString(ConfigurationManager.WexinSettings["OrgId"]).ToString()));
                filter.IgnoreOrgRule = true;
                var config = this.GetEntities<T_FM_BASE_CONFIG>(null, filter, "Nav_TopPicture.Nav_PictureFiles.Nav_ImgFile.Nav_File",
                               "Nav_LowPicture.Nav_PictureFiles.Nav_ImgFile.Nav_File").FirstOrDefault();
                List<byte[]> topPs = new List<byte[]>();
                List<byte[]> lowPs = new List<byte[]>();
                List<string> notices = new List<string>();
                if (config != null && config.Nav_TopPicture != null)
                {
                    var topPics = config.Nav_TopPicture.Nav_PictureFiles;
                    foreach (var topPic in topPics)
                    {
                        var data = topPic.Nav_ImgFile.Nav_File.FILE_DATA;
                        topPs.Add(data);
                    }
                }
                if (config != null && config.Nav_LowPicture != null)
                {
                    var lowPics = config.Nav_LowPicture.Nav_PictureFiles;
                    foreach (var lowPic in lowPics)
                    {
                        var data = lowPic.Nav_ImgFile.Nav_File.FILE_DATA;
                        lowPs.Add(data);
                    }
                }
                result.topPs = topPs;
                result.lowPs = lowPs;
                var notics = this.GetEntities<T_OP_NOTICE>(null, filter, "Nav_NoticeDetails");
                if (notics != null)
                {
                    var notic = notics.OrderByDescending(x => x.CREATE_TIME).FirstOrDefault();
                    notices.AddRange(notic.Nav_NoticeDetails.Select(x => x.TEXT));
                }
                result.notices = notices;
                return result;
            });
        }
        /// <summary>
        /// 常见问题
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetCommonQuestion")]
        public JsonActionResult<dynamic> GetCommonQuestion()
        {
            return SafeExecute<dynamic>(() =>
            {
                BaseFilter filter = new BaseFilter(new Guid(LibUtils.ToString(ConfigurationManager.WexinSettings["OrgId"]).ToString()));
                var questions = this.GetEntities<T_OP_COMMON_QUESTION>(null, filter);
                List<CommonQuestion> commonQuestions = new List<CommonQuestion>();
                foreach (var question in questions)
                {
                    commonQuestions.Add(new CommonQuestion { question = question.QUESTION, answer = question.ANSWER });
                }
                return commonQuestions;
            });
        }

        /// <summary>
        /// 获取充值记录
        /// </summary>
        /// <param name="orderByPage"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRechargeRecord")]
        public PagedActionResult<dynamic> GetRechargeRecord([FromBody] OrderByPage orderByPage)
        {
            return SafeGetPagedData<dynamic>((res) =>
            {
                BasePageFilter filter = new BasePageFilter();
                filter.IsMultipleDb = true;
                filter.IgnoreOrgRule = true;
                filter.PageIndex = orderByPage.pageIndex;
                filter.Limit = orderByPage.limit;
                filter.Sort = "CREATE_TIME";
                filter.Order = DbOrder.DESC;
                var member = this.GetEntity<T_FC_MEMBER>(x => x.OPENID == orderByPage.openid, filter, "Nav_RechargeCard");
                if (member == null)
                {
                    throw (new Exception("暂无充值订单！"));
                }
                var orders = this.GetOrderPageEntities<T_SO_RECHARGE_ORDER>(x => x.RECHARGE_CARD_ID == member.Nav_RechargeCard.ID, filter);
                List<RechargeOrder> chargOrders = new List<RechargeOrder>();
                if (orders != null && orders.Data.Any())
                {
                    foreach (var order in orders.Data)
                    {
                        RechargeOrder rechargOrder = new RechargeOrder()
                        {
                            code = order.CODE,
                            status = order.ORDER_STATUS,
                            rechargeAmount = order.AMOUNT,
                            time = order.TIME
                        };
                        chargOrders.Add(rechargOrder);
                    }
                }
                res.Data = chargOrders;
                res.TotalCount = orders.TotalCount;
            });
        }



        /// <summary>
        /// 订单支付
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("Payment")]
        public JsonActionResult<dynamic> Payment([FromBody] PayInfo entity)
        {
            return SafeExecute<dynamic>(() =>
            {
                var tenantCode = entity.code.Substring(2, 4);
                var tenant = this.GetEntity<T_OP_TENANT>(x => x.CODE == tenantCode);//查找运营商
                if (entity.payType == (int)FCPayType.电卡支付)
                {
                    BaseFilter filter = new BaseFilter();
                    filter.IsSpecifyDb = true;
                    filter.SpecifyTenant = tenantCode;
                    filter.OrgId = tenant.ID;
                    var member = this.GetEntity<T_FC_MEMBER>(x => x.OPENID == entity.openid, filter, "Nav_RechargeCard");
                    if (member == null)
                        throw (new Exception("暂未开通电卡！"));
                    if (member.Nav_RechargeCard.BALANCE < entity.payAmount)
                        throw (new Exception("电卡余额不足，请先充值！"));
                    var rechargeCard = member.Nav_RechargeCard;
                    rechargeCard.BALANCE -= entity.payAmount;
                    this.UpdateEntityByTenant(rechargeCard, tenantCode, "BALANCE");//电卡扣除

                    var order = this.GetEntity<T_SO_CHARGING_ORDER>(x => x.CODE == entity.code && x.OPEN_ID == entity.openid, filter);//查询订单
                    order.ORDER_STATUS = (int)FCOrderStatus.已付款;
                    order.PAY_TYPE = entity.payType;
                    this.UpdateEntityByTenant(order, tenantCode);//更新订单状态
                    return true;
                }
                else //微信支付
                {
                    BaseFilter filter = new BaseFilter();
                    filter.IsSpecifyDb = true;
                    filter.SpecifyTenant = tenantCode;
                    filter.OrgId = tenant.ID;
                    var order = this.GetEntity<T_SO_CHARGING_ORDER>(x => x.CODE == entity.code && x.OPEN_ID == entity.openid, filter);//查询订单                                                                                                                                                         // var tenant = this.GetEntity<T_OP_TENANT>(x => x.CODE == entity.code.Substring(2, 4), baseFilter);
                    var macId = string.Empty;
                    var wxPaykey = string.Empty;
                    if (tenant != null && tenant.MCH_ID != null && tenant.WXPAYKEY != null)
                    {
                        macId = tenant.MCH_ID;
                        wxPaykey = tenant.WXPAYKEY;
                    }
                    else
                        throw new Exception("商户ID或支付Key未配置!");
                    var res = WeChatPayHelper.Unifiedorder(entity.openid, (int)(Convert.ToDouble(entity.payAmount) * (double)100), order.CODE, "WX", macId, wxPaykey);//调用微信下单
                    return res;
                }
            });
        }

        #region 运营商信息
        [HttpPost, Route("GetTenant")]
        public PagedActionResult<dynamic> GetTenant([FromBody] OrderByPage orderByPage)
        {
            return SafeGetPagedData<dynamic>((res) =>
            {
                IEnumerable<T_OP_TENANT> tenantDatas = new List<T_OP_TENANT>();
                var count = 0;
                IEnumerable<string> applyedTenant = null;//归属运营商
                IEnumerable<string> applyTenant = null;//审核中
                var baseFilter = new BaseFilter();
                baseFilter.IsMultipleDb = true;
                baseFilter.IgnoreOrgRule = true;
                var applyeds = this.GetEntities<T_MT_MAINTAIN_PERSON>(x => x.Nav_Approval.OPEN_ID == orderByPage.openid
               && x.IS_APPROVAL, baseFilter, "Nav_Approval");//已审核非离职人员
                applyedTenant = applyeds.Select(x => x.Nav_Approval.TENANT_CODE);
                var applyings = this.GetEntities<T_MT_MAINTAIN_APPROVAL>(x => x.OPEN_ID == orderByPage.openid
                   && x.APPROVAL_STATUS == (int)MTApprovalEnum.待审核, baseFilter);
                applyTenant = applyings.Select(x => x.TENANT_CODE);

                var filter = new BasePageFilter();
                filter.PageIndex = orderByPage.pageIndex;
                filter.Limit = orderByPage.limit;
                filter.IgnoreOrgRule = true;
                filter.Sort = "CREATE_TIME";
                filter.Order = DbOrder.ASC;
                if (orderByPage.isApplyed)//归属运营商
                {
                    if (applyedTenant != null && applyedTenant.Any())
                    {
                        var tenants = this.GetOrderPageEntities<T_OP_TENANT>(x => x.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 &&
                       applyedTenant.Contains(x.CODE) && (x.NAME.Contains(orderByPage.keyword) || x.CODE.Contains(orderByPage.keyword))
                       &&x.PROJECT_TYPE == (int)OPProjectTypeEnum.充电桩, filter);
                        tenantDatas = tenants.Data;
                        count = tenants.TotalCount;
                    }                             
                }
                else
                {
                    var tenants = this.GetOrderPageEntities<T_OP_TENANT>(x => x.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 &&
                      !applyedTenant.Contains(x.CODE) && (x.NAME.Contains(orderByPage.keyword) || x.CODE.Contains(orderByPage.keyword)) 
                      && x.PROJECT_TYPE == (int)OPProjectTypeEnum.充电桩, filter);
                    tenantDatas = tenants.Data;
                    count = tenants.TotalCount;
                }
                List<WxTenant> tenantInfos = new List<WxTenant>();
                foreach (var tenant in tenantDatas)
                {
                    WxTenant wxTenant = new WxTenant()
                    {
                        orgId = tenant.ID.ToString(),
                        tenantCode = tenant.CODE,
                        tenantName = tenant.NAME,
                        status = applyedTenant.Contains(tenant.CODE) ? 2 : (applyTenant.Contains(tenant.CODE) ? 1 : 0)
                    };
                    tenantInfos.Add(wxTenant);
                }

                res.Data = tenantInfos;
                res.TotalCount = count;
            });
        }
        #endregion

        #region 申请成为维护人员
        [HttpPost, Route("ApplyMaintain")]
        public JsonActionResult<dynamic> ApplyMaintain([FromBody] ApplicationInfo entity)
        {
            return SafeExecute<dynamic>(() =>
            {
                BaseFilter filter = new BaseFilter();
                filter.IsSpecifyDb = true;
                filter.SpecifyTenant = entity.tenantCode;
                filter.OrgId = new Guid(entity.orgId);
                var approvaled = this.GetEntity<T_MT_MAINTAIN_PERSON>(x => x.Nav_Approval.OPEN_ID == entity.openid
                    &&x.IS_APPROVAL, filter);
                if (approvaled != null)
                    throw new Exception("当前用户已是运维人员!");
                var approval = this.GetEntity<T_MT_MAINTAIN_APPROVAL>(x => x.OPEN_ID == entity.openid
                      && x.APPROVAL_STATUS == (int)MTApprovalEnum.待审核 && x.TENANT_CODE == entity.tenantCode, filter);
                if (approval != null)
                    throw new Exception("审核中!");
                else 
                { 
                    BaseFilter baseFilter = new BaseFilter();
                    baseFilter.IgnoreOrgRule = true;
                    baseFilter.IsSpecifyDb = true;
                    var client = this.GetEntity<T_OP_CLINET_OPENID>(x => x.OPEN_ID == entity.openid, baseFilter, "NavClient");
                    approval = new T_MT_MAINTAIN_APPROVAL()
                    {
                        ORG_ID = new Guid(entity.orgId),
                        OPEN_ID = entity.openid,
                        CLIENT_ID = client.NavClient.ID.ToString(),
                        NAME = client.NavClient.NICK_NAME,
                        TEL = client.NavClient.TEL,
                        TENANT_CODE = entity.tenantCode,
                        REMARK = entity.remark
                    };
                    this.AddEntityByTenant(approval, entity.tenantCode);
                }
                return true;
            });
        }
        #endregion

        #region 获取是哪几家运营商运维人员

        [HttpGet, Route("GetOperatorInfo")]
        public JsonActionResult<dynamic> GetOperatorInfo(string openid)
        {
            return SafeExecute<dynamic>(() =>
            {
                #region 用户信息
                WeiUserUpdateModel result = new WeiUserUpdateModel();
                if (string.IsNullOrEmpty(openid))
                    throw (new Exception("参数openid为空"));
                var weChatOpen = this.GetEntity<T_OP_CLINET_OPENID>(x => x.OPEN_ID == openid, "NavClient");
                if (weChatOpen == null)
                    throw (new Exception("用户不存在"));
                var user = weChatOpen.NavClient;
                result.openid = openid;
                UserInfo userInfo = new UserInfo()
                {
                    id = user.ID.ToString(),
                    name = user.NAME,
                    nickName = user.NICK_NAME,
                    tel = user.TEL,
                    email = user.EMAIL,
                    idcard = user.ID_CARD,
                    addr = user.ADDR,
                    avatarUrl = user.AVATAURL
                };
                result.UserInfo = userInfo;
                #endregion
                #region 运维信息
                BaseFilter filter = new BaseFilter();
                filter.IgnoreOrgRule = true;
                filter.IsMultipleDb = true;
                var operations = this.GetEntities<T_MT_MAINTAIN_PERSON>(x => x.Nav_Approval.OPEN_ID == openid
               && x.IS_APPROVAL, filter, "Nav_Approval.Nav_Person");//已审核非离职人员
                if (operations != null && operations.Any())
                {
                    result.isOperator = true;
                    var tenantCodes = operations.Select(x => x.Nav_Approval.TENANT_CODE);
                    BaseFilter baseFilter = new BaseFilter();
                    baseFilter.IgnoreOrgRule = true;
                    baseFilter.IsSpecifyDb = true;
                    var tenants = this.GetEntities<T_OP_TENANT>(x => tenantCodes.Contains(x.CODE), baseFilter);
                    var TenantInfos = new List<WxTenant>();
                    foreach (var tenant in tenants)
                    {
                        var TenantInfo = new WxTenant()
                        {
                            tenantCode = tenant.CODE,
                            tenantName = tenant.NAME
                        };
                        TenantInfos.Add(TenantInfo);
                    }
                    result.TenantInfos = TenantInfos;
                }
                else
                    result.isOperator = false;
                #endregion
                return result;
            });
        }
        #endregion

        #region 获取待处理任务数
        [HttpGet, Route("GetTaskNumber")]
        public JsonActionResult<dynamic> GetTaskNumber(string openid)
        {
            return SafeExecute<dynamic>(() =>
            {
                BasePageFilter filter = new BasePageFilter();
                filter.PageIndex = 1;
                filter.Limit = 10;
                filter.IsMultipleDb = true;
                filter.IgnoreOrgRule = true;
                var operations = this.GetEntities<T_MT_MAINTAIN_PERSON>(x => x.Nav_Approval.OPEN_ID == openid
               &&x.IS_APPROVAL, filter, "Nav_Approval.Nav_Person");//已审核非离职人员
                var persons = operations.Select(x => x.Nav_Approval.RELATION_PERSON_ID);
                var jobs1 = this.GetOrderPageEntities<T_CP_CHARGING_ACTIVATE_JOB>(x => persons.Contains(x.CONCERT_PERSON_ID) &&
                x.ACTIVATE_STATUS == (int)MTActivateEnum.未完成, filter);//激活单
                var jobs2 = this.GetOrderPageEntities<T_MT_MAINTENANCE_PLAN>(x => persons.Contains(x.CONCERT_PERSON_ID) &&
                    x.MAINTENANCE_STATUS == (int)MTMaintenanceEnum.未解决, filter);//维修单
                var jobs3 = this.GetOrderPageEntities<T_MT_CURING_PLAN>(x => persons.Contains(x.CONCERT_PERSON_ID) &&
                    (x.CURING_STATUS == (int)MTCuringEnum.未保养|| x.CURING_STATUS == (int)MTCuringEnum.保养中), filter);//养护单
                List<TaskNumber> taskNumbers = new List<TaskNumber>();
                taskNumbers.Add(new TaskNumber() { orderType = 0, count = jobs1.TotalCount });
                taskNumbers.Add(new TaskNumber() { orderType = 1, count = jobs2.TotalCount });
                taskNumbers.Add(new TaskNumber() { orderType = 2, count = jobs3.TotalCount });
                return taskNumbers;
            });
        }
        #endregion

        #region 后台调用接口
        /// <summary>
        /// 获取计费规则
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        /// /// <summary>
        [HttpGet, Route("GetBillingRule")]
        public JsonActionResult<T_OP_BILLING_RULE> GetBillingRule()
        {
            return SafeExecute(() =>
            {
                BaseFilter filter = new BaseFilter();
                filter.IgnoreOrgRule = true;
                var rule = GetEntity<T_OP_BILLING_RULE>(null, filter, "Nav_Version", "Nav_Versions");
                return rule;
            });
        }
        #endregion
    }
}
