using Sugar.Enties;
using SqlSugar;
using System;
using System.Collections.Generic;

public class fdc_pm_housemeterManager : DbContext<fdc_pm_housemeter>
{

    //当前类已经继承了 DbContext增、删、查、改的方法

    //这里面写的代码不会给覆盖,如果要重新生成请删除 fdc_pm_housemeterManager.cs


    #region 教学方法
    /// <summary>
    /// 如果DbContext中的增删查改方法满足不了你，你可以看下具体用法
    /// </summary>
    public void Study()
    {

        /*********查询*********/

        var data1 = fdc_pm_housemeterDb.GetById(1);//根据ID查询
        var data2 = fdc_pm_housemeterDb.GetList();//查询所有
        var data3 = fdc_pm_housemeterDb.GetList(it => 1 == 1);  //根据条件查询  
        //var data4 = fdc_pm_housemeterDb.GetSingle(it => 1 == 1);//根据条件查询一条,如果超过一条会报错

        var p = new PageModel() { PageIndex = 1, PageSize = 2 };// 分页查询
        var data5 = fdc_pm_housemeterDb.GetPageList(it => 1 == 1, p);
        Console.Write(p.PageCount);//返回总数

        var data6 = fdc_pm_housemeterDb.GetPageList(it => 1 == 1, p, it => SqlFunc.GetRandom(), OrderByType.Asc);// 分页查询加排序
        Console.Write(p.PageCount);//返回总数

        List<IConditionalModel> conModels = new List<IConditionalModel>(); //组装条件查询作为条件实现 分页查询加排序
        conModels.Add(new ConditionalModel() { FieldName = typeof(fdc_pm_housemeter).GetProperties()[0].Name, ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
        var data7 = fdc_pm_housemeterDb.GetPageList(conModels, p, it => SqlFunc.GetRandom(), OrderByType.Asc);

        fdc_pm_housemeterDb.AsQueryable().Where(x => 1 == 1).ToList();//支持了转换成queryable,我们可以用queryable实现复杂功能

        //我要用事务
        var result = Db.Ado.UseTran(() =>
         {
             //写事务代码
         });
        if (result.IsSuccess)
        {
            //事务成功
        }

        //多表查询地址 http://www.codeisbug.com/Doc/8/1124



        /*********插入*********/
        var insertData = new fdc_pm_housemeter() { };//测试参数
        var insertArray = new fdc_pm_housemeter[] { insertData };
        fdc_pm_housemeterDb.Insert(insertData);//插入
        fdc_pm_housemeterDb.InsertRange(insertArray);//批量插入
        var id = fdc_pm_housemeterDb.InsertReturnIdentity(insertData);//插入返回自增列
        fdc_pm_housemeterDb.AsInsertable(insertData).ExecuteCommand();//我们可以转成 Insertable实现复杂插入



        /*********更新*********/
        var updateData = new fdc_pm_housemeter() { };//测试参数
        var updateArray = new fdc_pm_housemeter[] { updateData };//测试参数
        fdc_pm_housemeterDb.Update(updateData);//根据实体更新
        fdc_pm_housemeterDb.UpdateRange(updateArray);//批量更新
        //fdc_pm_housemeterDb.Update(it => new fdc_pm_housemeter() { Name = "a", CreateTime = DateTime.Now }, it => it.id==1);// 只更新Name列和CreateTime列，其它列不更新，条件id=1
        fdc_pm_housemeterDb.AsUpdateable(updateData).ExecuteCommand();



        /*********删除*********/
        var deldata = new fdc_pm_housemeter() { };//测试参数
        fdc_pm_housemeterDb.Delete(deldata);//根据实体删除
        fdc_pm_housemeterDb.DeleteById(1);//根据主键删除
        fdc_pm_housemeterDb.DeleteById(new int[] { 1, 2 });//根据主键数组删除
        fdc_pm_housemeterDb.Delete(it => 1 == 2);//根据条件删除
        fdc_pm_housemeterDb.AsDeleteable().Where(it => 1 == 2).ExecuteCommand();//转成Deleteable实现复杂的操作
    }
    #endregion


    /// <summary>
    /// 获取房产详细仪表
    /// </summary>
    /// <param name="staffcode"></param>
    /// <returns></returns>
    public List<HouseMeterDTO> GetHouseMeter(string staffcode, string bcode, string metertypename, int pageNumber, int pageSize)
    {
        int startindex = (pageNumber - 1) * pageSize + 1; int limitindex = (pageNumber - 1) * pageSize + pageSize;
        List<HouseMeterDTO> dto = new List<HouseMeterDTO>();
        var sql = $@"select * from ( 
				select   ROW_NUMBER() OVER(ORDER BY b.hcode ) AS RowNumber,b.hcode,b.hname,COUNT(*) OVER(PARTITION BY '') AS TotalCount
				 from fdc_pm_build a
                    INNER JOIN dbo.fdc_pm_house b on a.bcode = b.bcode
                    inner join fdc_pm_userinmanagementsec u on a.pk_managementsecid = u.pk_managementsecid
                    where u.staffcode ='{staffcode}' AND a.bcode='{bcode}' group BY b.hcode,b.hname) houseList
					where  RowNumber between {startindex} and  {limitindex}";
        var hList = Db.Ado.SqlQuery<House>(sql);

        foreach (House h in hList)
        {
            var strsql = $@"SELECT r.ownername,edate= CONVERT(varchar, z.edate, 120 ),a.pk_meterid, a.metername,b.metertypename, a.hcode, c.hname,a.amount
                    FROM fdc_pm_housemeter a
                    INNER JOIN fdc_pm_metertype b on a.metertype = b.pk_metertypeid AND a.CostRule = 0
                    INNER JOIN fdc_pm_house c on a.hcode = c.hcode
                        inner join fdc_pm_ownerhouse s on c.hcode = s.hcode
                    inner join fdc_pm_owner r on s.ownerid = r.ownerid
                    INNER JOIN fdc_pm_build e on e.bcode = c.bcode
                    INNER JOIN fdc_pm_userinmanagementsec f on f.pk_managementsecid = e.pk_managementsecid
                    left join(select max(edate) as edate,pk_meterid from fdc_pm_meterrecord_b mrb inner join fdc_pm_meterrecord mr on mrb.billno = mr.billno group by pk_meterid) z on a.pk_meterid = z.pk_meterid
                    WHERE f.staffcode = '{staffcode}'  AND c.hcode ='{h.hcode}' and b.metertypename='{metertypename}'";
            var meterList = Db.Ado.SqlQuery<Meter>(strsql);

            if (meterList.Count > 0)
            {
                HouseMeterDTO hm = new HouseMeterDTO();
                hm.hcode = h.hcode;
                hm.hname = h.hname;
                hm.totalcount = h.totalcount;
                hm.meters = meterList;
                dto.Add(hm);
            }

        }
        return dto;
    }



}