using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using Microsoft.AspNetCore.Http;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.TaxZongdiManage.Request;
using SqlSugar;
using OpenAuth.App.ServiceApp.TaxBuildingManage.Request;

namespace OpenAuth.App.ServiceApp.TaxBuildingManage
{
    public class TaxBuildingApp : SqlSugarBaseApp<TaxBuilding, SugarDbContext>
    {
        private ISqlSugarClient client;
        CommonDataManager _commonDataManager;

        #region 构造函数
        public TaxBuildingApp(
             CommonDataManager commonDataManager,
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<TaxBuilding> repository,
            IAuth auth,
            ISqlSugarClient sqlSugarClient
            ) : base(unitWork, repository, auth)
        {
            this.client = sqlSugarClient;
            _commonDataManager = commonDataManager;
        }
        #endregion

        #region  获取分页数据列表
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<dynamic>>>> LoadBuildingPageList(TaxBuildingReq req)
        {
            RefAsync<int> totalCount = 0;
            var query = client.Queryable<TaxBuilding>()
                .WhereIF(!string.IsNullOrEmpty(req.jzwbm), r => r.jzwbm == req.jzwbm)
                .WhereIF(!string.IsNullOrEmpty(req.jzwmc), r => r.jzwmc.Contains(req.jzwmc))
                .WhereIF(!string.IsNullOrEmpty(req.jzwjg), r => r.jzwjg == req.jzwjg)
                .WhereIF(req.jgrqmax!=null, r => r.jgrq<req.jgrqmax)
                .WhereIF(req.jgrqmin!=null, r => r.jgrq>req.jgrqmin)
                  .Select<dynamic>(r => new
                  {
                      RowNumber = SqlFunc.RowNumber(r.gid),
                      r.gid,
                      r.jzwbm,
                      r.jzwmc,
                      r.jzwjg,
                      r.jzsyqr,
                      r.jzwsjmj,
                      r.jzwfzmj,
                      r.jgrq,
                      r.dcrq,
                      r.bz
                  });

            var result = await query.ToPageListAsync(req.page, req.limit, totalCount);

            return new Response<PageInfo<List<dynamic>>>
            {
                Code = 200,
                Message = "success",
                Result = new PageInfo<List<dynamic>>
                {
                    Items = result,
                    Total = totalCount
                }
            };
        }

        /// <summary>
        /// 根据id获取单个企业用房信息
        /// </summary>
        /// <param name="gid">用房gid</param>
        /// <returns></returns>
        public async Task<TaxBuilding> GetBuildingInfoById(int gid)
        {
            var list = await client.Queryable<TaxBuilding>().Where(r => r.gid == gid).FirstAsync();
            return list;
        }
        #endregion

        #region 编辑企业用房信息
        /// <summary>
        /// 添加企业用房信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<Response<bool>> AddBuilding(TaxBuilding req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                if (uow.TaxBuilding.IsAny(u => u.jzwbm == req.jzwbm))
                {
                    throw new Exception("建筑物编码已存在");
                }
                //获取主键
                string _gid = _commonDataManager.GetMaxKeyVal("gid", "tax_building", 1);
                req.gid = int.Parse(_gid);//转为数字类型

                //获取objectid
                string _objid = _commonDataManager.GetMaxKeyVal("objectid", "tax_building", 1);
                req.objectid = int.Parse(_objid);//转为数字类型

                bool insert = await uow.TaxBuilding.InsertAsync(req);
                bool flag = uow.Commit();

                return new Response<bool>
                {
                    Result = flag && insert,
                    Message = (flag && insert) == true ? "success" : "error"
                };
            }
        }


        /// <summary>
        /// 修改企业用房信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<Response<bool>> UpdateBuilding(TaxBuilding req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                if (uow.TaxBuilding.AsQueryable().Where(u => u.jzwbm == req.jzwbm && u.gid == req.gid).Count() > 1)
                {
                    throw new Exception("建筑物编码已存在");
                }

                bool update = await uow.TaxBuilding.UpdateAsync(req);
                bool flag = uow.Commit();

                return new Response<bool>
                {
                    Result = flag && update,
                    Message = (flag && update) == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 删除企业用房
        /// </summary>
        /// <param name="ids"></param>
        public async Task<Response<bool>> DeleteBuilding(int[] ids)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                var delete = await uow.TaxBuilding.DeleteAsync(a => ids.Contains(a.gid));
                var flag = uow.Commit();
                return new Response<bool>
                {
                    Result = flag && delete,
                    Message = flag && delete == true ? "success" : "error"
                };
            }
        }
        #endregion

        #region 上传企业用房信息
        /// <summary>
        /// 上传企业用房信息
        /// </summary>
        /// <param name="formFiles"></param>
        /// <returns></returns>
        public Response<bool> ImportBuildingInfo(IFormFileCollection formFiles)
        {
            IFormFile file = formFiles[0];
            //存储文件到服务器
            if (file != null)
            {
                if (file.FileName.IndexOf(".xls") > 0 || file.FileName.IndexOf(".xlsx") > 0)
                {
                    //数据库导入
                    IWorkbook workbook = null;
                    if (file.FileName.IndexOf(".xlsx") > 0)
                    {
                        using (var stream = file.OpenReadStream())
                        {
                            workbook = new XSSFWorkbook(stream);//excel的版本2007
                        }
                    }
                    else if (file.FileName.IndexOf(".xls") > 0)
                    {
                        using (var stream = file.OpenReadStream())
                        {
                            workbook = new HSSFWorkbook(stream);//excel的版本2003
                        }
                    }

                    //数据处理
                    using (var uow = base.UnitWork.CreateContext())
                    {
                        //获取sheet
                        ISheet sheet;
                        sheet = workbook.GetSheetAt(0);
                        //处理sheet数据
                        string res = "";
                        if (sheet != null)
                        {
                            IRow firstRow = sheet.GetRow(0);
                            if (firstRow.GetCell(26)?.ToString() != "jzsyqr")
                            {
                                throw new Exception("非标准模板文档，请重新整理。");
                            }
                            //获取有效数据行数
                            int lastRow = sheet.LastRowNum;
                            //int rowCount = 0;
                            //具体excel数据解析
                            for (int i = 1; i <= lastRow; ++i)
                            {
                                IRow row = sheet.GetRow(i);
                                if (row == null || string.IsNullOrEmpty(row.GetCell(0).ToString())) continue;

                                TaxBuilding cy = new TaxBuilding();
                                //获取主键
                                string _gid = _commonDataManager.GetMaxKeyVal("gid", "tax_zongdi", 1);
                                cy.gid = int.Parse(_gid);//转为数字类型

                                //获取objectid
                                string _objid = _commonDataManager.GetMaxKeyVal("objectid", "tax_zongdi", 1);
                                cy.objectid = int.Parse(_objid);//转为数字类型
                                if (string.IsNullOrEmpty(row.GetCell(2)?.ToString()))
                                {
                                    cy.shape_leng = null;
                                }
                                else
                                {
                                    cy.shape_leng = Convert.ToDecimal(row.GetCell(2)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(3)?.ToString()))
                                {
                                    cy.shape_area = null;
                                }
                                else
                                {
                                    cy.shape_area = Convert.ToDecimal(row.GetCell(3)?.ToString());
                                }

                                cy.szzdbm = row.GetCell(4)?.ToString();
                                cy.jzwbm = row.GetCell(5)?.ToString();
                                cy.jzwjg = row.GetCell(6)?.ToString();
                                cy.jzwcs = row.GetCell(7)?.ToString();
                                cy.szcs = row.GetCell(8)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(9)?.ToString()))
                                {
                                    cy.jgrq = null;
                                }
                                else
                                {
                                    cy.jgrq = Convert.ToDateTime(row.GetCell(9)?.DateCellValue);
                                }
                                cy.qdfs = row.GetCell(10)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(11)?.ToString()))
                                {
                                    cy.symj = null;
                                }
                                else
                                {
                                    cy.symj = Convert.ToDecimal(row.GetCell(11)?.ToString());
                                }

                                if (string.IsNullOrEmpty(row.GetCell(12)?.ToString()))
                                {
                                    cy.mjjsxs = null;
                                }
                                else
                                {
                                    cy.mjjsxs = Convert.ToDecimal(row.GetCell(12)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(13)?.ToString()))
                                {
                                    cy.jzwsjzdmj = null;
                                }
                                else
                                {
                                    cy.jzwsjzdmj = Convert.ToDecimal(row.GetCell(13)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(14)?.ToString()))
                                {
                                    cy.jzwsjmj = null;
                                }
                                else
                                {
                                    cy.jzwsjmj = Convert.ToDecimal(row.GetCell(14)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(15)?.ToString()))
                                {
                                    cy.jzwfzmj = null;
                                }
                                else
                                {
                                    cy.jzwfzmj = Convert.ToDecimal(row.GetCell(15)?.ToString());
                                }

                                cy.dcr = row.GetCell(16)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(17)?.ToString()))
                                {
                                    cy.dcrq = null;
                                }
                                else
                                {
                                    cy.dcrq = Convert.ToDateTime(row.GetCell(17)?.DateCellValue);
                                }
                                cy.clr = row.GetCell(18)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(19)?.ToString()))
                                {
                                    cy.clrq = null;
                                }
                                else
                                {
                                    cy.clrq = Convert.ToDateTime(row.GetCell(19)?.DateCellValue);
                                }
                                cy.bz = row.GetCell(20)?.ToString();
                                cy.bdcdyh=row.GetCell(21)?.ToString();
                                cy.jzwmc = row.GetCell(22)?.ToString();
                                cy.fwybh = row.GetCell(23)?.ToString();
                                if (!string.IsNullOrEmpty(row.GetCell(24)?.ToString()))
                                {
                                    cy.geom = row.GetCell(24)?.ToString();
                                }
                                cy.jzwsyqr = row.GetCell(25)?.ToString();
                                cy.jzsyqr = row.GetCell(26)?.ToString();

                                if (uow.TaxBuilding.IsAny(u => u.jzwbm == cy.jzwbm))
                                {
                                    res += "建筑物编码" + cy.jzwbm + "已存在,";
                                }
                                else
                                {
                                    uow.TaxBuilding.Insert(cy);
                                }
                            }
                        }
                        var flag = uow.Commit();

                        return new Response<bool>
                        {
                            Result = flag,
                            Message = flag == true ? "导入成功" + res : "导入失败"
                        };
                    }
                }
                else
                {
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "上传文件类型错误，请上传Excel文件"
                    };
                }
            }
            else
            {
                return new Response<bool>
                {
                    Result = false,
                    Message = "文件为空"
                };
            }
        }
        #endregion
    }
}
