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.Interface;
using SqlSugar;
using OpenAuth.App.ServiceApp.TaxZongdiManage.Request;
using DocumentFormat.OpenXml.EMMA;
using OpenAuth.App.BasicQueryService;
using Org.BouncyCastle.Ocsp;

namespace OpenAuth.App.ServiceApp.TaxZongdiManage
{
    public class TaxZongdiApp : SqlSugarBaseApp<TaxZongdi, SugarDbContext>
    {
        private ISqlSugarClient client;
        CommonDataManager _commonDataManager;

        #region 构造函数
        public TaxZongdiApp(
             CommonDataManager commonDataManager,
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<TaxZongdi> 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>>>> LoadZongdiPageList(TaxZongdiReq req)
        {
            RefAsync<int> totalCount = 0;
            var query = client.Queryable<TaxZongdi>()
                .WhereIF(!string.IsNullOrEmpty(req.zdbm), r => r.zdbm == req.zdbm)
                .WhereIF(!string.IsNullOrEmpty(req.syqsq), r => r.syqsq.Contains(req.syqsq))
                .WhereIF(!string.IsNullOrEmpty(req.djqdm), r => r.djqdm == req.djqdm)
                .WhereIF(!string.IsNullOrEmpty(req.djzqdm), r => r.djzqdm == req.djzqdm)
                .WhereIF(!string.IsNullOrEmpty(req.bdcdyh), r => r.bdcdyh == req.bdcdyh)
                .WhereIF(!string.IsNullOrEmpty(req.tdxz), r => r.tdxz == req.tdxz)
                  .Select<dynamic>(r => new
                  {
                      RowNumber = SqlFunc.RowNumber(r.gid),
                      r.gid,
                      r.shxydm,
                      r.syrmc,
                      r.zdbm,
                      r.djqmc,
                      r.djzqmc,
                      r.bdcdyh,
                      r.zdfzmj,
                      r.syqsq,
                      r.tdxz,
                      r.jzfzzmj,
                      r.tdqdfs
                  });

            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<TaxZongdi> GetZongdiInfoById(int gid)
        {
            var list = await client.Queryable<TaxZongdi>().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>> AddZongdi(TaxZongdi req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                if (uow.TaxZongdi.IsAny(u => u.zdbm == req.zdbm))
                {
                    throw new Exception("宗地编码已存在");
                }
                //获取主键
                string _gid = _commonDataManager.GetMaxKeyVal("gid", "tax_zongdi", 1);
                req.gid = int.Parse(_gid);//转为数字类型

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

                //StringBuilder geomSql = new StringBuilder();
                //if (req.geom != null)
                //{
                //    //格式化数据
                //    string _wktModel = _commonDataManager.WktDataConvert(req.geom, "MULTIPOLYGON ZM", 4);

                //    req.geom = null;

                    
                //    geomSql.AppendFormat($" update tax_zongdi set geom = st_geomfromtext('{_wktModel}',4326) where gid = '{_gid}'");
                //}


                bool insert = await uow.TaxZongdi.InsertAsync(req);
                //var geo=await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
                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>> UpdateZongdi(TaxZongdi req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                if (uow.TaxZongdi.AsQueryable().Where(u => u.zdbm == req.zdbm && u.gid == req.gid).Count() > 1)
                {
                    throw new Exception("用地编码已存在");
                }
                
                bool update = await uow.TaxZongdi.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>> DeleteZongdi(int[] ids)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                var delete = await uow.TaxZongdi.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> ImportZongdiInfo(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(35)?.ToString() != "ssnydbamj")
                            {
                                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;

                                TaxZongdi cy = new TaxZongdi();
                                //获取主键
                                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.zdbm=row.GetCell(4)?.ToString();
                                cy.djqdm=row.GetCell(5)?.ToString();
                                cy.djqmc=row.GetCell(6)?.ToString();
                                cy.djzqdm=row.GetCell(7)?.ToString();
                                cy.djzqmc=row.GetCell(8)?.ToString();
                                cy.syrmc=row.GetCell(9)?.ToString();
                                cy.syrlx=row.GetCell(10)?.ToString();
                                cy.shxydm=row.GetCell(11)?.ToString();
                                cy.sjyt=row.GetCell(12)?.ToString();
                                cy.tdxz=row.GetCell(13)?.ToString();
                                cy.tdqdfs=row.GetCell(14)?.ToString();
                                cy.synx=row.GetCell(15)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(16)?.ToString()))
                                {
                                    cy.symj = null;
                                }
                                else
                                {
                                    cy.symj = Convert.ToDecimal(row.GetCell(16)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(17)?.ToString()))
                                {
                                    cy.zdfzmj = null;
                                }
                                else
                                {
                                    cy.zdfzmj = Convert.ToDecimal(row.GetCell(17)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(18)?.ToString()))
                                {
                                    cy.zdsjmj = null;
                                }
                                else
                                {
                                    cy.zdsjmj = Convert.ToDecimal(row.GetCell(18)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(19)?.ToString()))
                                {
                                    cy.jzfzzmj = null;
                                }
                                else
                                {
                                    cy.jzfzzmj = Convert.ToDecimal(row.GetCell(19)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(20)?.ToString()))
                                {
                                    cy.jzsjzmj = null;
                                }
                                else
                                {
                                    cy.jzsjzmj = Convert.ToDecimal(row.GetCell(20)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(21)?.ToString()))
                                {
                                    cy.gjgjzmj = null;
                                }
                                else
                                {
                                    cy.gjgjzmj = Convert.ToDecimal(row.GetCell(21)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(22)?.ToString()))
                                {
                                    cy.zhjgjzmj = null;
                                }
                                else
                                {
                                    cy.zhjgjzmj = Convert.ToDecimal(row.GetCell(22)?.ToString());
                                }
                                cy.dcr = row.GetCell(23)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(24)?.ToString()))
                                {
                                    cy.dcrq = null;
                                }
                                else
                                {
                                    cy.dcrq = Convert.ToDateTime(row.GetCell(24)?.DateCellValue);
                                }
                                //cy.dcrq=Convert.ToDateTime(row.GetCell(19).ToString());
                                cy.clr = row.GetCell(25)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(26)?.ToString()))
                                {
                                    cy.clrq = null;
                                }
                                else
                                {
                                    cy.clrq = Convert.ToDateTime(row.GetCell(26)?.DateCellValue);
                                }
                                //cy.clrq=Convert.ToDateTime(row.GetCell(21).ToString());
                                cy.bz = row.GetCell(27)?.ToString();
                                cy.bdcdyh=row.GetCell(28)?.ToString();
                                cy.zdybh=row.GetCell(29)?.ToString();
                                
                                if (string.IsNullOrEmpty(row.GetCell(30)?.ToString()))
                                {
                                    cy.jzsyzmj = null;
                                }
                                else
                                {
                                    cy.jzsyzmj = Convert.ToDecimal(row.GetCell(30)?.ToString());
                                }
                                cy.zddm=row.GetCell(31)?.ToString();
                                cy.syqsq=row.GetCell(32)?.ToString();
                                cy.syzzq = row.GetCell(33)?.ToString();
                                if (!string.IsNullOrEmpty(row.GetCell(34)?.ToString()))
                                {
                                    cy.geom = row.GetCell(34)?.ToString();
                                }
                                if (string.IsNullOrEmpty(row.GetCell(35)?.ToString()))
                                {
                                    cy.ssnydbamj = null;
                                }
                                else
                                {
                                    cy.ssnydbamj = Convert.ToDecimal(row.GetCell(35)?.ToString());
                                }
                                if (uow.TaxZongdi.IsAny(u => u.zdbm == cy.zdbm))
                                {
                                    res += "宗地编码" + cy.zdbm + "已存在,";
                                }
                                else
                                {
                                    uow.TaxZongdi.Insert(cy);
                                    //uow.Db.Ado.ExecuteCommand(geomSql.ToString());
                                }
                            }
                        }
                        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
    }
}
