using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Sugar.Enties;
using Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.IO;
using MimeMapping;

namespace PMS.NetCore.Controllers
{
    /// <summary>
    /// 系统配置
    /// </summary>
    [Produces("application/json;charset=UTF-8")]
    [Route("api/SystemConfiguration")]
    [ServiceFilter(typeof(Filter.TokenAuthorize))]
    public class SystemConfigurationController : BaseController
    {
        /// <summary>
        /// 存储模式  file:文件  ，database：数据库
        /// </summary>
        private string savePattern = "file";
        /// <summary>
        /// 文件存储目录
        /// </summary>
        private string savePath = "/uploadimg";

        /// <summary>
        /// 系统配置
        /// </summary>
        public SystemConfigurationController()
        {
            logger = NLog.LogManager.GetCurrentClassLogger();
        }
        #region 结算方式
        /// <summary>
        /// 获取结算方式列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetSettleTypeList")]
        public JsonResult GetSettleTypeList()
        {
            var manager = new settletypeManager();
            var list = manager.GetList();
            logger.Info($"【GetSettleTypeList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 根据结算方式编码获取结算方式实例
        /// </summary>
        /// <param name="dto">结算方式编码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetSettleType")]
        public JsonResult GetSettleType([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetSettleType】dto:{dto.value}");
            if (dto.value.IsNullOrEmpty())
            {
                return Json("结算方式编码不能为空");

            }
            var model = new settletypeManager().GetById(dto.value);
            logger.Info($"【GetSettleType】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);

        }

        /// <summary>
        /// 结算方式添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SettleTypeAdd")]
        public JsonResult SettleTypeAdd([FromBody] settletype dto)
        {
            logger.Info($"【SettleTypeAdd】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto.csscode.IsNullOrEmpty())
            {
                return Json("结算方式编码不能为空");
            }
            var manager = new settletypeManager();
            var model = manager.GetById(dto.csscode);
            if (model != null)
            {
                return Json("结算方式编码必须唯一");
            }
            var success = manager.Insert(dto);
            if (success)
            {
                return Json("插入成功");
            }
            else
            {
                return Json("插入失败");
            }
        }

        /// <summary>
        /// 结算方式修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SettleTypeUpdate")]
        public JsonResult SettleTypeUpdate([FromBody] settletype dto)
        {
            logger.Info($"【SettleTypeUpdate】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto.csscode.IsNullOrEmpty())
            {
                return Json("结算方式编码不能为空");
            }
            var manager = new settletypeManager();
            var model = manager.GetById(dto.csscode);
            if (model == null)
            {
                return Json("要修改的结算方式不存在");
            }
            var success = manager.Update(dto);
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }

        /// <summary>
        /// 结算方式删除
        /// </summary>
        /// <param name="dto">结算方式主键值</param>
        /// <returns></returns>
        [HttpPost]
        [Route("SettleTypeDelete")]
        public JsonResult SettleTypeDelete([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【SettleTypeDelete】dto:{JsonConvert.SerializeObject(dto)}");

            var manager = new settletypeManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("要删除的结算方式不存在");
            }
            var success = manager.Delete(m => m.csscode == dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }
        }
        #endregion

        #region 会计科目
        /// <summary>
        /// 分页获取会计科目
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页面条数</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCodeList")]
        public JsonResult GetCodeList(int pageIndex, int pageSize)
        {
            logger.Info($"【GetCodeList】pageIndex:{pageSize},pageSize:{pageSize}");
            if (pageSize <= 0 || pageIndex <= 0)
            {
                return Json("页码或页面条数不能小于等于0");
            }
            var manager = new codeManager();
            var list = manager.Db.Queryable<code>().ToPageList(pageIndex, pageSize);
            logger.Info($"【GetCodeList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }
        #endregion

        #region 业态档案
        /// <summary>
        /// 获取业态档案列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFdc_pm_operstateList")]
        public JsonResult GetFdc_pm_operstateList()
        {
            var manager = new fdc_pm_operstateManager();
            var list = manager.GetList();
            logger.Info($"【GetFdc_pm_operstateList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取业态档案实例
        /// </summary>
        /// <param name="dto">业态档案主键值</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFdc_pm_operstate")]
        public JsonResult GetFdc_pm_operstate([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetFdc_pm_operstate】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto == null || dto.value.IsNullOrEmpty())
            {
                return Json("参数错误");
            }
            var manager = new fdc_pm_operstateManager();
            var model = manager.GetById(dto.value);
            logger.Info($"【GetFdc_pm_operstate】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }

        /// <summary>
        /// 业态档案添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_operstateAdd")]
        public JsonResult Fdc_pm_operstateAdd([FromBody] fdc_pm_operstate dto)
        {
            logger.Info($"【Fdc_pm_operstateAdd】dto:{JsonConvert.SerializeObject(dto)}");
            if (!dto.scode.IsInteger())
            {
                return Json("业态编码格式不正确，只能是数字形式");
            }
            if (dto.sname.IsNullOrEmpty())
            {
                return Json("业态名称不能为空");
            }
            if (!dto.fathercode.IsInteger())
            {
                return Json("上级节点编码格式不正确，只能是数字形式");
            }

            if (dto.scode == dto.fathercode)
            {
                return Json("不能设置自身为上级节点");
            }
            var manager = new fdc_pm_operstateManager();
            var model = manager.GetById(dto.scode);
            if (model != null)
            {
                return Json("业态编码必须唯一");
            }
            var fatherModel = manager.GetById(dto.fathercode);
            if (fatherModel == null && dto.fathercode != "0")
            {
                return Json("父节点不存在");
            }
            var success = manager.Insert(dto);
            logger.Info($"【Fdc_pm_operstateAdd】success:{success}");
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");
            }
        }

        /// <summary>
        /// 业态档案修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_operstateUpdate")]
        public JsonResult Fdc_pm_operstateUpdate([FromBody] fdc_pm_operstate dto)
        {
            logger.Info($"【Fdc_pm_operstateUpdate】dto:{JsonConvert.SerializeObject(dto)}");
            if (!dto.scode.IsInteger())
            {
                return Json("业态编码格式不正确，只能是数字形式");
            }
            if (dto.sname.IsNullOrEmpty())
            {
                return Json("业态名称不能为空");
            }
            if (!dto.fathercode.IsInteger())
            {
                return Json("上级节点编码格式不正确，只能是数字形式");
            }
            if (dto.scode == dto.fathercode)
            {
                return Json("不能设置自身为上级节点");
            }
            var manager = new fdc_pm_operstateManager();
            var model = manager.GetById(dto.scode);
            if (model == null)
            {
                return Json("业态档案不存在");
            }
            var fatherModel = manager.GetById(dto.fathercode);
            if (fatherModel == null && dto.fathercode != "0")
            {
                return Json("父节点不存在");
            }
            model = dto;
            var success = manager.Update(model);
            logger.Info($"【Fdc_pm_operstateUpdate】success:{success}");
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }

        /// <summary>
        /// 业态档案删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_operstateDelete")]
        public JsonResult Fdc_pm_operstateDelete([FromBody] SingleParamDTO dto)
        {
            if (dto.value.IsNullOrEmpty())
            {
                return Json("要删除的业态编码不能为空");
            }
            var manager = new fdc_pm_operstateManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("要删除的记录不存在");
            }
            var success = manager.CurrentDb.DeleteById(dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }

        }
        #endregion

        #region 户型档案
        /// <summary>
        /// 获取户型档案列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFdc_pm_modelList")]
        public JsonResult GetFdc_pm_modelList()
        {
            var manager = new fdc_pm_modelManager();
            var list = manager.GetList();
            logger.Info($"【GetFdc_pm_modelList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取户型档案实例
        /// </summary>
        /// <param name="dto">户型档案主键值</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFdc_pm_model")]
        public JsonResult GetFdc_pm_model([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetFdc_pm_model】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto == null || dto.value.IsNullOrEmpty())
            {
                return Json("参数错误");
            }
            var manager = new fdc_pm_modelManager();
            var model = manager.GetById(dto.value);
            logger.Info($"【GetFdc_pm_model】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }

        /// <summary>
        /// 户型档案添加
        /// </summary>
        /// <param name="dto">户型档案实例</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_modelAdd")]
        public JsonResult Fdc_pm_modelAdd([FromBody] fdc_pm_model dto)
        {
            logger.Info($"【Fdc_pm_modelAdd】dto:{JsonConvert.SerializeObject(dto)}");

            var manager = new fdc_pm_modelManager();
            var model = manager.GetById(dto.autoid);
            if (model != null)
            {
                return Json("编号必须唯一");
            }
            var model2 = new fdc_pm_operstateManager().GetById(dto.scode);
            if (model2 == null)
            {
                return Json("所属业态不存在");
            }
            var success = manager.Insert(dto);
            logger.Info($"【Fdc_pm_modelAdd】success:{success}");
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");
            }
        }


        /// <summary>
        /// 户型档案删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_modelDelete")]
        public JsonResult Fdc_pm_modelDelete([FromBody] SingleParamDTO dto)
        {
            if (dto.value.IsNullOrEmpty())
            {
                return Json("要删除的户型档案编号不能为空");
            }
            var manager = new fdc_pm_modelManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("要删除的记录不存在");
            }
            var success = manager.CurrentDb.DeleteById(dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }

        }
        #endregion

        #region 朝向档案
        /// <summary>
        /// 获取朝向档案列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFdc_pm_directionList")]
        public JsonResult GetFdc_pm_directionList()
        {
            var manager = new fdc_pm_directionManager();
            var list = manager.GetList();
            logger.Info($"【GetFdc_pm_directionList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取户朝向案实例
        /// </summary>
        /// <param name="dto">朝向档案主键值</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFdc_pm_direction")]
        public JsonResult GetFdc_pm_direction([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetFdc_pm_direction】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto == null || dto.value.IsNullOrEmpty())
            {
                return Json("参数错误");
            }
            var manager = new fdc_pm_directionManager();
            var model = manager.GetById(dto.value);
            logger.Info($"【GetFdc_pm_direction】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }

        /// <summary>
        /// 朝向档案添加
        /// </summary>
        /// <param name="dto">朝向档案实例</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_directionAdd")]
        public JsonResult Fdc_pm_directionAdd([FromBody] fdc_pm_direction dto)
        {
            logger.Info($"【Fdc_pm_directionAdd】dto:{JsonConvert.SerializeObject(dto)}");

            var manager = new fdc_pm_directionManager();

            if (dto.direction.IsNullOrEmpty())
            {
                return Json("朝向不能为空");
            }
            var success = manager.Insert(dto);
            logger.Info($"【Fdc_pm_directionAdd】success:{success}");
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");
            }
        }


        /// <summary>
        /// 朝向档案删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_directionDelete")]
        public JsonResult Fdc_pm_directionDelete([FromBody] SingleParamDTO dto)
        {
            if (dto.value.IsNullOrEmpty())
            {
                return Json("要删除的户型档案编号不能为空");
            }
            var manager = new fdc_pm_directionManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("要删除的记录不存在");
            }
            var success = manager.CurrentDb.DeleteById(dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }

        }
        #endregion

        #region 项目档案
        /// <summary>
        /// 获取项目档案列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("GetFdc_pm_projectList")]
        public JsonResult GetFdc_pm_projectList()
        {
            var manager = new fdc_pm_projectManager();
            var list = manager.GetList().OrderBy(m => m.autoid);
            logger.Info($"【GetFdc_pm_projectList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取项目档案实例
        /// </summary>
        /// <param name="dto">项目档案编码</param>
        /// <returns></returns>        
        [HttpPost]
        [Route("GetFdc_pm_project")]
        public JsonResult GetFdc_pm_project([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetFdc_pm_project】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto == null || dto.value.IsNullOrEmpty())
            {
                return Json("参数错误");
            }
            var manager = new fdc_pm_projectManager();
            var model = manager.GetById(dto.value);
            logger.Info($"【GetFdc_pm_project】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }

        /// <summary>
        /// 获取项目楼栋档案
        /// </summary>
        /// <returns></returns>        
        [HttpGet]
        [Route("GetFdc_pm_projectBuild")]
        [AllowAnonymous]
        public JsonResult GetFdc_pm_projectBuild(string staffcode)
        {
            logger.Info($"【GetFdc_pm_projectBuild】dto:{JsonConvert.SerializeObject(staffcode)}");
            var manager = new fdc_pm_projectManager();
            var model = manager.GetProjectBuild(staffcode);
            logger.Info($"【GetFdc_pm_projectBuild】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }


        /// <summary>
        /// 获取房产详细仪表
        /// </summary>
        /// <returns></returns>        
        [HttpGet]
        [Route("Getfdc_pm_housemeterList")]
        [AllowAnonymous]
        public JsonResult Getfdc_pm_housemeterList(string bcode, string staffcode, string metertypename, int pageNumber, int pageSize)
        {
            logger.Info($"【Getfdc_pm_housemeterList】dto:{JsonConvert.SerializeObject(bcode + "-" + staffcode)}");
            var manager = new fdc_pm_housemeterManager();
            var model = manager.GetHouseMeter(staffcode, bcode, metertypename, pageNumber, pageSize);
            logger.Info($"【Getfdc_pm_housemeterList】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }


        /// <summary>
        /// 项目档案添加
        /// </summary>
        /// <param name="dto">项目档案实例</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_projectAdd")]
        public JsonResult Fdc_pm_projectAdd([FromBody] fdc_pm_project dto)
        {
            logger.Info($"【Fdc_pm_projectAdd】dto:{JsonConvert.SerializeObject(dto)}");

            var manager = new fdc_pm_projectManager();

            if (dto.pcode.IsNullOrEmpty())
            {
                return Json("编码不能为空");
            }
            var entity = manager.GetById(dto.pcode);
            if (entity != null)
            {
                return Json("编码必须唯一");
            }
            if (dto.pname.IsNullOrEmpty())
            {
                return Json("项目名称不能为空");
            }
            if (dto.fathercode.IsNullOrEmpty() || dto.fathercode == "o")    //父级项目为空
            {
                dto.fathercode = "o";      //赋默认值

            }
            else
            {
                var model = manager.GetById(dto.fathercode);
                if (model == null)
                {
                    return Json("父级项目不存在");
                }
            }

            var success = manager.Insert(dto);
            logger.Info($"【Fdc_pm_projectAdd】success:{success}");
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");
            }
        }

        /// <summary>
        /// 项目档案修改
        /// </summary>
        /// <param name="dto">项目档案实例</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_projectUpdate")]
        public JsonResult Fdc_pm_projectUpdate([FromBody] fdc_pm_project dto)
        {
            logger.Info($"【Fdc_pm_projectUpdate】dto:{JsonConvert.SerializeObject(dto)}");

            var manager = new fdc_pm_projectManager();

            if (dto.pcode.IsNullOrEmpty())
            {
                return Json("编码不能为空");
            }
            var entity = manager.GetById(dto.pcode);
            if (entity == null)
            {
                return Json("不存在的项目档案");
            }
            if (dto.pname.IsNullOrEmpty())
            {
                return Json("项目名称不能为空");
            }
            if (dto.fathercode.IsNullOrEmpty() || dto.fathercode == "o")    //父级项目为空
            {
                dto.fathercode = "o";      //赋默认值

            }
            else
            {
                var model = manager.GetById(dto.fathercode);
                if (model == null)
                {
                    return Json("父级项目不存在");
                }
            }
            entity.pname = dto.pname;
            entity.fathercode = dto.fathercode;
            entity.psgn = dto.psgn;
            entity.flag = dto.flag;
            entity.paddress = dto.paddress;
            entity.pclass = dto.pclass;
            entity.pdevcom = dto.pdevcom;
            entity.ptype = dto.ptype;
            entity.memo = dto.memo;
            entity.url = dto.url;
            entity.cltemccode = dto.cltemccode;


            var success = manager.Update(entity);
            logger.Info($"【Fdc_pm_projectUpdate】success:{success}");
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }

        /// <summary>
        /// 项目档案删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_projectDelete")]
        public JsonResult Fdc_pm_projectDelete([FromBody] SingleParamDTO dto)
        {
            if (dto.value.IsNullOrEmpty())
            {
                return Json("要删除的项目档案编号不能为空");
            }
            var manager = new fdc_pm_projectManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("要删除的记录不存在");
            }
            var success = manager.CurrentDb.DeleteById(dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }

        }
        #endregion

        #region 管理处
        /// <summary>
        /// 管理处列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("Getfdc_pm_managementsecList")]
        public JsonResult Getfdc_pm_managementsecList()
        {
            var manager = new fdc_pm_managementsecManager();
            var list = manager.GetList();
            logger.Info($"【Getfdc_pm_managementsecList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取管理处实例
        /// </summary>
        /// <param name="dto">管理处编码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Getfdc_pm_managementsec")]
        public JsonResult Getfdc_pm_managementsec([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【Getfdc_pm_managementsec】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto == null || dto.value.IsNullOrEmpty())
            {
                return Json("参数错误");
            }
            var manager = new fdc_pm_managementsecManager();
            var model = manager.GetById(dto.value);
            logger.Info($"【Getfdc_pm_managementsec】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }

        /// <summary>
        /// 管理处添加
        /// </summary>
        /// <param name="dto">管理处实例</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fdc_pm_managementsecAdd")]
        public JsonResult fdc_pm_managementsecAdd([FromBody] fdc_pm_managementsec dto)
        {
            logger.Info($"【fdc_pm_managementsecAdd】dto:{JsonConvert.SerializeObject(dto)}");

            var manager = new fdc_pm_managementsecManager();
            var number = manager.Db.Ado.GetInt("SELECT MAX(CAST(pk_managementsecid AS int)) FROM fdc_pm_managementsec");
            dto.pk_managementsecid = (number + 1).ToString();

            var entity = manager.GetById(dto.pk_managementsecid);
            if (entity != null)
            {
                return Json("管理处编号必须唯一");
            }
            if (dto.managementsecname.IsNullOrEmpty())
            {
                return Json("管理处名称不能为空");
            }

            if (dto.ibuildcount.IsNullOrEmpty())
            {
                return Json("楼栋数不能为空");
            }
            if (dto.nmanagementarea.IsNullOrEmpty())
            {
                return Json("管理面积不能为空");
            }
            var success = manager.Insert(dto);
            logger.Info($"【fdc_pm_managementsecAdd】success:{success}");
            if (success)
            {
                return Json("添加成功");
            }
            else
            {
                return Json("添加失败");
            }
        }

        /// <summary>
        /// 项目档案修改
        /// </summary>
        /// <param name="dto">项目档案实例</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fdc_pm_managementsecUpdate")]
        public JsonResult fdc_pm_managementsecUpdate([FromBody] fdc_pm_managementsec dto)
        {
            logger.Info($"【fdc_pm_managementsecUpdate】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto.pk_managementsecid.IsNullOrEmpty())
            {
                return Json("管理处编号不能为空");
            }
            var manager = new fdc_pm_managementsecManager();
            var entity = manager.GetById(dto.pk_managementsecid);
            if (entity == null)
            {
                return Json("记录不存在");
            }
            if (dto.managementsecname.IsNullOrEmpty())
            {
                return Json("管理处名称不能为空");
            }

            if (dto.ibuildcount.IsNullOrEmpty())
            {
                return Json("楼栋数不能为空");
            }
            if (dto.nmanagementarea.IsNullOrEmpty())
            {
                return Json("管理面积不能为空");
            }

            entity.managementsecname = dto.managementsecname;
            entity.ibuildcount = dto.ibuildcount;
            entity.nmanagementarea = dto.nmanagementarea;
            entity.iemployercount = dto.iemployercount;
            entity.imanagecount = dto.imanagecount;
            entity.itechcount = dto.itechcount;
            entity.isecuritycount = dto.isecuritycount;
            entity.idustcount = dto.idustcount;
            entity.ncontractarea = dto.ncontractarea;
            entity.dcontractdate = dto.dcontractdate;
            entity.iroomcount = dto.iroomcount;
            entity.iparkspacecount = dto.iparkspacecount;
            entity.ngreenarea = dto.ngreenarea;
            entity.vywhtel = dto.vywhtel;
            entity.dywhsetupdate = dto.dywhsetupdate;
            entity.vmanager = dto.vmanager;
            entity.vmanagetel = dto.vmanagetel;


            var success = manager.Update(entity);
            logger.Info($"【fdc_pm_managementsecUpdate】success:{success}");
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }

        /// <summary>
        /// 项目档案删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("fdc_pm_managementsecDelete")]
        public JsonResult fdc_pm_managementsecDelete([FromBody] SingleParamDTO dto)
        {
            if (dto.value.IsNullOrEmpty())
            {
                return Json("要删除的项目档案编号不能为空");
            }
            var manager = new fdc_pm_managementsecManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("要删除的记录不存在");
            }
            var success = manager.CurrentDb.DeleteById(dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }

        }
        /// <summary>
        /// 给管理处分配费用项目权限
        /// </summary>
        /// <param name="managementId">管理处编号</param>
        /// <param name="billsitemIds">费用项编号串，由逗号分割</param>
        /// <returns></returns>
        [HttpPost]
        [Route("DistributionManagementBillsItem")]
        public JsonResult DistributionManagementBillsItem(string managementId, string billsitemIds)
        {
            logger.Info($"【DistributionManagementBillsItem】managementId:{managementId},billsitemIds:{billsitemIds}");
            if (managementId.IsNullOrEmpty())
            {
                return Json("请选择管理处");
            }
            var arr = billsitemIds.Split(',');
            if (arr.Length <= 0)
            {
                return Json("请选择费用项目");
            }
            var manager = new MangmengBillsitemManager();
            try
            {
                return Json("");
            }
            catch (Exception ex)
            {
                return Json("");
            }

        }
        #endregion

        #region 收费项目
        /// <summary>
        /// 获取所有收费项
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("Getfdc_pm_billsitemList")]
        public JsonResult Getfdc_pm_billsitemList()
        {
            var manager = new fdc_pm_billsitemManager();
            var list = manager.Getfdc_pm_billsitemList();
            logger.Info($"【fdc_pm_managementsecUpdate】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }
        #endregion

        #region 管理处人员引用

        #endregion

        #region 楼栋档案
        /// <summary>
        /// 获取楼栋列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("GetFdc_pm_buildList")]
        public JsonResult GetFdc_pm_buildList([FromBody] SingleParamDTO dto)
        {
            var manager = new fdc_pm_buildManager();
            var list = manager.GetList(m => m.pcode == dto.value);
            logger.Info($"【GetFdc_pm_buildList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        #endregion


        #region  房产资料
        /// <summary>
        /// 获取房产资料列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("GetFdc_pm_houseList")]
        public JsonResult GetFdc_pm_houseList()
        {
            var manager = new fdc_pm_houseManager();
            var list = manager.GetList();
            logger.Info($"【GetFdc_pm_houseList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取房产资料列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("GetFdc_pm_houseListByBcode")]
        public JsonResult GetFdc_pm_houseListByBcode([FromBody] SingleParamDTO dto)
        {
            var manager = new fdc_pm_houseManager();
            var list = manager.GetList(m => m.bcode == dto.value);
            logger.Info($"【GetFdc_pm_houseList】list:{JsonConvert.SerializeObject(list)}");
            return Json(list);
        }

        /// <summary>
        /// 获取房产资料实例
        /// </summary>
        /// <param name="dto">房号</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetFdc_pm_house")]
        public JsonResult GetFdc_pm_house([FromBody] SingleParamDTO dto)
        {
            logger.Info($"【GetFdc_pm_house】dto:{JsonConvert.SerializeObject(dto)}");
            if (dto == null || dto.value.IsNullOrEmpty())
            {
                return Json("参数错误");
            }
            var manager = new fdc_pm_houseManager();
            var model = manager.GetById(dto.value);
            logger.Info($"【GetFdc_pm_house】model:{JsonConvert.SerializeObject(model)}");
            return Json(model);
        }

        /// <summary>
        /// 房产资料添加Fdc_pm_housetAdd
        /// </summary>
        /// <param name="list">房产资料实例</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("Fdc_pm_housetAdd")]
        public JsonResult Fdc_pm_houseAdd([FromBody] List<fdc_pm_house> list)
        {
            logger.Info($"【Fdc_pm_houseAdd】list:{JsonConvert.SerializeObject(list)}");
            var errMsg = "";

            try
            {
                var manager = new fdc_pm_houseManager();
                foreach (var dto in list)
                {
                    var index = list.IndexOf(dto);
                    if (dto.hcode.IsNullOrEmpty())
                    {
                        errMsg += $"第{index + 1}条数据房产编号不能为空;";
                    }
                    var entity = manager.GetById(dto.hcode);
                    if (entity != null)
                    {
                        errMsg += $"第{index + 1}条数据房产编号已存在;";
                    }
                    if (dto.hname.IsNullOrEmpty())
                    {
                        errMsg += $"第{index + 1}条数据房产名称不能为空;";
                    }
                    if (dto.bcode.IsNullOrEmpty())
                    {
                        errMsg += $"第{index + 1}条数据楼栋编号不能为空;";
                    }
                    else
                    {
                        var service = new fdc_pm_buildManager();
                        var model = service.fdc_pm_buildDb.GetSingle(m => m.bcode == dto.bcode);
                        if (model == null)
                        {
                            errMsg += $"第{index + 1}条数据楼栋编号不存在;";
                        }
                    }
                }
                if (errMsg.IsNotNullAndEmpty())
                {
                    return Json(errMsg);
                }


                var row = manager.Db.Insertable(list).ExecuteCommand();
                logger.Info($"【Fdc_pm_houseAdd】row:{row}");
                return Json(row > 0 ? true : false);

            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return Json(ex.Message);
            }


        }


        /// <summary>
        /// 房产资料修改
        /// </summary>
        /// <param name="dto">房产资料实例</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_houseUpdate")]
        public JsonResult Fdc_pm_houseUpdate([FromBody] fdc_pm_house dto)
        {
            logger.Info($"【Fdc_pm_houseUpdate】dto:{JsonConvert.SerializeObject(dto)}");

            var manager = new fdc_pm_houseManager();

            if (dto.hcode.IsNullOrEmpty())
            {
                return Json("房号不能为空");
            }
            var entity = manager.GetById(dto.hcode);
            if (entity == null)
            {
                return Json("不存在的房产");
            }
            if (dto.hname.IsNullOrEmpty())
            {
                return Json("房产名称不能为空");
            }
            entity.bcode = dto.bcode;
            entity.hname = dto.hname;
            entity.operstatename = dto.operstatename;
            entity.hunit = dto.hunit;
            entity.hparea = dto.hparea;
            entity.hfloor = dto.hfloor;
            entity.hbarea = dto.hbarea;
            entity.hinarea = dto.hinarea;
            entity.cmemo = dto.cmemo;


            var success = manager.Update(entity);
            logger.Info($"【Fdc_pm_projectUpdate】success:{success}");
            if (success)
            {
                return Json("修改成功");
            }
            else
            {
                return Json("修改失败");
            }
        }

        /// <summary>
        /// 房产资料删除
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Fdc_pm_houseDelete")]
        public JsonResult Fdc_pm_houseDelete([FromBody] SingleParamDTO dto)
        {
            if (dto.value.IsNullOrEmpty())
            {
                return Json("要删除的房号不能为空");
            }
            var manager = new fdc_pm_houseManager();
            var model = manager.GetById(dto.value);
            if (model == null)
            {
                return Json("要删除的记录不存在");
            }
            var success = manager.CurrentDb.DeleteById(dto.value);
            if (success)
            {
                return Json("删除成功");
            }
            else
            {
                return Json("删除失败");
            }

        }
        #endregion

        #region 图片上传和显示
        /// <summary>
        /// /图片上传
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [DisableRequestSizeLimit]      //禁用大小限制
        [Route("UploadImage")]
        public JsonResult UploadImage([FromForm] IFormCollection formCollection)
        {
            //var list = new List<fdc_pm_file>();
            var code = Request.Form["code"].ToString();
            FormFileCollection filelist = (FormFileCollection)formCollection.Files;

            var manager = new fdc_pm_fileManager();
            if (savePattern == "file")    //文件存储到文件目录下
            {
                foreach (IFormFile file in filelist)
                {
                    //保存到数据库
                    var attachMent = new fdc_pm_file();
                    var extname = Path.GetExtension(file.FileName);
                    attachMent.filename = file.FileName.Replace(extname, "");

                    var content_type = file.ContentType;

                    var length = (int)file.Length;

                    attachMent.fileurl = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);

                    attachMent.code = code;
                    manager.Insert(attachMent);
                    #region 存文件到文件夹
                    var filePath = savePath;

                    //获取日期路径                   
                    filePath += $"/{file.FileName}";
                    using (var sw = System.IO.File.Open(filePath, FileMode.Create, FileAccess.Write))
                    {
                        var stream = file.OpenReadStream();
                        var content = Utils.UploadFileHelper.StreamToBytes(stream);
                        sw.Write(content, 0, content.Length);
                        sw.Close();
                    }
                    #endregion

                }
            }
            else                  //文件存储到数据库
            {
                foreach (IFormFile file in filelist)
                {
                    //var attachMent = new AttachMent();
                    //attachMent.FileName = file.FileName;
                    //attachMent.Content_Type = file.ContentType;
                    //attachMent.Length = (int?)file.Length;
                    //var stream = file.OpenReadStream();
                    //attachMent.Content = Utils.UploadFileHelper.StreamToBytes(stream);
                    //attachMent.AttachMentType = attachMentType;
                    //attachMent.CreatePerson = createPerson;
                    //attachMent.MasterCode = masterCode;
                    //manager.AddOrUpdate(attachMent);
                }
            }


            return Json("success");
        }

        /// <summary>
        /// 附件显示
        /// </summary>
        /// <param name="autoid"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [Route("ShowImg")]
        public FileResult ShowImg(string autoid)
        {
            var bll = new fdc_pm_fileManager();
            var entity = bll.GetList(m => m.autoid == autoid.ToInteger()).FirstOrDefault();
            if (entity.fileurl != null)     //从数据库读取
            {
                var filePath = savePath;
                var filename = entity.fileurl;

                filePath += $"/{filePath}/{filename}";

                logger.Info($"附件保存路径：{filePath}");
                if (!System.IO.File.Exists(filePath))
                {
                    RedirectToAction("NotFound");
                }
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] infbytes = new byte[(int)fs.Length];
                fs.Read(infbytes, 0, infbytes.Length);
                fs.Close();
                var contentType = MimeUtility.GetMimeMapping(filePath);
                return File(infbytes, contentType);

            }
            else
            {
                RedirectToAction("NotFound");
            }

            return null;
        }
        #endregion
    }
}
