using ASHermed.AdminInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Repository.MySql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ASHermed.SinoInterface.Api.MySqlRepository
{

    public class OnlineOrderRepository : BaseRepositoryToASHermed_SinoInterface<Online_Order>, IOnlineOrderRepository
    {
        public int CreateOrder(Online_Order order)
        {
            order.CouponId = 1314;
            StringBuilder str = new StringBuilder();
            str.Append("insert into Online_Order ");
            str.Append(@"(OrderNo,PatId,AptId,OrderStatus,CreateTime,DocId,AptPrice,AptTime,AptType,IsUseCoupon,CouponId,CouponPrice,IsInsuranceUser,InsuranceId,InsuranceStatus,PayPrice,PayWay,PayTime,Remark,UpdateTime,UpdateUser,IsEnglish) ");
            str.Append(" values ");
            str.Append(@"(@OrderNo,@PatId,@AptId,@OrderStatus,@CreateTime,@DocId,@AptPrice,@AptTime,@AptType,@IsUseCoupon,@CouponId,@CouponPrice,@IsInsuranceUser,@InsuranceId,@InsuranceStatus,@PayPrice,@PayWay,@PayTime,@Remark,@UpdateTime,@UpdateUser,@IsEnglish); ");
            var parms = new Dictionary<string, object>();
            parms.Add("@OrderNo", order.OrderNo);
            parms.Add("@PatId", order.PatId);
            parms.Add("@AptId", order.AptId);
            parms.Add("@OrderStatus", order.OrderStatus);
            parms.Add("@CreateTime", order.CreateTime);
            parms.Add("@DocId", order.DocId);
            parms.Add("@AptPrice", order.AptPrice);
            parms.Add("@AptTime", order.AptTime);
            parms.Add("@AptType", order.AptType);
            parms.Add("@IsUseCoupon", order.IsUseCoupon);
            parms.Add("@CouponId", order.CouponId);
            parms.Add("@CouponPrice", order.CouponPrice);
            parms.Add("@IsInsuranceUser", order.IsInsuranceUser);
            parms.Add("@InsuranceId", order.InsuranceId);
            parms.Add("@InsuranceStatus", order.InsuranceStatus);
            parms.Add("@PayPrice", order.PayPrice);
            parms.Add("@PayWay", order.PayWay);
            parms.Add("@PayTime", order.PayTime);
            parms.Add("@Remark", order.Remark);
            parms.Add("@UpdateTime", order.UpdateTime);
            parms.Add("@UpdateUser", order.UpdateUser);
            parms.Add("@IsEnglish", order.IsEnglish);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int PerfPayInfoByNo(string orderNo, string PayType, string payTime, string tradeNo, string tradeStatus)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update Online_Order set ");
            str.Append(@"OrderStatus=@OrderStatus,
                            PayTime=@PayTime,
                            TradeNo=@TradeNo,
                            PayWay=@PayWay ");
            str.Append(@" where OrderNo=@OrderNo");
            var parms = new Dictionary<string, object>();
            parms.Add("@OrderNo", orderNo);
            parms.Add("@OrderStatus", tradeStatus);
            parms.Add("@PayTime", payTime);
            parms.Add("@PayWay", PayType);
            parms.Add("@TradeNo", tradeNo);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int AppPerfPayInfoByNo(string orderNo, string payTime, string tradeNo, string tradeStatus)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update Online_Order set ");
            str.Append(@"OrderStatus=@OrderStatus,
                            PayTime=@PayTime,
                            TradeNo=@TradeNo ");
            str.Append(@" where OrderNo=@OrderNo");
            var parms = new Dictionary<string, object>();
            parms.Add("@OrderNo", orderNo);
            parms.Add("@OrderStatus", tradeStatus);
            parms.Add("@PayTime", payTime);
            parms.Add("@TradeNo", tradeNo);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public PageListModel<OrderListModel> GetOrderList(OrderListReq req, List<int> patIds)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select  SQL_CALC_FOUND_ROWS OrderNo,AptType,AptId,payprice as Price,OrderStatus,CreateTime,IsInsuranceUser from online_order  where PatId in @patIds ");

            if (!string.IsNullOrEmpty(req.OrderStatus) && req.OrderStatus != "0")
            {
                var arr = req.OrderStatus.Split(',');
                selectSql.Append(@" and OrderStatus in @OrderStatus");
                parms.Add("@OrderStatus", arr.ToList());
            }

            selectSql.Append(@" order by CREATETIME desc limit @pageIndex,@pageSize");//GROUP BY T.ID 

            parms.Add("@pageIndex", (req.PageIndex - 1) * req.PageSize);
            parms.Add("@pageSize", req.PageSize);
            parms.Add("@patIds", patIds);
            var result = QueryPageList<OrderListModel>(selectSql.ToString(), "select FOUND_ROWS() AS Count", parms);
            PageListModel<OrderListModel> res = new PageListModel<OrderListModel>();
            res.PageList = result.Data.ToList();
            res.TotalCount = int.Parse(result.Count.ToString());
            return res;
        }
        public OrderDetailModel GetOrderDetail(string orderNo, int language)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select o.OrderNo,o.PatId,p.PAT_NAME as PatName,o.OrderStatus,o.DocId,o.AptPrice,o.AptId,o.AptTime,o.AptType,o.IsUseCoupon, o.CouponId,o.CouponPrice,o.IsInsuranceUser,o.InsuranceId,o.InsuranceStatus,o.PayPrice,o.CreateTime,d.LIST_IMAGE AS ListImage,oapt.`Status`,oapt.LinKingAptStatus,oapt.Description,o.PayWay,o.PayTime,tg.GroupId,oapt.ApplyUserId ");
            if (language == 1)
            {
                selectSql.Append(@",d.cn_name as DocName ");
            }
            else
            {
                selectSql.Append(@",d.en_name as DocName ");
            }
            selectSql.Append(@" from online_order o LEFT JOIN pub_pat_info p on o.PatId = p.ID 
                                
                                LEFT JOIN dic_doctor d on o.DocId = d.id 
                                LEFT JOIN online_apt_info oapt ON o.AptId = oapt.Id
                                LEFT JOIN tencent_group_record tg on tg.PatId = oapt.PatId and tg.DocId = oapt.DocId and tg.UserId = oapt.ApplyUserId
                                where d.IS_DELETED = 0  and o.OrderNo = @OrderNo ");//and p.IS_DELETED = 0 
            //LEFT JOIN pub_map_user_pat up on p.id=up.pat_id and up.IS_DELETED = 0
            parms.Add("@OrderNo", orderNo);
            var result = Query<OrderDetailModel>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        public List<Online_Order> GetAllOrder()
        {
            var sql = @" Select Id,OrderNo,PatId From online_order ";
            return Query<Online_Order>(sql).ToList();
        }

        public OrderDetailModel GetOrderDetailForAptId(string aptId, int language)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select o.OrderNo,o.PatId,p.PAT_NAME as PatName,o.OrderStatus,o.DocId,o.AptPrice,o.AptTime,o.AptType,o.IsUseCoupon, o.CouponId,o.CouponPrice,o.IsInsuranceUser,o.InsuranceId,o.InsuranceStatus,o.PayPrice,o.CreateTime,d.LIST_IMAGE AS ListImage,oapt.Description,o.PayWay,o.PayTime ");
            if (language == 1)
            {
                selectSql.Append(@",d.cn_name as DocName,dept.CN_NAME AS DeptName ");
            }
            else
            {
                selectSql.Append(@",d.en_name as DocName,dept.EN_NAME AS DeptName ");
            }
            selectSql.Append(@" from online_order o LEFT JOIN pub_pat_info p on o.PatId = p.ID 
                                LEFT JOIN dic_doctor d on o.DocId = d.id 
                                LEFT JOIN online_apt_info oapt ON o.AptId = oapt.Id
                                Left JOIN dic_dept dept ON dept.ID=oapt.DeptId
                                where d.IS_DELETED = 0 and p.IS_DELETED = 0 and AptId = @AptId AND (o.AptType=1 OR o.AptType=2) ");

            parms.Add("@AptId", aptId);
            var result = Query<OrderDetailModel>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        public OrderDetailModel GetOrderDetailForPrescriptionAptId(int aptId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select o.OrderNo,o.PatId,p.PAT_NAME as PatName,o.OrderStatus,o.DocId,o.AptPrice,o.AptTime,o.AptType,o.IsUseCoupon, o.CouponId,o.CouponPrice,o.IsInsuranceUser,o.InsuranceId,o.InsuranceStatus,o.PayPrice,o.CreateTime,oapt.RECEIPT_REMARK AS Description,o.PayWay,o.PayTime ");
            selectSql.Append(@" from online_order o 
                                LEFT JOIN pub_pat_info p on o.PatId = p.ID 
                                LEFT JOIN out_internet_prescription_info oapt ON o.AptId = oapt.Id
                                where p.IS_DELETED = 0 and AptId = @AptId AND o.AptType=3 and oapt.IsDelete=0 ");

            parms.Add("@AptId", aptId);
            var result = Query<OrderDetailModel>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        public Online_Order GetOrderByNo(string orderNo)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from online_order 
                                where OrderNo = @OrderNo ");

            parms.Add("@OrderNo", orderNo);
            var result = Query<Online_Order>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        public int UpdateOrder(string orderNo, int status)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update Online_Order set ");
            str.Append(@"OrderStatus=@OrderStatus ");
            str.Append(@" where OrderNo=@OrderNo");
            var parms = new Dictionary<string, object>();
            parms.Add("@OrderNo", orderNo);
            parms.Add("@OrderStatus", status);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int UpdateCFOrder(int prescriptionId, int status)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update Online_Order set ");
            str.Append(@"OrderStatus=@OrderStatus ");
            str.Append(@" where AptType=3 and AptId=@AptId");
            var parms = new Dictionary<string, object>();
            parms.Add("@AptId", prescriptionId);
            parms.Add("@OrderStatus", status);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int UpdateOrderPayWay(string orderNo, string payway)
        {
            var sql = @" update Online_Order set PayWay=@PayWay WHERE OrderNo=@OrderNo ";
            return Execute(sql, new { OrderNo = orderNo, PayWay = payway });
        }

        public int CommentOrder(OrderCommentReq req)
        {
            StringBuilder str = new StringBuilder();
            str.Append("insert into online_order_comment ");
            str.Append(@"(OrderNo,DocId,Star,Comment,UserId,CreateUser,CreateTime,IsAnonymous) ");
            str.Append(" values ");
            str.Append(@"(@OrderNo,@DocId,@Star,@Comment,@UserId,@CreateUser,@CreateTime,@IsAnonymous); ");
            var parms = new Dictionary<string, object>();
            parms.Add("@OrderNo", req.OrderNo);
            parms.Add("@DocId", req.DocId);
            parms.Add("@Star", req.Star);
            parms.Add("@Comment", req.Comment);
            parms.Add("@UserId", req.UserId);
            parms.Add("@CreateUser", req.CreateUser);
            parms.Add("@CreateTime", DateTime.Now);
            parms.Add("@IsAnonymous", req.IsAnonymous);

            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int InsuranceOrderSign(InsuranceOrderSignReq req)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update Online_Order set ");
            str.Append(@"OrderStatus=@OrderStatus, ");
            str.Append(@"InsuranceSign=@InsuranceSign, ");
            str.Append(@"UpdateTime=@UpdateTime ");
            str.Append(@" where OrderNo=@OrderNo");
            var parms = new Dictionary<string, object>();
            parms.Add("@OrderNo", req.OrderNo);
            parms.Add("@OrderStatus", 11);
            parms.Add("@InsuranceSign", req.InsuranceSign);
            parms.Add("@UpdateTime", DateTime.Now);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public List<string> GetCancelOrders()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select orderno from  online_order where (AptId is not null and OrderStatus=1 and TIMESTAMPDIFF(MINUTE, CreateTime, now()) > 15 AND AptType != 3) or (AptId is not null and OrderStatus=1 and TIMESTAMPDIFF(HOUR, CreateTime, now()) > 3 AND AptType = 3)");
            //获取预约单超15分钟待支付的单子 和 超过3小时未付款的处方单
            var result = Query<string>(selectSql.ToString(), parms);
            return result?.ToList();
        }


        public string GetGroupOrderNo(string groupId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select orderno from tencent_group_record where groupid = @groupid");
            parms.Add("@groupid", groupId);
            var result = Query<string>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        public List<Tencent_Group_Record> GetAllTencentGroup()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from tencent_group_record where `Status` = 1");
            var result = Query<Tencent_Group_Record>(selectSql.ToString(), parms);
            return result?.ToList();
        }
        public int UpdateGroupUserId(int id ,int userId)
        {
            var sql = @" Update tencent_group_record set userId=@userId where id=@id ";
            return Execute(sql, new { id = id, userId = userId });
        }


        public Online_Order_Comment GetOrderComment(string orderNo)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from online_order_comment where orderNo = @orderNo");
            parms.Add("@orderNo", orderNo);
            var result = Query<Online_Order_Comment>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        public int UpdateComment(OrderCommentReq req)
        {
            var sql = @" Update online_order_comment set Star=@Star,Comment=@Comment where OrderNo=@OrderNo ";
            return Execute(sql, new { Star = req.Star, Comment = req.Comment, OrderNo = req.OrderNo });
        }

        /// <summary>
        /// job获取最后15分钟提示的未支付订单
        /// </summary>
        /// <returns></returns>
        public List<Online_Order> GetNoticeOrders()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from online_order where AptType = 3 and OrderStatus =1 and TIMESTAMPDIFF(MINUTE, CreateTime, now()) >120  and TIMESTAMPDIFF(MINUTE, CreateTime, now())<130");

            var result = Query<Online_Order>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        /// <summary>
        /// job获取理赔单超24小时未签字的订单
        /// </summary>
        /// <returns></returns>
        public List<Online_Order> GetSginNoticeOrders()
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from online_order where IsInsuranceUser =1 and AptType = 2 and OrderStatus =20 and TIMESTAMPDIFF(HOUR, CreateTime, now()) >24");

            var result = Query<Online_Order>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        public List<Online_Order> GetOrderByStatus(int userId, int status)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from online_order where OrderStatus = @OrderStatus and PatId in (select PAT_ID from pub_map_user_pat where USER_ID =@USER_ID)");
            parms.Add("@OrderStatus", status);
            parms.Add("@USER_ID", userId);
            var result = Query<Online_Order>(selectSql.ToString(), parms);
            return result?.ToList();
        }

        public AptInfo CheckMySoonApt(int userId, int language)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            if (language == 1)
            {
                selectSql.Append(@"select a.PatId,p.PAT_NAME as PatName,a.DocId,d.CN_NAME as DocName,d.LIST_IMAGE as DocImg,a.AptTime,b.orderno,b.AptType ");
            }
            else
            {
                selectSql.Append(@"select a.PatId,p.PAT_NAME as PatName,a.DocId,d.EN_NAME as DocName,d.LIST_IMAGE as DocImg,a.AptTime,b.orderno,b.AptType ");
            }
            selectSql.Append(@" from online_apt_info a inner join online_order b on a.Id = b.AptId 
                                left join pub_pat_info p on p.ID = a.PatId
                                LEFT JOIN dic_doctor d on d.ID = a.DocId
                                where (`STATUS` = 4 or `STATUS` = 2) and TIMESTAMPDIFF(MINUTE, now(), a.AptTime) > 0 and TIMESTAMPDIFF(MINUTE, now(), a.AptTime) <= 15 and a.PatId in
                                 (SELECT PAT_ID FROM  pub_map_user_pat where USER_ID=@userId)");
            parms.Add("@userId", userId);
            var result = Query<AptInfo>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }


        public string CheckMySoonPre(int userId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select b.APPT_NUMBER as OrderNo from online_order a
	INNER JOIN out_internet_prescription_info b ON a.AptId = b.id  where b.IsDelete=0 and AptType = 3 and OrderStatus =1 and TIMESTAMPDIFF(MINUTE, CreateTime, now()) >0 and a.PatId in
 (SELECT PAT_ID FROM  pub_map_user_pat where USER_ID=@userId)");
            parms.Add("@userId", userId);
            var result = Query<string>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }

        /// <summary>
        /// 获取用户待签字订单
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Online_Order GetUserSignOrders(int userId)
        {
            var selectSql = new StringBuilder();
            var parms = new Dictionary<string, object>();
            selectSql.Append(@"select * from online_order where PatId in (select PAT_ID from Pub_Map_User_Pat where USER_ID = @userId and IS_DELETED = 0) and OrderStatus = 20 and IsInsuranceUser = 1 and OrderNo like 'GH%'");
            parms.Add("@userId", userId);
            var result = Query<Online_Order>(selectSql.ToString(), parms);
            return result?.FirstOrDefault();
        }



    }
}
