using Infrastructure;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.DroneSsnydManage.Export;
using OpenAuth.App.ServiceApp.DroneSsnydManage.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.DroneSsnydManage
{
    public class DroneSsnyApp : SqlSugarBaseApp<DroneSsnyd, SugarDbContext>
    {
        private readonly ISqlSugarClient _client;
        public DroneSsnyApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<DroneSsnyd> repository, ISqlSugarClient client, IAuth auth)
            : base(unitWork, repository, auth)
        {
            _client = client;
        }

        /// <summary>
        /// 到期预警
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageInfo<List<DroneSsnyd>> TimeoutWarning(string xiangmumc, string countyid, string streetid,
            string xiangmuno, string xiangmuyt,
            int pageIndex, int pageSize)
        {
            int totalCount = 0;
            var endTime = DateTime.Now.AddMonths(2);

            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();

            var list = base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), a => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), a => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), a => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), a => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), a => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .Where(a => a.end_time <= endTime && a.end_time > DateTime.Now)
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToPageList(pageIndex, pageSize, ref totalCount);

            return new PageInfo<List<DroneSsnyd>>
            {
                Items = list,
                Total = totalCount
            };
        }


        /// <summary>
        /// 超期报警
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageInfo<List<DroneSsnyd>> TimeOutAlarmList(string xiangmumc, string countyid, string streetid,
            string xiangmuno, string xiangmuyt,
            int pageIndex, int pageSize)
        {
            int totalCount = 0;
            var endTime = DateTime.Now;

            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();

            var list = base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), a => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), a => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), a => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), a => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), a => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .Where(a => a.end_time < endTime)
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToPageList(pageIndex, pageSize, ref totalCount);

            return new PageInfo<List<DroneSsnyd>>
            {
                Items = list,
                Total = totalCount
            };
        }

        /// <summary>
        /// 历史项目
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public PageInfo<List<DroneSsnyd>> HistoryProject(DroneSsnyAppPageReq req)
        {
            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();
            var totalCount = 0;
            var list = Repository.AsQueryable()
                .Where(a => a.handle_status_id == 99)
                .WhereIF(!string.IsNullOrEmpty(req.streetid), a => a.streetid == req.streetid)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_yt), a => a.xiangmu_yt == req.xiangmu_yt)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_no), a => a.xiangmu_no.Contains(req.xiangmu_no))
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_name), a => a.xiangmu_name.Contains(req.xiangmu_name))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToPageList(req.page, req.limit, ref totalCount);
            return new PageInfo<List<DroneSsnyd>>
            {
                Items = list,
                Total = totalCount
            };
        }

        /// <summary>
        /// 项目变更
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public PageInfo<List<DroneSsnyd>> ProjectChange(DroneSsnyAppPageReq req)
        {
            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();
            var totalCount = 0;
            var list = Repository.AsQueryable()
                .Where(a => a.handle_status_id != 99)
                .WhereIF(!string.IsNullOrEmpty(req.streetid), a => a.streetid == req.streetid)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_yt), a => a.xiangmu_yt == req.xiangmu_yt)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_no), a => a.xiangmu_no.Contains(req.xiangmu_no))
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_name), a => a.xiangmu_name.Contains(req.xiangmu_name))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToPageList(req.page, req.limit, ref totalCount);
            return new PageInfo<List<DroneSsnyd>>
            {
                Items = list,
                Total = totalCount
            };
        }

        public List<DroneSsnydExport> HistoryProjectList(DroneSnnyAppReq req)
        {
            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();
            var list = Repository.AsQueryable()
                .Where(a => a.handle_status_id == 99)
                .WhereIF(!string.IsNullOrEmpty(req.streetid), a => a.streetid == req.streetid)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_yt), a => a.xiangmu_yt == req.xiangmu_yt)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_no), a => a.xiangmu_no.Contains(req.xiangmu_no))
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_name), a => a.xiangmu_name.Contains(req.xiangmu_name))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .Select(
                    a => new DroneSsnydExport()
                    {
                        xiangmu_no = a.xiangmu_no,
                        xiangmu_name = a.xiangmu_name,
                        streetname = a.streetname,
                        communityname = a.communityname,
                        quanliren = a.quanliren,
                        xingzhengquhua = a.xingzhengquhua,
                        beian_no = a.beian_no,
                        start_time = a.start_time,
                        end_time = a.end_time,
                        xiangmu_yt = a.xiangmu_yt,
                        shengchan_area = a.shengchan_area,
                        fuzhu_area = a.fuzhu_area,
                        shenqing_area = a.shenqing_area,
                        handle_status_name = a.handle_status_name,
                        xiafatime = a.xiafatime
                    })
                .ToList();
            return list;
        }

        public List<DroneSsnydExport> ProjectChangeExport(DroneSnnyAppReq req)
        {
            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();
            var list = Repository.AsQueryable()
                .Where(a => a.handle_status_id != 99)
                .WhereIF(!string.IsNullOrEmpty(req.streetid), a => a.streetid == req.streetid)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_yt), a => a.xiangmu_yt == req.xiangmu_yt)
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_no), a => a.xiangmu_no.Contains(req.xiangmu_no))
                .WhereIF(!string.IsNullOrEmpty(req.xiangmu_name), a => a.xiangmu_name.Contains(req.xiangmu_name))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .Select(
                    a => new DroneSsnydExport()
                    {
                        xiangmu_no = a.xiangmu_no,
                        xiangmu_name = a.xiangmu_name,
                        streetname = a.streetname,
                        communityname = a.communityname,
                        quanliren = a.quanliren,
                        xingzhengquhua = a.xingzhengquhua,
                        beian_no = a.beian_no,
                        start_time = a.start_time,
                        end_time = a.end_time,
                        xiangmu_yt = a.xiangmu_yt,
                        shengchan_area = a.shengchan_area,
                        fuzhu_area = a.fuzhu_area,
                        shenqing_area = a.shenqing_area,
                        handle_status_name = a.handle_status_name,
                        xiafatime = a.xiafatime
                    })
                .ToList();
            return list;
        }


        #region 导出

        //超期预警
        public List<DroneSsnyd> TimeoutWarningExport(string xiangmumc, string countyid, string streetid,
            string xiangmuno, string xiangmuyt)
        {
            var endTime = DateTime.Now.AddMonths(2);

            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();

            var list = base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), a => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), a => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), a => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), a => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), a => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .Where(a => a.end_time <= endTime && a.end_time > DateTime.Now)
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToList();

            return list;
        }

        /// <summary>
        /// 超期报警
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<DroneSsnyd> TimeOutAlarmExport(string xiangmumc, string countyid, string streetid, string xiangmuno,
            string xiangmuyt)
        {
            var endTime = DateTime.Now;

            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();
            var list = base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), a => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), a => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), a => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), a => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), a => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .Where(a => a.end_time < endTime)
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToList();

            return list;
        }

        /// <summary>
        /// 项目列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<DroneSsnyd> GetDronssnydExportList(string xiangmumc, string countyid, string streetid,
            string xiangmuno, DateTime? hechatimebegin, DateTime? hechatimeend, string xiangmuyt,int? status)
        {
            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }
            bool issystem = _auth.IsSystem();

            var list = base.Repository.AsQueryable()
                .Where(a => a.handle_status_id != 0 && a.handle_status_id != null)
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), a => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), a => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), a => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), a => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), a => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .WhereIF(status!=null,a=>a.handle_status_id== status)
                .LeftJoin<DroneSsnydRcjg>((a, d) => a.Id == d.ssnyd_id)
                .WhereIF(hechatimebegin != null && hechatimeend != null,
                (a, d) => (a.hechatime_kg != null && a.hechatime_kg < hechatimeend && a.hechatime_kg >= hechatimebegin)
                || (a.hechatime_jz != null && a.hechatime_jz < hechatimeend && a.hechatime_jz >= hechatimebegin)
                || (a.hechatime_wg != null && a.hechatime_wg < hechatimeend && a.hechatime_wg >= hechatimebegin)
                || (a.hechatime_wgzg != null && a.hechatime_wgzg < hechatimeend && a.hechatime_wgzg >= hechatimebegin)
                || (a.hechatime_jzzg != null && a.hechatime_jzzg < hechatimeend && a.hechatime_jzzg >= hechatimebegin)
                || (a.hechatime_kgzg != null && a.hechatime_kgzg < hechatimeend && a.hechatime_kgzg >= hechatimebegin)
                || (d.hechatime_rc != null && d.hechatime_rc < hechatimeend && d.hechatime_rc >= hechatimebegin)
                || (d.hechatime_rczg != null && d.hechatime_rczg < hechatimeend && d.hechatime_rczg >= hechatimebegin)
                || (d.hechatime_rcfh != null && d.hechatime_rcfh < hechatimeend && d.hechatime_rcfh >= hechatimebegin))
                .OrderBy((a, d) => a.end_time, OrderByType.Desc)
                .Select((a, d) => a)
                .Distinct()
                .ToList();

            return list;
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="list"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public Response<MemoryStream> ListToExcel(List<DroneSsnyd> list, List<string> headers)
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();

                #region 内容样式

                IFont font1 = workbook.CreateFont(); //创建一个字体样式对象
                font1.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                //font1.Boldweight = short.MaxValue;//字体加粗
                font1.FontHeightInPoints = 12; //字体大小
                ICellStyle style = workbook.CreateCellStyle(); //创建样式对象
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.Alignment = HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.SetFont(font1); //将字体样式赋给样式对象 
                style.WrapText = true;

                #endregion

                #region 标题样式

                IFont font = workbook.CreateFont(); //创建一个字体样式对象
                font.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                font.Boldweight = (short)FontBoldWeight.Bold; //字体加粗
                font.FontHeightInPoints = 12; //字体大小
                ICellStyle style1 = workbook.CreateCellStyle(); //创建样式对象
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.Alignment = HorizontalAlignment.Center;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.SetFont(font); //将字体样式赋给样式对象 

                #endregion

                #region 创建表头

                IRow rowHeader = sheet.CreateRow(0);
                rowHeader.Height = 20 * 30;
                for (int i = 0; i < headers.Count; i++)
                {
                    var header = headers[i];
                    rowHeader.CreateCell(i);
                    rowHeader.Cells[i].CellStyle = style1;
                    rowHeader.Cells[i].SetCellValue(header);
                    if (i == 0)
                    {
                        sheet.SetColumnWidth(0, 20 * 200);
                    }
                    else
                    {
                        sheet.SetColumnWidth(i, 20 * 350);
                    }
                }

                #endregion

                #region 填充数据

                for (int i = 0; i < list.Count; i++) //循环数据
                {
                    var item = list[i];
                    IRow dataRow = sheet.CreateRow(i + 1);
                    //dataRow.Height = 20 * 20;
                    var type = item.GetType();
                    var props = type.GetProperties();
                    for (int j = 0; j < headers.Count; j++)
                    {
                        dataRow.CreateCell(j);
                        dataRow.Cells[j].CellStyle = style;
                    }

                    dataRow.Cells[0].SetCellValue(item.xiangmu_no);
                    dataRow.Cells[1].SetCellValue(item.xiangmu_name);
                    dataRow.Cells[2].SetCellValue(item.streetname);
                    dataRow.Cells[3].SetCellValue(item.communityname);
                    dataRow.Cells[4].SetCellValue(item.quanliren);
                    dataRow.Cells[5].SetCellValue(item.lianxifangshi);
                    dataRow.Cells[6].SetCellValue(item.xingzhengquhua);
                    dataRow.Cells[7].SetCellValue(item.beian_no);
                    dataRow.Cells[8].SetCellValue(item.beianriqi.ToString());
                    dataRow.Cells[9].SetCellValue(item.handle_status_name);
                    if (item.start_time != null)
                    {
                        dataRow.Cells[10].SetCellValue(Convert.ToDateTime(item.start_time).ToString("yyyy-MM-dd"));
                    }
                    else
                    {
                        dataRow.Cells[10].SetCellValue("");
                    }
                    if (item.end_time != null)
                    {
                        dataRow.Cells[11].SetCellValue(Convert.ToDateTime(item.end_time).ToString("yyyy-MM-dd"));
                    }
                    else
                    {
                        dataRow.Cells[11].SetCellValue("");
                    }
                    dataRow.Cells[12].SetCellValue(item.xiangmu_yt);
                    dataRow.Cells[13].SetCellValue(item.jianzhujiegou);
                    if (item.shenqing_area != null)
                    {
                        dataRow.Cells[14].SetCellValue(item.shenqing_area.ToString());
                    }
                    else
                    {
                        dataRow.Cells[14].SetCellValue("0.00");
                    }

                    if (item.shengchan_area != null)
                    {
                        dataRow.Cells[15].SetCellValue(item.shengchan_area.ToString());
                    }
                    else
                    {
                        dataRow.Cells[15].SetCellValue("0.00");
                    }

                    if (item.fuzhu_area != null)
                    {
                        dataRow.Cells[16].SetCellValue(item.fuzhu_area.ToString());
                    }
                    else
                    {
                        dataRow.Cells[16].SetCellValue("0.00");
                    }
                }

                #endregion

                response.Result = new MemoryStream();

                workbook.Write(response.Result);
                workbook = null;
                response.Result.Close();
                response.Result.Dispose();
                response.Code = 200;
                response.Message = "获取成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }

            return response;
        }

        #endregion

        #region 项目列表

        /// <summary>
        /// 项目列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageInfo<List<DroneSsnyd>> GetDronssnydList(string xiangmumc, string countyid, string streetid,
            string xiangmuno, DateTime? hechatimebegin,DateTime?hechatimeend, string xiangmuyt, int? status,
            int pageIndex, int pageSize)
        {
            int totalCount = 0;

            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();

            

            var list = base.Repository.AsQueryable()
                .Where(a => a.handle_status_id != 0&&a.handle_status_id!=null)
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), a => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), a => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), a => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), a => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), a => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .WhereIF(status != null, a => a.handle_status_id == status)

                .LeftJoin<DroneSsnydRcjg>((a,d)=>a.Id==d.ssnyd_id)
                .WhereIF(hechatimebegin != null && hechatimeend != null, 
                (a, d) => (a.hechatime_kg != null && a.hechatime_kg < hechatimeend && a.hechatime_kg >= hechatimebegin) 
                || (a.hechatime_jz != null && a.hechatime_jz < hechatimeend && a.hechatime_jz >= hechatimebegin) 
                || (a.hechatime_wg != null && a.hechatime_wg < hechatimeend && a.hechatime_wg >= hechatimebegin) 
                || (a.hechatime_wgzg != null && a.hechatime_wgzg < hechatimeend && a.hechatime_wgzg >= hechatimebegin) 
                || (a.hechatime_jzzg != null && a.hechatime_jzzg < hechatimeend && a.hechatime_jzzg >= hechatimebegin) 
                || (a.hechatime_kgzg != null && a.hechatime_kgzg < hechatimeend && a.hechatime_kgzg >= hechatimebegin) 
                || (d.hechatime_rc != null && d.hechatime_rc < hechatimeend && d.hechatime_rc >= hechatimebegin) 
                || (d.hechatime_rczg != null && d.hechatime_rczg < hechatimeend && d.hechatime_rczg >= hechatimebegin) 
                || (d.hechatime_rcfh != null && d.hechatime_rcfh < hechatimeend && d.hechatime_rcfh >= hechatimebegin))

                .OrderBy((a, d) => a.end_time, OrderByType.Desc)
                .Select((a, d) => a)
                .Distinct()
                .ToPageList(pageIndex, pageSize, ref totalCount);

            return new PageInfo<List<DroneSsnyd>>
            {
                Items = list,
                Total = totalCount
            };
        }

        #endregion

        #region  预警列表
        /// <summary>
        /// 预警问题列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageInfo<List<DroneSsnyd>> GetWentiDronssnydList(string xiangmumc, string countyid, string streetid,
            string xiangmuno, string xiangmuyt, int? status,
            int pageIndex, int pageSize)
        {
            int totalCount = 0;

            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();

            var list = _client.Queryable<DroneSsnydRcjg>()
                .LeftJoin<DroneSsnyd>((r,a)=>r.ssnyd_id==a.Id)
                .Where((r, a) => r.iswenti_rc=="是"&&r.is_lishi==0)
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), (r, a) => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), (r, a) => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), (r, a) => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), (r, a) => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), (r, a) => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, (r, a) => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .WhereIF(status != null, (r, a) => a.handle_status_id == status)
                .OrderBy((r, a) => a.end_time, OrderByType.Desc)
                .Select((r, a) => a)
                .ToPageList(pageIndex, pageSize, ref totalCount);

            return new PageInfo<List<DroneSsnyd>>
            {
                Items = list,
                Total = totalCount
            };
        }


        public List<DroneSsnyd> GetWentiDronssnydexport(string xiangmumc, string countyid, string streetid,
    string xiangmuno, string xiangmuyt, int? status)
        {
            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }

            bool issystem = _auth.IsSystem();

            var list = _client.Queryable<DroneSsnydRcjg>()
                .LeftJoin<DroneSsnyd>((r, a) => r.ssnyd_id == a.Id)
                .Where((r, a) => r.iswenti_rc == "是" && r.is_lishi == 0)
                .WhereIF(!string.IsNullOrEmpty(xiangmumc), (r, a) => a.xiangmu_name.Contains(xiangmumc))
                .WhereIF(!string.IsNullOrEmpty(countyid), (r, a) => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), (r, a) => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuyt), (r, a) => a.xiangmu_yt == xiangmuyt)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), (r, a) => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, (r, a) => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .WhereIF(status != null, (r, a) => a.handle_status_id == status)
                .OrderBy((r, a) => a.end_time, OrderByType.Desc)
                .Select((r, a) => a)
                .ToList();

            return list;
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="list"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public Response<MemoryStream> ListWentiToExcel(List<DroneSsnyd> list, List<string> headers)
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();

                #region 内容样式

                IFont font1 = workbook.CreateFont(); //创建一个字体样式对象
                font1.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                //font1.Boldweight = short.MaxValue;//字体加粗
                font1.FontHeightInPoints = 12; //字体大小
                ICellStyle style = workbook.CreateCellStyle(); //创建样式对象
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.Alignment = HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.SetFont(font1); //将字体样式赋给样式对象 
                style.WrapText = true;

                #endregion

                #region 标题样式

                IFont font = workbook.CreateFont(); //创建一个字体样式对象
                font.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                font.Boldweight = (short)FontBoldWeight.Bold; //字体加粗
                font.FontHeightInPoints = 12; //字体大小
                ICellStyle style1 = workbook.CreateCellStyle(); //创建样式对象
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.Alignment = HorizontalAlignment.Center;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.SetFont(font); //将字体样式赋给样式对象 

                #endregion

                #region 创建表头

                IRow rowHeader = sheet.CreateRow(0);
                rowHeader.Height = 20 * 30;
                for (int i = 0; i < headers.Count; i++)
                {
                    var header = headers[i];
                    rowHeader.CreateCell(i);
                    rowHeader.Cells[i].CellStyle = style1;
                    rowHeader.Cells[i].SetCellValue(header);
                    if (i == 0)
                    {
                        sheet.SetColumnWidth(0, 20 * 200);
                    }
                    else
                    {
                        sheet.SetColumnWidth(i, 20 * 350);
                    }
                }

                #endregion

                #region 填充数据

                for (int i = 0; i < list.Count; i++) //循环数据
                {
                    var item = list[i];
                    IRow dataRow = sheet.CreateRow(i + 1);
                    //dataRow.Height = 20 * 20;
                    var type = item.GetType();
                    var props = type.GetProperties();
                    for (int j = 0; j < headers.Count; j++)
                    {
                        dataRow.CreateCell(j);
                        dataRow.Cells[j].CellStyle = style;
                    }

                    dataRow.Cells[0].SetCellValue(item.xiangmu_no);
                    dataRow.Cells[1].SetCellValue(item.xiangmu_name);
                    dataRow.Cells[2].SetCellValue(item.streetname);
                    dataRow.Cells[3].SetCellValue(item.communityname);
                    dataRow.Cells[4].SetCellValue(item.quanliren);
                    dataRow.Cells[5].SetCellValue(item.lianxifangshi);
                    dataRow.Cells[6].SetCellValue(item.xingzhengquhua);
                    dataRow.Cells[7].SetCellValue(item.beian_no);
                    dataRow.Cells[8].SetCellValue(item.beianriqi.ToString());
                    dataRow.Cells[9].SetCellValue(item.handle_status_name);
                    if (item.start_time != null)
                    {
                        dataRow.Cells[10].SetCellValue(Convert.ToDateTime(item.start_time).ToString("yyyy-MM-dd"));
                    }
                    else
                    {
                        dataRow.Cells[10].SetCellValue("");
                    }
                    if (item.end_time != null)
                    {
                        dataRow.Cells[11].SetCellValue(Convert.ToDateTime(item.end_time).ToString("yyyy-MM-dd"));
                    }
                    else
                    {
                        dataRow.Cells[11].SetCellValue("");
                    }
                             
                    dataRow.Cells[12].SetCellValue(item.xiangmu_yt);
                    dataRow.Cells[13].SetCellValue(item.jianzhujiegou);
                    if (item.shenqing_area != null)
                    {
                        dataRow.Cells[14].SetCellValue(item.shenqing_area.ToString());
                    }
                    else
                    {
                        dataRow.Cells[14].SetCellValue("0.00");
                    }

                    if (item.shengchan_area != null)
                    {
                        dataRow.Cells[15].SetCellValue(item.shengchan_area.ToString());
                    }
                    else
                    {
                        dataRow.Cells[15].SetCellValue("0.00");
                    }

                    if (item.fuzhu_area != null)
                    {
                        dataRow.Cells[16].SetCellValue(item.fuzhu_area.ToString());
                    }
                    else
                    {
                        dataRow.Cells[16].SetCellValue("0.00");
                    }
                }

                #endregion

                response.Result = new MemoryStream();

                workbook.Write(response.Result);
                workbook = null;
                response.Result.Close();
                response.Result.Dispose();
                response.Code = 200;
                response.Message = "获取成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }

            return response;
        }
        #endregion

        /// <summary>
        ///  项目编号维护
        /// </summary>
        /// <param name="id"></param>
        /// <param name="newXiangmuNo"></param>
        public async Task MaintainNumber(string id, string newXiangmuNo)
        {
            var project = await Repository.AsQueryable().SingleAsync(a => a.Id == id && a.handle_status_id != 99);
            if (project == null)
            {
                throw new Exception("项目不存在或停止生产");
            }

            var newProject = new DroneSsnyd()
            {
                Id = project.Id,
                xiangmu_no = newXiangmuNo
            };
            await Repository.AsUpdateable(newProject).IgnoreNullColumns().ExecuteCommandAsync();
        }

        public async Task MaintainXianmuName(string id, string newXiangmuName)
        {
            var project = await Repository.AsQueryable().SingleAsync(a => a.Id == id && a.handle_status_id != 99);
            if (project == null)
            {
                throw new Exception("项目不存在或停止生产");
            }

            var newProject = new DroneSsnyd()
            {
                Id = project.Id,
                xiangmu_name = newXiangmuName
            };
            await Repository.AsUpdateable(newProject).IgnoreNullColumns().ExecuteCommandAsync();
        }

        public async Task ProjectRenewal(string id, DateTime newEndTime)
        {
            var project = await Repository.AsQueryable().SingleAsync(a => a.Id == id && a.handle_status_id != 99);
            if (project == null)
            {
                throw new Exception("项目不存在或停止生产");
            }

            if (newEndTime < project.end_time)
            {
                throw new Exception("新的结束时间不能早于原结束时间");
            }

            var newProject = new DroneSsnyd()
            {
                Id = project.Id,
                end_time = newEndTime
            };
            await Repository.AsUpdateable(newProject).IgnoreNullColumns().ExecuteCommandAsync();
        }

        public async Task CloseProject(string id)
        {
            var project = await Repository.AsQueryable().SingleAsync(a => a.Id == id && a.handle_status_id != 99);
            if (project == null)
            {
                throw new Exception("项目不存在或停止生产");
            }

            var newProject = new DroneSsnyd()
            {
                Id = project.Id,
                handle_status_id = 99,
                handle_status_name = "项目终止",
            };
            await Repository.AsUpdateable(newProject).IgnoreNullColumns().ExecuteCommandAsync();
        }

        public DroneSsnyd ProjectDetail(string id)
        {
            var project = Repository.GetById(id);
            if (project == null)
            {
                throw new Exception("项目不存在");
            }

            project.RcjgList = Repository
                .ChangeRepository<SugarRepositiry<DroneSsnydRcjg>>().AsQueryable()
                .Where(c => c.ssnyd_id == id)
                .ToList();
            return project;
        }

        public async Task ProjectHandover(ProjectHandoverReq req)
        {
            var project = req.MapTo<DroneSsnyd>();
            project.handle_status_id = 98;
            project.handle_status_name = "项目移交";
            await Repository.AsUpdateable(project).IgnoreNullColumns().ExecuteCommandAsync();
        }

        public async Task ProjectMaintain(DroneSsnydEditReq req)
        {
            // shp 解析 
            var project = req.MapTo<DroneSsnyd>();
            var oldProject = await Repository.GetByIdAsync(project.Id);
            using var uow = base.UnitWork.CreateContext();
            var a = 0;
            if (!string.IsNullOrEmpty(req.shpPath))
            {
                var geomid = oldProject.geomid;
                var geometry = new DroneShpData()
                {
                    gid = int.Parse(geomid),
                    geom = req.shpPath
                };
                //a = await uow.DroneShpData.AsUpdateable(geometry).IgnoreNullColumns().ExecuteCommandAsync();
            }


            var b = await uow.DroneSsnyd.AsUpdateable(project).IgnoreNullColumns().ExecuteCommandAsync();
            if (b > 0)
            {
                uow.Commit();
            }
            else
            {
                throw new Exception("更新失败");
            }
        }

        public async Task<PageInfo<List<DroneSsnydRcjg>>> ProjectSupervise(DroneSsnydRcjgPageReq req)
        {
            var project = await Repository.GetByIdAsync(req.ProjectId);
            RefAsync<int> totalCount = 0;
            var list = await Repository
                .ChangeRepository<SugarRepositiry<DroneSsnydRcjg>>()
                .AsQueryable()
                .LeftJoin<WFTask>((a, b) =>
                    a.Id == b.ProcessId && b.Type == 7 && b.PrevToken == "create")
                //.LeftJoin<WFTask>((a, b,c) => a.ssnyd_id == c.ProcessId  && c.State == 1)
                .Where((a, b) => a.ssnyd_id == req.ProjectId)
                .WhereIF(req.IsLishi != null, (a, b) => a.is_lishi == req.IsLishi)
                .OrderBy((a, b) => a.create_time, OrderByType.Desc)
                .Select((a, b) => new DroneSsnydRcjg()
                {
                    Id = a.Id,
                    taskId = b.Id,
                    iswenti_rc = a.iswenti_rc, // 监管-是否存在问题  
                    wentileixing_rc = a.wentileixing_rc, //监管-问题类型  
                    qtqksm_rc = a.qtqksm_rc, //监管-其他情况说明  
                    zgfs_rc = a.zgfs_rc, //监管-整改方式  
                    zgqx_rc = a.zgqx_rc, //监管-整改期限  
                    hechauser_rc = a.hechauser_rc, //监管-核查人员  
                    hechatime_rc = a.hechatime_rc, //监管-核查时间  
                    wjzp_rc = a.wjzp_rc, //监管-现场外景照片  
                    njzp_rc = a.njzp_rc, //监管-现场内景照片  
                    zgfs_rczg = a.zgfs_rczg, //整改-整改方式  
                    hechauser_rczg = a.hechauser_rczg, // 整改-办理人员  
                    hechatime_rczg = a.hechatime_rczg, //整改-办理时间  
                    wjzp_rczg = a.wjzp_rczg, // 整改-现场外景照片  
                    njzp_rczg = a.njzp_rczg, //整改-现场内景照片  
                    iswenti_rcfh = a.iswenti_rcfh, //复核-是否整改完成  
                    wentileixing_rcfh = a.wentileixing_rcfh, // 复核-问题类型  
                    qtqksm_rcfh = a.qtqksm_rcfh, //复核-其他情况说明  
                    zgfs_rcfh = a.zgfs_rcfh, //  复核-整改方式  
                    zgqx_rcfh = a.zgqx_rcfh, //复核-整改期限  
                    hechauser_rcfh = a.hechauser_rcfh, // 复核-核查人员  
                    hechatime_rcfh = a.hechatime_rcfh, // 复核-核查时间  
                    wjzp_rcfh = a.wjzp_rcfh, //复核-现场外景照片  
                    njzp_rcfh = a.njzp_rcfh, // 复核--现场内景照片  
                    ssnyd_id = a.ssnyd_id, //主表id  
                    create_time = a.create_time, // 创建时间  
                    fujian_rc = a.fujian_rc, // 监管_附件  
                    fujian_rczg = a.fujian_rczg, // 整改_附件  
                    fujian_rcfh = a.fujian_rcfh, // 复核_附件  
                    is_lishi = a.is_lishi, // 0新的1历史  
                    xiangmu_no = project.xiangmu_no
                })
                .ToPageListAsync(req.page, req.limit, totalCount);
            return new PageInfo<List<DroneSsnydRcjg>>
            {
                Items = list,
                Total = totalCount
            };
        }

        #region  项目审核
        /// <summary>
        /// 项目审核列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageInfo<List<DroneSsnyd>> GetDronssnydShenheList(string countyid, string streetid,string xiangmuno,int pageIndex, int pageSize)
        {
            int totalCount = 0;

            //获取当前登录用户
            var orgs = _auth.GetCurrentUser().Orgs;
            List<string> ids = new List<string>();
            if (orgs != null && orgs.Count > 0)
            {
                ids = orgs.Select(r => r.Id.ToString()).ToList();
            }
            bool issystem = _auth.IsSystem();

            var list = base.Repository.AsQueryable()
                .Where(a => a.handle_status_id == 0 || a.handle_status_id == null)
                .WhereIF(!string.IsNullOrEmpty(countyid), a => a.countyid == countyid)
                .WhereIF(!string.IsNullOrEmpty(streetid), a => a.streetid == streetid)
                .WhereIF(!string.IsNullOrEmpty(xiangmuno), a => a.xiangmu_no.Contains(xiangmuno))
                .WhereIF(!issystem, a => (ids.Contains(a.countyid) || ids.Contains(a.streetid)))
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToPageList(pageIndex, pageSize, ref totalCount);

            return new PageInfo<List<DroneSsnyd>>
            {
                Items = list,
                Total = totalCount
            };
        }
        #endregion
    }
}