using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using EquipmentApi.IRepositories;
using MadRunFabric.Model;
using EquipmentApi.Model.Dto;
using EquipmentApi.Model.Input;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using Api.SignToken;
using AutoMapper;

namespace EquipmentApi.Controllers
{
    /// <summary>
    /// 设备信息管理控制器，对设备信息的操作
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class EquipmentController : BaseController
    {
        private readonly ILogger<EquipmentController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IEqp_Equipment_InfoRepository _eqp_equipment_infoRepository;
        private readonly IEqp_Import_InfoRepository _eqp_import_infoRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IMapper _mapper;
        private readonly ISys_DictionaryValueRepository _sys_dictionaryValuerepository;

        public EquipmentController(
            ILogger<EquipmentController> logger,IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            IEqp_Equipment_InfoRepository equipment_infoRepository,IEqp_Import_InfoRepository equipment_importRepository,
            ISignTokenService signTokenService, IMapper mapper, ISys_DictionaryValueRepository sys_dictionaryValuerepository)
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _eqp_equipment_infoRepository = equipment_infoRepository;
            _eqp_import_infoRepository = equipment_importRepository;
            _signTokenService = signTokenService;
            _mapper = mapper;
            _sys_dictionaryValuerepository = sys_dictionaryValuerepository;
        }

        /// <summary>
        /// 获取全部设备信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDrop()
        {
            var list = await _eqp_equipment_infoRepository.Get(x => x.isdelete == 0);

            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            if (userinfo.isallproject == 0)
                list = list.Where(x => userinfo.projectlist.Contains(x.projectid));

            var listmodel = new List<DropListDto>();
            foreach (var item in list)
            {
                var model = new DropListDto();
                model.id = item.id;
                model.text = item.equipment_name;
                listmodel.Add(model);
            }
            return Success("成功", listmodel);
        }

        /// <summary>
        /// 获取维修设备信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getrepairlistdrop")]
        public async Task<IActionResult> GetRepairListDrop(string keyword, string floorid, string systemid)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Eqp_Equipment_Info>.Sort.Descending("equipment_number");
            //根据条件查询集合
            var listFilter = new List<FilterDefinition<Eqp_Equipment_Info>>();
            listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Eq("isdelete", 0));
            ////查询
            //if (!string.IsNullOrEmpty(systemid))
            //    listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.systemid.Equals(systemid)));
            //if (!string.IsNullOrEmpty(floorid))
            //    listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.floorid.Equals(floorid)));
            //模糊查询(设备名称，设备编号)
            if (!string.IsNullOrEmpty(keyword))
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.equipment_name.Contains(keyword) || s.equipment_number.Contains(keyword)));

            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            if (userinfo.isallproject == 0)
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => userinfo.projectlist.Contains(s.projectid)));
            #endregion
            var filter = Builders<Eqp_Equipment_Info>.Filter.And(listFilter);
            var list = await _eqp_equipment_infoRepository.Get(filter, null, sort);

            List<Eqp_Equipment_Info> listnew = new List<Eqp_Equipment_Info>();
           var listmodel = list.Select(p => new
            {
                p.id,
                code = p.equipment_number,
                name = p.equipment_name
            });
           
            return Success("成功", listnew);
        }

        /// <summary>
        /// 设备信息列表 by page
        /// </summary>
        /// <param name="keyword">设备编号</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListByPageAsync(string keyword, string floorid, string systemid, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Eqp_Equipment_Info>.Sort.Descending("equipment_number");

            //根据条件查询集合
            var listFilter = new List<FilterDefinition<Eqp_Equipment_Info>>();
            listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Eq("isdelete", 0));
            //查询
            if (!string.IsNullOrEmpty(systemid))
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.systemid.Equals(systemid)));
            if (!string.IsNullOrEmpty(floorid))
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.floorid.Equals(floorid)));
            //模糊查询(设备名称，设备编号)
            if (!string.IsNullOrEmpty(keyword))
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.equipment_name.Contains(keyword) || s.equipment_number.Contains(keyword)));

            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            if (userinfo.isallproject == 0)
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => userinfo.projectlist.Contains(s.projectid)));
            #endregion

            var filter = Builders<Eqp_Equipment_Info>.Filter.And(listFilter);
            var list = await _eqp_equipment_infoRepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _eqp_equipment_infoRepository.CountAsync(filter);   //获取总数


            var obj = new
            {
                rows = list,
                total = redCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 设备信息列表 by page - 关联查询
        /// </summary>
        /// <param name="keyword">设备编号</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPage(string keyword, string provincecode, string citycode, string projectid, string protype, string bulidid, string floorid, string systemid, int pageindex = 1, int pagesize = 10)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            int recordCount = 0;
            var result = _eqp_equipment_infoRepository.GetListsByPage(keyword, provincecode, citycode, projectid, protype, bulidid, floorid, systemid, userinfo,pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 设备信息列表 by page - 关联查询
        /// </summary>
        /// <param name="keyword">设备编号</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet("getlists")]
        public IActionResult GetList(string keyword, string provincecode, string citycode, string projectid, string protype, string bulidid, string floorid, string systemid, int pageindex = 1, int pagesize = 10)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            int recordCount = 0;
            var result = _eqp_equipment_infoRepository.GetListsByPage(keyword, provincecode, citycode, projectid, protype, bulidid, floorid, systemid, userinfo, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 设备信息列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="floorid"></param>
        /// <param name="systemid"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetLists(string keyword, string floorid, string systemid)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Eqp_Equipment_Info>.Sort.Descending("equipment_number");
            //根据条件查询集合
            var listFilter = new List<FilterDefinition<Eqp_Equipment_Info>>();
            listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Eq("isdelete", 0));
            //查询
            if (!string.IsNullOrEmpty(systemid))
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.systemid.Equals(systemid)));
            if (!string.IsNullOrEmpty(floorid))
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.floorid.Equals(floorid)));
            //模糊查询(设备名称，设备编号)
            if (!string.IsNullOrEmpty(keyword))
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.equipment_name.Contains(keyword) || s.equipment_number.Contains(keyword)));

            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            if (userinfo.isallproject == 0)
                listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => userinfo.projectlist.Contains(s.projectid)));
            #endregion
            var filter = Builders<Eqp_Equipment_Info>.Filter.And(listFilter);
            var list = await _eqp_equipment_infoRepository.Get(filter, null, sort);

            return Success("获取成功", list);
        }

        /// <summary>
        /// 获取设备列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getapplists")]
        public async Task<IActionResult> GetAppLists(string keyword, string provincecode, string citycode, string projectid, string protype, string bulidid, string floorid, string systemid,string systemname,string equipnum)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            if (!string.IsNullOrWhiteSpace(systemname))
            {
                var ml = await _sys_dictionaryValuerepository.GetSingle(p => p.name  == systemname);
                if (ml != null)
                {
                    systemid = ml.id;
                }
            }

            var result = _eqp_equipment_infoRepository.GetAppLists(keyword, provincecode, citycode, projectid, protype, bulidid, floorid, systemid, userinfo, equipnum);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取设备详情 by id
        /// </summary>
        /// <param name="id">设备id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _eqp_equipment_infoRepository.GetSingle(id);
            if (model != null)
            {
                var result = new
                {
                    model.floorid,
                    model.equipment_name,
                    model.systemid,
                    model.equipment_number,
                    model.equipment_model,
                    model.equipment_image,
                    model.purchase_order,
                    model.maintenance_order,
                    //model.equipment_supplier,
                    //model.equipment_manufacturer,
                    //model.install_date,
                    model.install_place,
                    //model.inspect_date,
                    //model.made_date,
                    //model.use_date,
                    //model.purchase_money,
                    //model.quality_date,
                    model.use_startdate,
                    model.use_enddate,
                    model.quality_startdate,
                    model.quality_enddate,
                    model.extensionlist
                };
                return Success("获取成功！", result);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 获取设备详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public IActionResult GetDetails(string id)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var model = _eqp_equipment_infoRepository.GetDetails(id, userinfo);
            return Success("获取成功！", model);
        }

        /// <summary>
        /// 添加设备信息
        /// </summary>
        /// <param name="input">设备信息参数</param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> Add(EquipmentInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.equipment_name))
                return Error("设备名称不能为空");
            if (string.IsNullOrEmpty(input.equipment_number))
                return Error("设备编码不能为空");

            var modelold = await _eqp_equipment_infoRepository.GetSingle(p => p.equipment_number == input.equipment_number && p.isdelete == 0);
            if (modelold != null)
            {
                return Error("设备编码已经存在");
            }
            #endregion
            var model = new Eqp_Equipment_Info();
            model.province = input.province;
            model.city = input.city;
            model.projectid = input.projectid;
            model.protypeid = input.protypeid;
            model.buildid = input.buildid;
            model.floorid = input.floorid;
            model.equipment_name = input.equipment_name;
            model.systemid = input.systemid;
            model.equipment_number = input.equipment_number;
            model.equipment_model = input.equipment_model;

            if (input.equipment_image != null)
            {
                model.equipment_image = input.equipment_image;
            }
            else
            {
                model.equipment_image = new List<FileBaseModel>();
            }
            if (input.purchase_order != null)
            {
                model.purchase_order = input.purchase_order;
            }
            else
            {
                model.purchase_order = new List<FileBaseModel>();
            }
            if (input.maintenance_order != null)
            {
                model.maintenance_order = input.maintenance_order;
            }
            else
            {
                model.maintenance_order = new List<FileBaseModel>();
            }

            //model.equipment_supplier = input.equipment_supplier;
            //model.equipment_manufacturer = input.equipment_manufacturer;
            //model.install_date = input.install_date;
            model.install_place = input.install_place;
            //model.inspect_date = input.inspect_date;
            //model.made_date = input.made_date;
            //model.use_date = input.use_date;
            //model.purchase_money = input.purchase_money;
            //model.quality_date = input.quality_date;
            model.use_startdate = input.use_startdate;
            model.use_enddate = input.use_enddate;
            model.quality_startdate = input.quality_startdate;
            model.quality_enddate = input.quality_enddate;
            if (input.extensionlist != null)
            {
                model.extensionlist = input.extensionlist;
            }
            else
            {
                model.extensionlist = new List<ExtensionModel>();
            }
            model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.isdelete = 0;
            model.createtime = DateTime.Now;

            bool b = await _eqp_equipment_infoRepository.Add(model);
            if (b)
                return Success("添加成功");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改设备信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> Update(EquipmentInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.equipment_name))
                return Error("设备名称不能为空");
            if (string.IsNullOrEmpty(input.equipment_number))
                return Error("设备编码不能为空");
            var modelold = await _eqp_equipment_infoRepository.GetSingle(p => p.equipment_number == input.equipment_number && p.id != input.id && p.isdelete == 0);
            if (modelold != null)
            {
                return Error("设备编码已经存在");
            }
            #endregion
            var model = new Eqp_Equipment_Info();
            model = await _eqp_equipment_infoRepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");

            model.province = input.province;
            model.city = input.city;
            model.projectid = input.projectid;
            model.protypeid = input.protypeid;
            model.buildid = input.buildid;
            model.floorid = input.floorid;
            model.equipment_name = input.equipment_name;
            model.systemid = input.systemid;
            model.equipment_number = input.equipment_number;
            model.equipment_model = input.equipment_model;

            if (input.equipment_image != null)
            {
                model.equipment_image = input.equipment_image;
            }
            else
            {
                model.equipment_image = new List<FileBaseModel>();
            }
            if (input.purchase_order != null)
            {
                model.purchase_order = input.purchase_order;
            }
            else
            {
                model.purchase_order = new List<FileBaseModel>();
            }
            if (input.maintenance_order != null)
            {
                model.maintenance_order = input.maintenance_order;
            }
            else
            {
                model.maintenance_order = new List<FileBaseModel>();
            }

            //model.equipment_supplier = input.equipment_supplier;
            //model.equipment_manufacturer = input.equipment_manufacturer;
            //model.install_date = input.install_date;
            model.install_place = input.install_place;
            //model.inspect_date = input.inspect_date;
            //model.made_date = input.made_date;
            //model.use_date = input.use_date;
            //model.purchase_money = input.purchase_money;
            //model.quality_date = input.quality_date;
            model.use_startdate = input.use_startdate;
            model.use_enddate = input.use_enddate;
            model.quality_startdate = input.quality_startdate;
            model.quality_enddate = input.quality_enddate;

            if (input.extensionlist != null)
            {
                model.extensionlist = input.extensionlist.ToList<ExtensionModel>();
            }
            else
            {
                model.extensionlist = new List<ExtensionModel>();
            }

            bool b = await _eqp_equipment_infoRepository.UpdateOne(model);
            if (b)
                return Success("保存成功");
            return Error("保存失败");
        }

        /// <summary>
        /// 逻辑删除设备
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(string[] ids)
        {
            string usercode= User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var eq = await _eqp_equipment_infoRepository.GetSingle(item);
                    eq.isdelete = 1;
                    eq.deleteby = usercode;
                    eq.deletetime = DateTime.Now.ToLocalTime();
                    if (_eqp_equipment_infoRepository.UpdateOne(eq).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }


        /// <summary>
        /// 导出模板
        /// </summary>
        /// <returns></returns>
        [HttpGet("downtemplate")]
        [AllowAnonymous]
        public IActionResult DownTemplateAsync()
        {
            string mbname = _configuration["upload:mbname"].ToString();
            string mbkeys = _configuration["upload:mbkeys"].ToString();

            NPOIHelper npoi = new NPOIHelper();
            byte[] sm = npoi.ExportToExcelTemplate(mbkeys.Split(","));
            if (sm != null)
            {
                return File(sm, "application/vnd.ms-excel", mbname);
            }
            else
            {
                return Error("下载失败");
            }
        }

        /// <summary>
        /// 上传文件并将设备信息导入数据库
        /// </summary>
        /// <returns></returns>
        [HttpPost("importexcel")]
        public async Task<IActionResult> ImportExcel(string province, string city, string projectid, string protypeid,string bulidingid, string systemid, int headrow = 0)
        {
            if (string.IsNullOrEmpty(bulidingid))
                return Error("参数错误");
            if (string.IsNullOrEmpty(systemid))
                return Error("系统名称不能为空");

            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            Microsoft.AspNetCore.Http.IFormFile _upfile = Request.Form.Files[0];
            if (!_upfile.ContentType.Equals("application/vnd.ms-excel") && !_upfile.ContentType.Equals("application/x-xls") && !_upfile.ContentType.Equals("application/x-xlsx") && !_upfile.ContentType.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !_upfile.ContentType.Equals("application/octet-stream"))
                return Error($"请正确上传Excel文件：file.ContentType={_upfile.ContentType}");

            NPOIHelper npoi = new NPOIHelper();
            var dtExcel = npoi.ExcelToTable1(_upfile, headrow);
            int num = dtExcel.Rows.Count;
            var cols = dtExcel.Columns;
            int colnum = cols.Count;

            string dbkeys = _configuration["upload:dbkeys"].ToString();
            string[] dbcols = dbkeys.Split(",");
            string errmsg = string.Empty;

            if (num > 0)
            {
                int index = 1;
                foreach (System.Data.DataRow dr in dtExcel.Rows)
                {
                    var model = new Eqp_Equipment_Info();
                    model.province = province;
                    model.city =city;
                    model.projectid = projectid;
                    model.protypeid = protypeid;
                    model.buildid = bulidingid;
                    model.systemid = systemid;
                    model.isdelete = 0;
                    model.importid = "000000000000000000000000";
                    model.createby = usercode;

                    var floorname = dr[0].ToString();
                    model.floorid = _eqp_import_infoRepository.GetFloorId(floorname);
                    var dbcolslist = dbcols.ToList();

                    var sbbm = dr[dbcolslist.IndexOf("equipment_number")].ToString();
                    var modelold = await _eqp_equipment_infoRepository.GetSingle(p => p.equipment_number == sbbm && p.isdelete == 0);
                    if (modelold == null)
                    {

                        Type t = model.GetType();
                        PropertyInfo[] PropertyList = t.GetProperties();

                        foreach (PropertyInfo item in PropertyList)
                        {
                            if (dbcolslist.Contains(item.Name))
                            {
                                //string type = item.PropertyType.Name;
                                object v = Convert.ChangeType(dr[dbcolslist.IndexOf(item.Name)].ToString(), item.PropertyType);
                                item.SetValue(model, v, null);
                            }
                        }

                        model.equipment_image = new List<FileBaseModel>();
                        model.purchase_order = new List<FileBaseModel>();
                        model.maintenance_order = new List<FileBaseModel>();

                        List<ExtensionModel> ems = new List<ExtensionModel>();
                        for (int i = dbcols.Length; i < colnum; i++)
                        {
                            ExtensionModel em = new ExtensionModel();
                            em.name = cols[i].ColumnName;
                            em.value = dr[i].ToString();

                            ems.Add(em);
                        }

                        model.extensionlist = ems;

                        bool b = await _eqp_equipment_infoRepository.Add(model);
                        if (!b)
                        {
                            errmsg = errmsg + "\r\n第" + index + "行设备编码（" + sbbm + "）信息错误";
                        }
                        index++;
                    }
                    else
                    {
                        errmsg = errmsg + "\r\n第" + index + "行设备编码（" + sbbm + "）已经存在";
                    }
                }
            }
            else
            {
                return Error("文件中无数据");
            }

            if (!string.IsNullOrEmpty(errmsg))
            {
                //删除已导入的部分
                await _eqp_equipment_infoRepository.Remove(x => x.importid == "000000000000000000000000");
                return Error("导入失败，原因：" + errmsg);
            }

            #region 上传文件服务器
            string upresult = "";
            try
            {
                string url = _configuration["upload:url"].ToString();
                string poststr = _configuration["upload:params"].ToString();
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);

                if (poststr != "")
                {
                    foreach (string c in poststr.Split('&'))
                    {
                        string[] item = c.Split('=');
                        if (item.Length != 2)
                        {
                            break;
                        }
                        string name = item[0];
                        string value = item[1];
                        string strHeader = string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", name);
                        byte[] strByte = System.Text.Encoding.UTF8.GetBytes(strHeader);
                        postStream.Write(strByte, 0, strByte.Length);

                        byte[] valuebyte = System.Text.Encoding.UTF8.GetBytes(string.Format("{0}", value));
                        postStream.Write(valuebyte, 0, value.Length);

                        postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                    }
                }


                //请求头部信息 
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", _upfile.FileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
                //FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                Stream fs = _upfile.OpenReadStream();
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页（html）代码
                upresult = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                return Error("上传失败");
            }

            if (upresult == "")
            {
                return Error("上传失败");
            }
            #endregion

            var upobj = upresult.ToJObject();
            var fes = upobj["data"].ToString().ToObject<List<FileBaseModel>>();
            FileBaseModel fbm = fes[0];
            //导入记录保存数据库
            var modele = new Eqp_Import_Info();
            modele.province = province;
            modele.city = city;
            modele.projectid = projectid;
            modele.protypeid = protypeid;
            modele.buildid = bulidingid;
            modele.filename = fbm.filename;
            modele.fileurl = fbm.fileurl;
            modele.filesize = long.Parse(fbm.filesize);
            modele.filemd5 = fbm.filemd5;
            modele.fileext = fbm.fileext;
            modele.createby = usercode;
            modele.isdelete = 0;
            string FID = await _eqp_import_infoRepository.AddRetID(modele);

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("importid", FID);
            var listFilter = new List<FilterDefinition<Eqp_Equipment_Info>>();
            listFilter.Add(Builders<Eqp_Equipment_Info>.Filter.Where(s => s.importid == "000000000000000000000000"));
            var filter = Builders<Eqp_Equipment_Info>.Filter.And(listFilter);
            await _eqp_equipment_infoRepository.UpdateManay(new Eqp_Equipment_Info(), dic, filter);

            return Success("导入成功");
        }

        ///// <summary>
        ///// 导入Excel列表
        ///// </summary>
        ///// <param name="keyword"></param>
        ///// <param name="stime"></param>
        ///// <param name="etime"></param>
        ///// <param name="pageindex"></param>
        ///// <param name="pagesize"></param>
        ///// <returns></returns>
        //[HttpGet("getimportlistbypage")]
        //public async Task<IActionResult> GetImportListsByPageAsync(string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        //{
        //    #region 条件信息
        //    ////排序字段
        //    var sort = Builders<Eqp_Import_Info>.Sort.Descending("createtime");

        //    //根据条件查询集合
        //    var listApp = new List<FilterDefinition<Eqp_Import_Info>>();
        //    listApp.Add(Builders<Eqp_Import_Info>.Filter.Eq("isdelete", 0));
        //    if (!string.IsNullOrEmpty(stime))
        //        listApp.Add(Builders<Eqp_Import_Info>.Filter.Gt("createtime", stime));
        //    if (!string.IsNullOrEmpty(etime))
        //        listApp.Add(Builders<Eqp_Import_Info>.Filter.Lt("createtime", etime));
        //    //模糊查询(学习资料标题)
        //    if (!string.IsNullOrEmpty(keyword))
        //        listApp.Add(Builders<Eqp_Import_Info>.Filter.Where(s => s.filename.Contains(keyword)));
        //    #endregion

        //    var filter = Builders<Eqp_Import_Info>.Filter.And(listApp);
        //    var list = await _eqp_import_infoRepository.GetByPage(filter, pageindex, pagesize, sort);
        //    var redCount = await _eqp_import_infoRepository.CountAsync(filter);   //获取总数

        //    var obj = new
        //    {
        //        state = "success",
        //        message = "成功",
        //        rows = list,
        //        total = redCount,
        //    };
        //    return Content(obj.ToJson());

        //}

        /// <summary>
        /// 导入Excel列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getimportlistbypage")]
        public IActionResult GetImportListsByPage(string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _eqp_import_infoRepository.GetImportListsByPage(keyword, stime, etime, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount,
            };
            return Success("获取成功", obj);

        }

        /// <summary>
        /// 删除Excel记录（同时删除对应导入设备信息）
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deleteimport")]
        public async Task<IActionResult> DeleteImport(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    //删除excel记录
                    var ml = await _eqp_import_infoRepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteby = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_eqp_import_infoRepository.Update(ml).Result)
                    {
                        res += 1;
                        #region 批量删除 - 删除对应excel记录id所有设备信息
                        var imodel = new Eqp_Equipment_Info();
                        Dictionary<string, string> dic = new Dictionary<string, string>();
                        dic.Add("isdelete", "1");
                        dic.Add("deleteby", usercode);
                        dic.Add("deletetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        var list = new List<FilterDefinition<Eqp_Equipment_Info>>();
                        var filterBuilder = Builders<Eqp_Equipment_Info>.Filter;
                        list.Add(filterBuilder.Eq("importid", item));
                        var filter = Builders<Eqp_Equipment_Info>.Filter.And(list);
                        await _eqp_equipment_infoRepository.UpdateManay(imodel, dic, filter);
                        #endregion
                    }
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 获取树信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getfivetree")]
        public IActionResult GetFiveTree()
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var obj = _eqp_equipment_infoRepository.GetFiveTree(userinfo);
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取项目树
        /// </summary>
        /// <returns></returns>
        [HttpGet("getprojecttree")]
        public IActionResult GetProjectTree()
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var obj = _eqp_equipment_infoRepository.GetProjectTree(userinfo);
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取树信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getaddresstree")]
        public IActionResult GetAddressTree(string projectid)
        {
            var obj = _eqp_equipment_infoRepository.GetAddressTree(projectid);
            return Success("成功", obj);
        }

        /// <summary>
        /// 根据楼层id获取详细信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("gettreeinfo")]
        public IActionResult GetTreeInfo(string floorid)
        {
            var obj = _eqp_equipment_infoRepository.GetTreeInfo(floorid);
            return Success("成功", obj);
        }

    }
}