using Sugar.Enties;
using SqlSugar;
using System;
using System.Collections.Generic;
using Utils;
using System.Linq;
public class fdc_pm_ownerManager : DbContext<fdc_pm_owner>
{


    /// <summary>
    /// 获取租户信息
    /// </summary>
    /// <param name="phone"></param>
    /// <returns></returns>
    public Tenant GetTenant(string phone)
    {
        var model = Db.Queryable<fdc_pm_owner>().First(m => m.firsttel == phone && (m.typename == "个人租户" || m.typename == "企业租户"));
        if (model == null)
        {
            return null;
        }
        var sql = $" SELECT a.hcode,a.hname,a.hbarea area,b.nprice price FROM dbo.fdc_pm_ownerhouse a LEFT JOIN dbo.fdc_pm_rentcontract_stand b ON a.contractid=b.contractid  WHERE ownerid='{model.ownerid}' AND flag=1";
        var list = Db.SqlQueryable<House>(sql).ToList();
        var tennat = new Tenant();
        tennat.Name = model.firstman;
        tennat.Tel = model.firsttel;
        tennat.ContractPerson = model.firstman;
        tennat.Houses = list;
        return tennat;

    }
    /// <summary>
    /// 租户绑定  
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public BindTenantOut BindTenant(BindTenantInput input)
    {
        var output = new BindTenantOut();

        if (input.Type == "1")   //表示是绑定
        {
            var model = Db.Queryable<fdc_pm_owner>().First(m => m.firsttel == input.Phone && (m.typename == "个人租户" || m.typename == "企业租户"));
            if (model == null)
            {
                output.msg = "绑定失败";
                output.State = 3;
                return output;
            }
            if (model.weixinid.IsNullOrEmpty())
            {
                model.weixinid = input.WechatOpenID;
                Db.Updateable(model).UpdateColumns(m => m.weixinid).ExecuteCommand();

                output.msg = "绑定成功";
                output.State = 2;
                return output;
            }
            else
            {
                output.msg = "绑定失败";
                output.State = 3;
                return output;
            }
        }
        else if (input.Type == "2")   //判断是否绑定
        {
            var model = Db.Queryable<fdc_pm_owner>().First(m => m.firsttel == input.Phone && (m.typename == "个人租户" || m.typename == "企业租户"));
            if (model == null)
            {
                output.msg = "未绑定";
                output.State = 6;
                return output;
            }
            if (model.weixinid.IsNullOrEmpty())
            {

                output.msg = "未绑定";
                output.State = 6;
                return output;
            }
            else
            {
                output.msg = "已绑定";
                output.State = 1;
                return output;
            }
        }
        else   //解绑操作
        {
            var model = Db.Queryable<fdc_pm_owner>().First(m => m.firsttel == input.Phone && (m.typename == "个人租户" || m.typename == "企业租户"));
            if (model == null)
            {
                output.msg = "解绑失败";
                output.State = 5;
                return output;

            }
            if (model.weixinid.IsNullOrEmpty())
            {
                output.msg = "解绑失败";
                output.State = 5;
                return output;

            }
            else
            {

                model.weixinid = "";
                Db.Updateable(model).UpdateColumns(m => m.weixinid).ExecuteCommand();
                output.msg = "解绑成功";
                output.State = 4;
                return output;
            }
        }
    }
    /// <summary>
    /// 获取缴费信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public List<PaymentInfo> GetPaymentInfo(PaymentInput input)
    {
        var sql = $"SELECT a.firstman rentname,b.hname,b.hcode,b.hbarea harea,CONVERT(VARCHAR(10),b.bdate,120) startdate,CONVERT(VARCHAR(10),b.edate,120) enddate FROM dbo.fdc_pm_owner a INNER JOIN fdc_pm_ownerhouse b ON a.ownerid=b.ownerid  WHERE a.weixinid='{input.WechatOpenID}' AND  (a.typename='个人租户' OR a.typename='企业租户')   AND b.flag=1";
        var list = Db.SqlQueryable<PaymentInfo>(sql).ToList();
        foreach (var paymentInfo in list)
        {
            sql = $"SELECT b.billitemname faretype,nneedpaymny amount,a.nrevmny ReceivedAmount,isnull( c.dbilldate,'') faredate,c.Revpeoioddate   FROM fdc_pm_fare_b a INNER JOIN fdc_pm_billsitem b ON a.billitemcode=b.billitemcode LEFT JOIN  (SELECT MAX(CONVERT(VARCHAR(10),rf.dbilldate,120)) dbilldate,rfb.farerowid,rfb.billitemcode,rfb.Revpeoioddate FROM fdc_pm_revfare rf  INNER JOIN fdc_pm_revfare_b rfb ON rf.pk_revfarecode=rfb.pk_revfarecode  GROUP BY rfb.farerowid,rfb.billitemcode,rfb.Revpeoioddate) c ON a.farerowid=c.farerowid AND a.billitemcode=c.billitemcode  WHERE a.hcode='{paymentInfo.HCode}'   AND ( a.flag=1 OR a.flag IS NULL)";
            if (input.StartDate.IsNotNullAndEmpty())
            {
                sql += $" and c.dbilldate>='{input.StartDate}'";
            }
            if (input.EndDate.IsNotNullAndEmpty())
            {
                sql += $" and c.dbilldate<'{Convert.ToDateTime(input.EndDate).AddDays(1).ToString("yyyy-MM-dd")}'";
            }
            var listDetail = Db.SqlQueryable<PayMentDetail>(sql).ToList();

            paymentInfo.PayMentDetails = listDetail;
        }
        return list;
    }


    /// <summary>
    /// 判断用户openid 是否存在
    /// </summary>
    /// <param name="openid"></param>
    /// <returns></returns>
    public bool CheckWxOpenId(string openid)
    {
        var sql = $"SELECT ownerid  FROM dbo.fdc_pm_owner   WHERE weixinid='{openid}'";
        var model = Db.SqlQueryable<dynamic>(sql).First();
        if (model != null)
        {
            return true;
        }
        return false;

    }

    /// <summary>
    /// 根据openid 获取用户信息
    /// </summary>
    /// <param name="openid"></param>
    /// <returns></returns>
    public OwnerDTO LoginOwnerByOpenId(string openid)
    {
        var sql = $"SELECT a.ownerid,a.ownername,c.hcode,c.hname,d.bcode,d.bname,a.tel FROM dbo.fdc_pm_owner a INNER JOIN dbo.fdc_pm_ownerhouse b ON a.ownerid=b.ownerid INNER JOIN fdc_pm_house c ON b.hcode=c.hcode INNER JOIN dbo.fdc_pm_build d ON c.bcode=d.bcode WHERE a.weixinid='{openid}'";
        var model = Db.Ado.SqlQuerySingle<OwnerDTO>(sql);
        return model;
    }


    /// <summary>
    /// 更新openid状态
    /// </summary>
    /// <param name="vcarcode"></param>
    /// <param name="carstatus"></param>
    /// <returns></returns>
    public bool Upfdc_pm_ownerOpenId(string phone, string openId)
    {
        Db.BeginTran();
        try
        {
            var fdc_pm_ownerinfo = fdc_pm_ownerDb.GetSingle(m => m.tel.Contains(phone));
            fdc_pm_ownerinfo.weixinid = openId;


            Db.Updateable(fdc_pm_ownerinfo).ExecuteCommand();


            Db.CommitTran();
            return true;
        }
        catch (Exception ex)
        {
            Db.RollbackTran();
            //logger.Error(ex);
            throw;
        }
    }


}