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 OpenAuth.App.Interface;
using SqlSugar;
using Infrastructure;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.CompanyManage.Request;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using Infrastructure.Utilities;
using Microsoft.AspNetCore.Http;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Yitter.IdGenerator;

namespace OpenAuth.App.ServiceApp.CompanyManage
{
    public class TaxCompanyApp : SqlSugarBaseApp<TaxCompany, SugarDbContext>
    {
        private ISqlSugarClient client;

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

        #region  获取分页数据列表
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<dynamic>>>> LoadCompanyPageList(TaxCompanyReq req)
        {
            RefAsync<int> totalCount = 0;

            var query =  client.Queryable<TaxCompany>()
                .WhereIF(!string.IsNullOrEmpty(req.shxydm),r=>r.shxydm==req.shxydm)
                .WhereIF(!string.IsNullOrEmpty(req.syrmc),r=>r.syrmc.Contains(req.syrmc))
                .WhereIF(!string.IsNullOrEmpty(req.djqdm),r=>r.djqdm==req.djqdm)
                .WhereIF(!string.IsNullOrEmpty(req.djzqdm),r=>r.djzqdm == req.djzqdm)
                .WhereIF(!string.IsNullOrEmpty(req.frdb),r=>r.frdb == req.frdb)
                .WhereIF(!string.IsNullOrEmpty(req.hy),r=>r.hy == req.hy)
                .WhereIF(!string.IsNullOrEmpty(req.jyzt),r=>r.jyzt == req.jyzt)
                .WhereIF(req.xmgxccmax!=null, r=>r.xmgxcc< req.xmgxccmax)
                .WhereIF(req.xmgxccmin!=null, r=>r.xmgxcc> req.xmgxccmin)
                .WhereIF(req.gdzcmax != null, r=>r.gdzc< req.gdzcmax)
                .WhereIF(req.gdzcmin != null, r=>r.gdzc> req.gdzcmin)
                .WhereIF(req.cscymax != null, r=>r.cscy < req.cscymax)
                .WhereIF(req.cscymin != null, r=>r.cscy > req.cscymin)
                  .Select<dynamic>(r => new 
                  {
                      RowNumber = SqlFunc.RowNumber(r.Id),
                      r.Id,
                      r.shxydm,
                      r.syrmc,
                      r.hy,
                      r.djqmc,
                      r.djzqmc,
                      //syrlx= SqlFunc.Subqueryable<TaxZongdi>().Where(a => a.shxydm == r.shxydm).Select(a => a.syrlx).FirstOrDefault(),
                      r.frdb,
                      r.lxfs,
                      r.xmgxcc,
                      r.cscy
                  });

            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="id">企业id</param>
        /// <returns></returns>
        public async Task<TaxCompany> GetConpanyInfoById(string id)
        {
            var list = await client.Queryable<TaxCompany>().Where(r=>r.Id==id).FirstAsync();
            return list;
        }

        /// <summary>
        /// 根据社会信用代码获取单个企业信息
        /// </summary>
        /// <param name="shxydm">企业社会信用代码</param>
        /// <returns></returns>
        public async Task<TaxCompany> GetConpanyInfoByshxydm(string shxydm)
        {
            var list = await client.Queryable<TaxCompany>().Where(r => r.shxydm == shxydm).FirstAsync();
            return list;
        }
        #endregion

        #region 编辑企业信息
        /// <summary>
        /// 添加企业信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<Response<bool>> AddCompany(TaxCompany req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                if (uow.TaxCompany.IsAny(u => u.shxydm == req.shxydm))
                {
                    throw new Exception("社会信用代码已存在");
                }
                req.Id = Guid.NewGuid().ToString();

                bool insert=await uow.TaxCompany.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>> UpdateCompany(TaxCompany req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                if (uow.TaxCompany.AsQueryable().Where(u => u.shxydm == req.shxydm&&u.Id==req.Id).Count()>1)
                {
                    throw new Exception("社会信用代码已存在");
                }

                bool update =await uow.TaxCompany.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>> DeleteCompany(string[] ids)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                var delete=await uow.TaxCompany.DeleteAsync(a => ids.Contains(a.Id));
                var flag = uow.Commit();
                return new Response<bool>
                {
                    Result = flag&& delete,
                    Message = flag && delete == true ? "success" : "error"
                };
            }
        }
        #endregion

        #region  查询乡镇
        /// <summary>
        /// 查询乡镇
        /// </summary>
        /// <returns></returns>
        public async Task<List<dynamic>> GetStreetInfo()
        {
            var list = await client.Queryable<TaxXzqh>()
                .OrderBy(r=>r.djqdm)
                .GroupBy(r => new {r.djqdm,r.djqmc})
                .Select<dynamic>(r => new
            {
                r.djqdm,
                r.djqmc,
            }).ToListAsync();
            return list;
        }
        public async Task<List<dynamic>> GetCommunityInfo(string djqdm)
        {
            var list = await client.Queryable<TaxXzqh>()
                .Where(r=>r.djqdm== djqdm)
                .OrderBy(r=>r.xzqdm)
                .Select<dynamic>(r => new
                {
                    r.xzqdm,
                    r.xzqmc,
                }).ToListAsync();
            return list;
        }
        #endregion
        #region 上传企业信息
        /// <summary>
        /// 上传企业信息
        /// </summary>
        /// <param name="formFiles"></param>
        /// <returns></returns>
        public Response<bool> ImportCompanyInfo(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(32)?.ToString() != "djzqmc")
                            {
                                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;
                                
                                TaxCompany cy = new TaxCompany();
                                cy.Id = Guid.NewGuid().ToString();
                                cy.shxydm =row.GetCell(0)?.ToString();
                                cy.frdb =row.GetCell(1)?.ToString();
                                cy.frsfzh =row.GetCell(2)?.ToString();
                                cy.lxfs=row.GetCell(3)?.ToString();
                                cy.hy=row.GetCell(4)?.ToString();
                                cy.jyzt =row.GetCell(5)?.ToString();
                                cy.ydhm =row.GetCell(6)?.ToString();
                                cy.ydhh =row.GetCell(7)?.ToString();
                                cy.dgyf =row.GetCell(8)?.ToString();
                                cy.yrhm =row.GetCell(9)?.ToString();
                                cy.yrhh=row.GetCell(10)?.ToString();
                                cy.rgyf =row.GetCell(11)?.ToString();
                                cy.yqhm =row.GetCell(12)?.ToString();
                                cy.yqhh=row.GetCell(13)?.ToString();
                                cy.qgyf =row.GetCell(14)?.ToString();
                                cy.yshm =row.GetCell(15)?.ToString();
                                cy.yshh =row.GetCell(16)?.ToString();
                                cy.sgyf =row.GetCell(17)?.ToString();
                                cy.dcr=row.GetCell(18)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(19)?.ToString()))
                                {
                                    cy.dcrq = null;
                                }
                                else
                                {
                                    cy.dcrq = Convert.ToDateTime(row.GetCell(19)?.DateCellValue);
                                }
                                //cy.dcrq=Convert.ToDateTime(row.GetCell(19).ToString());
                                cy.clr=row.GetCell(20)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(21)?.ToString()))
                                {
                                    cy.clrq = null;
                                }
                                else
                                {
                                    cy.clrq = Convert.ToDateTime(row.GetCell(21)?.DateCellValue);
                                }
                                //cy.clrq=Convert.ToDateTime(row.GetCell(21).ToString());
                                cy.bz=row.GetCell(22)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(23)?.ToString()))
                                {
                                    cy.gdzc=null;
                                }
                                else
                                {
                                    cy.gdzc=Convert.ToDecimal(row.GetCell(23)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(24)?.ToString()))
                                {
                                    cy.xmgxcc = null;
                                }
                                else
                                {
                                    cy.xmgxcc = Convert.ToDecimal(row.GetCell(24)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(25)?.ToString()))
                                {
                                    cy.cscy = null;
                                }
                                else
                                {
                                    cy.cscy = Convert.ToDecimal(row.GetCell(25)?.ToString());
                                }
                                if (string.IsNullOrEmpty(row.GetCell(26)?.ToString()))
                                {
                                    cy.gdtzze = null;
                                }
                                else
                                {
                                    cy.gdtzze = Convert.ToDecimal(row.GetCell(26)?.ToString());
                                }
                                var sfgs = row.GetCell(27)?.ToString();
                                if (string.IsNullOrEmpty(row.GetCell(27)?.ToString()))
                                {
                                    cy.sfgsqy = null;
                                }
                                else
                                {
                                    if (sfgs == "t")
                                    {
                                        cy.sfgsqy = true;
                                    }
                                    else
                                    {
                                        cy.sfgsqy = false;
                                    }
                                    //cy.sfgsqy = Convert.ToBoolean(row.GetCell(27).BooleanCellValue);
                                }
                                cy.syrmc=row.GetCell(28)?.ToString();
                                cy.djqdm=row.GetCell(29)?.ToString();
                                cy.djqmc=row.GetCell(30)?.ToString();
                                cy.djzqdm=row.GetCell(31)?.ToString();
                                cy.djzqmc=row.GetCell(32)?.ToString();                              
                                if (uow.TaxCompany.IsAny(u => u.shxydm == cy.shxydm))
                                {
                                    res += "社会信用代码" + cy.shxydm + "已存在,";
                                }
                                else
                                {
                                    uow.TaxCompany.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
    }
}
