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>
    {
        public DroneSsnyApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<DroneSsnyd> repository, IAuth auth)
            : base(unitWork, repository, auth)
        {
        }

        /// <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 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 == xiangmuno)
                .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 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 == xiangmuno)
                .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 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))
                .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 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))
                .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 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))
                .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 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))
                .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 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 == xiangmuno)
                .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 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 == xiangmuno)
                .Where(a => a.end_time < endTime)
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .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.xingzhengquhua);
                    dataRow.Cells[6].SetCellValue(item.beian_no);
                    dataRow.Cells[7].SetCellValue(item.start_time.ToString());
                    dataRow.Cells[8].SetCellValue(item.end_time.ToString());
                    dataRow.Cells[9].SetCellValue(item.xiangmu_yt);
                    if (item.shenqing_area != null)
                    {
                        dataRow.Cells[10].SetCellValue(item.shenqing_area.ToString());
                    }
                    else
                    {
                        dataRow.Cells[10].SetCellValue("0.00");
                    }

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

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

                    dataRow.Cells[13].SetCellValue(item.xiafatime.ToString());
                    dataRow.Cells[14].SetCellValue(item.handle_status_name);

                    //if (item.handle_status_id != null)
                    //{
                    //    StatusType status = (StatusType)item.handle_status_id;
                    //    dataRow.Cells[14].SetCellValue(status.ToString());
                    //}
                    //else
                    //{
                    //    dataRow.Cells[14].SetCellValue("--");
                    //}
                }

                #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, string xiangmuyt,
            int pageIndex, int pageSize)
        {
            int totalCount = 0;
            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 == xiangmuno)
                .OrderBy(a => a.end_time, OrderByType.Desc)
                .ToPageList(pageIndex, pageSize, ref totalCount);

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

        #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>();
            await Repository.AsUpdateable(project).IgnoreNullColumns().ExecuteCommandAsync();
        }

        public async Task ProjectMaintain(DroneSsnydEditReq req)
        {
            // todo  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 = ""
                };
                a = await uow.DroneShpData.AsUpdateable(geometry).IgnoreNullColumns().ExecuteCommandAsync();
            }


            var b = await uow.DroneSsnyd.AsUpdateable(project).IgnoreNullColumns().ExecuteCommandAsync();
            if (a > 0 && 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)
                .LeftJoin<WFTask>((a, b,c) => a.ssnyd_id == c.ProcessId)
                .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,c) => new DroneSsnydRcjg()
                {
                    Id = a.Id,
                    taskId = b.Id,
                    mainTaskId =c.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
            };
        }
    }
}