using CallCenter.Utility;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.Wiki
{
    [Authority]
    public class LawGuideController : BaseController
    {
        // GET: LawGuide

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile()
        {
            HttpFileCollection files = RequestString.GetFiles();
            if (files.Count > 0)
            {
                List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                string path = "/Upload/Wiki/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];
                    FileUp fu = new FileUp();

                    string name = fu.Upload(file, path);

                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = name;//附件名称
                    model_T_Sys_Accessories.F_FileType = System.IO.Path.GetExtension(file.FileName);//附件类型
                    model_T_Sys_Accessories.F_FileUrl = path + name;//附件地址
                    model_T_Sys_Accessories.F_Size = file.ContentLength;
                    model_T_Sys_Accessories.F_UserCode = User.F_UserCode;//上传人  
                    int id = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    model_T_Sys_Accessories.F_FileId = id;
                    acs.Add(model_T_Sys_Accessories);
                }

                return Success("成功", acs);
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetList(string keyvalue, string stime, string etime, int key = 0, int page = 1, int pagesize = 10, int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string sqldt = "";

            if (stime.Trim() != "" && stime != "undefined")
            {
                sql += " and F_FaBuShiJian >= '" + stime + "' ";
            }
            if (etime.Trim() != "" && etime != "undefined")
            {
                sql += " and F_FaBuShiJian <= '" + etime + "' ";
            }

            if (key>0)
            {
                //sql += " and F_Key = " + key;

                sqldt = " INNER JOIN [GetValueId]('" + key + "') Value on a.F_Key = Value.F_ValueId";
            }
            if (!string.IsNullOrEmpty(keyvalue))
            {
                sql += " and (F_YeWuMingCheng like '%" + keyvalue + "%' or F_BanLiLiuCheng like '%" + keyvalue + "%' or F_QiTaShuoMing like '%" + keyvalue + "%' )";
            }

         

            if (isdc > 0)
            {
                string cols = "'B'+ RIGHT ('00000'+CONVERT (varchar(10),a.F_Id),6) as 序号,F_HangYe as 所属行业 ,F_YeWuMingCheng as 业务名称,F_ShenQingTiaoJian as 申请条件,F_BanLiLiuCheng as 办理流程,F_BanLiCaiLiao as 办理材料,F_BanLiShiXian as 办理时限,F_BanLiDiDian as 办理地点,F_BanLiShiJian as 办理时间,F_BanLiDianHua as 办理电话,F_QiTaShuoMing as 其他说明, F_DiQu as 地区,F_ZhengCeYiJu as 政策依据,F_ShengXiaoShiJian as 生效时间,F_ShiXiaoShiJian as 失效时间,dbo.GetKeyNames(F_Key)  as 四级关键词,F_FaBuShiJian as 发布时间,F_FaBuRen as 发布人,F_FaBuDanWei as 发布单位,F_BiaoShiBianMa as 标识编码,(select  stuff((select ',' + F_FileName from T_Sys_Accessories  where F_FileId   in (select col from dbo.SplitToNvarchar(a.F_File,',' )) for xml path('')),1,1,''))  as 附件,F_BeiZhu as 备注,F_WangShangBanLiLianJie as 网站链接";
                var dtdc = DB.DbHelperSQL.Query(" select " + cols + " from T_Wiki_LawGuide a with(nolock) "+ sqldt + " where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("办事指南", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wiki_LawGuide a with(nolock) "+ sqldt,
                "F_Id",
                "a.*,dbo.GetDictionaryName(F_Key) as KeyName,'B'+ RIGHT ('00000'+CONVERT (varchar(10),a.F_Id),6) as 序号",
                sql,
                "ORDER BY F_DianJiLiang,F_CreateTime DESC",
                pagesize,
                page,
                true,
                out recordCount);

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

        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetModel(int id = 0)
        {
            if (id != 0)
            {
                var model = new BLL.T_Wiki_LawGuide().GetModel(id);
                if (model != null)
                {
                    DB.DbHelperSQL.ExecuteSql(" update T_Wiki_LawGuide set F_DianJiLiang=F_DianJiLiang+1 where F_Id=" + id);
                    DataTable dtkey = new DataTable();
                    if (model.F_Key > 0)
                    {
                        dtkey = DB.DbHelperSQL.Query(" select * from View_KeysSplit where id=" + model.F_Key).Tables[0];
                    }

                    DataTable dtfile = new DataTable();
                    var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                    if (!string.IsNullOrEmpty(model.F_File) && configfj != null)
                    {
                        dtfile = DB.DbHelperSQL.Query("select * from T_Sys_Accessories WITH(NOLOCK) where F_FileId in (" + model.F_File + ")").Tables[0];
                        foreach (DataRow dr in dtfile.Rows)
                        {
                            dr["F_FileUrl"] = configfj.F_ParamValue + dr["F_FileUrl"].ToString();
                        }
                    }
                    var obj = new { model , dtkey , dtfile };
                    return Success("成功", obj);
                }
                return Error("参数错误");
            }
            else
            {
                return Error("参数错误");
            }
        }
      
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddModel(int id = 0, int key = 0)
        {
            string fabudanwei = RequestString.GetFormString("fabudanwei");
            string faburen = RequestString.GetFormString("faburen");
            string hangye = RequestString.GetFormString("hangye");
            string diqu = RequestString.GetFormString("diqu");
            string shengxiaoshijian = RequestString.GetFormString("shengxiaoshijian");
            string shixiaoshijian = RequestString.GetFormString("shixiaoshijian");
            string fabushijian = RequestString.GetFormString("fabushijian");
            string yewumingcheng = RequestString.GetFormString("yewumingcheng");
            string biaoshibianma = RequestString.GetFormString("biaoshibianma");
            string shenqingtiaojian = RequestString.GetFormString("shenqingtiaojian");
            string zhengceyiju = RequestString.GetFormString("zhengceyiju");
            string wangshangbanlilianjie = RequestString.GetFormString("wangshangbanlilianjie");
            string file = RequestString.GetFormString("file");
            string banlicailiao = RequestString.GetFormString("banlicailiao");
            string banlishixian = RequestString.GetFormString("banlishixian");
            string banlididian = RequestString.GetFormString("banlididian");
            string banlishijian = RequestString.GetFormString("banlishijian");
            string banlidianhua = RequestString.GetFormString("banlidianhua");
            string qitashuoming = RequestString.GetFormString("qitashuoming");
            string banliliucheng = RequestString.GetFormString("banliliucheng");
            string beizhu = RequestString.GetFormString("beizhu");

            Model.T_Wiki_LawGuide dModel = new Model.T_Wiki_LawGuide();
            if (id == 0)
            {
                //var list = new BLL.T_Wiki_LawGuide().GetList(" F_FaBuDanWei='" + fabudanwei + "' and F_IsDelete=0 ").Tables[0];
                //if (list.Rows.Count > 0)
                //{
                //    return Error("已经存在");
                //}
                //else
                //{
            
                dModel.F_FaBuRen = User .F_UserName ;
                dModel.F_FaBuDanWei = fabudanwei;
                dModel.F_HangYe = hangye;
                dModel.F_DiQu = diqu;
                try
                {
                    dModel.F_ShengXiaoShiJian = DateTime.Parse(shengxiaoshijian);
                }
                catch { };
                try
                {
                    dModel.F_ShiXiaoShiJian = DateTime.Parse(shixiaoshijian);
                }
                catch { };
                dModel.F_FaBuShiJian = DateTime.Now;

               dModel.F_Key = key;
                dModel.F_YeWuMingCheng = yewumingcheng;
              
                dModel.F_ShenQingTiaoJian = shenqingtiaojian;
                dModel.F_ZhengCeYiJu = zhengceyiju;
                dModel.F_WangShangBanLiLianJie = wangshangbanlilianjie;
                dModel.F_File = file;
                dModel.F_BanLiCaiLiao = banlicailiao;
                dModel.F_BanLiShiXian = banlishixian;
                dModel.F_BanLiDiDian = banlididian;

                try
                {
                    dModel.F_BanLiShiJian = DateTime.Parse(fabushijian);
                }
                catch { };

                dModel.F_BanLiDianHua = banlidianhua;
                dModel.F_QiTaShuoMing = qitashuoming;
                dModel.F_BanLiLiuCheng = banliliucheng;
                dModel.F_BeiZhu = beizhu;

                dModel.F_DianJiLiang = 0;
                dModel.F_IsDelete = 0;
                dModel.F_CreateUser = User.F_UserCode;
                dModel.F_CreateTime = DateTime.Now;
                int n = new BLL.T_Wiki_LawGuide().Add(dModel);
                if (n > 0)
                {
                    DB.DbHelperSQL.ExecuteSql("update T_Wiki_LawGuide  set F_BiaoShiBianMa  =right('00000'+'" + User.F_DeptId + "'  ,5)+right('0000000'+'" + n + "'  ,8) where F_Id=" + n);
                    return Success("添加成功", n);
                   
                }
                   
                else
                    return Error("添加失败");
                //}
            }
            else
            {
                dModel = new BLL.T_Wiki_LawGuide().GetModel(id);
                if (dModel != null)
                {
                    //var list = new BLL.T_Wiki_LawGuide().GetList(" F_FaBuDanWei='" + fabudanwei + "' and F_IsDelete=0 and F_Id!='" + id + "' ").Tables[0];
                    //if (list.Rows.Count > 0)
                    //{
                    //    return Error("已经存在");
                    //}
                    //else
                    //{

                    dModel.F_FaBuRen = faburen;
                    dModel.F_FaBuDanWei = fabudanwei;
                    dModel.F_HangYe = hangye;
                    dModel.F_DiQu = diqu;
                    try
                    {
                        dModel.F_ShengXiaoShiJian = DateTime.Parse(shengxiaoshijian);
                    }
                    catch { };
                    try
                    {
                        dModel.F_ShiXiaoShiJian = DateTime.Parse(shixiaoshijian);
                    }
                    catch { };
                    try
                    {
                        dModel.F_FaBuShiJian = DateTime.Parse(fabushijian);
                    }
                    catch { };

                    dModel.F_Key = key;
                    dModel.F_YeWuMingCheng = yewumingcheng;
                    dModel.F_BiaoShiBianMa = biaoshibianma;
                    dModel.F_ShenQingTiaoJian = shenqingtiaojian;
                    dModel.F_ZhengCeYiJu = zhengceyiju;
                    dModel.F_WangShangBanLiLianJie = wangshangbanlilianjie;
                    dModel.F_File = file;
                    dModel.F_BanLiCaiLiao = banlicailiao;
                    dModel.F_BanLiShiXian = banlishixian;
                    dModel.F_BanLiDiDian = banlididian;

                    try
                    {
                        dModel.F_BanLiShiJian = DateTime.Parse(fabushijian);
                    }
                    catch { };

                    dModel.F_BanLiDianHua = banlidianhua;
                    dModel.F_QiTaShuoMing = qitashuoming;
                    dModel.F_BanLiLiuCheng = banliliucheng;
                    dModel.F_BeiZhu = beizhu;

                    if (new BLL.T_Wiki_LawGuide().Update(dModel))
                        return Success("修改成功");
                    else
                        return Error("修改失败");
                    //}
                }
                else
                {
                    return Error("修改失败");
                }
            }
        }
        ///// <summary>
        ///// 导入excel
        ///// </summary>
        public ActionResult ImportExcel()
        {
            HttpPostedFile _upFile = RequestString.GetFile("upFile");
            if (_upFile != null)
            {
                int headrow = 0;
                #region 上传文件
                string filepath = "";
                string datepath = DateTime.Now.ToString("yyyyMMddHHMMss");
                string aLastName = Path.GetExtension(_upFile.FileName);
                string oriname = Path.GetFileNameWithoutExtension(_upFile.FileName);
                if (aLastName != ".xls" && aLastName != ".xlsx")
                {
                    return Error("文件类型错误，请选择Excel文件");
                }
                string newpath = datepath + "_" + _upFile.FileName;
                if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
                {
                    Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
                }
                filepath = this.Request.ApplicationPath + "/ExcelData/" + newpath;
                string PhysicalPath = Server.MapPath(filepath);
                _upFile.SaveAs(PhysicalPath);
                #endregion
                NPOIHelper np = new NPOIHelper();
                DataTable dt = np.ExcelToTable(_upFile, headrow);
                string msg = string.Empty;
                if (dt == null || dt.Rows.Count == 0)
                    return Error("文件没有数据");
                else
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        headrow = headrow + 1;
                        Model.T_Wiki_LawGuide dModel = new Model.T_Wiki_LawGuide();
                        dModel.F_FaBuRen = User.F_UserName;
                        dModel.F_FaBuDanWei = dr["发布单位"].ToString();
                        dModel.F_HangYe = dr["所属行业"].ToString();
                        dModel.F_DiQu = dr["地区"].ToString();
                        try
                        {
                            dModel.F_ShengXiaoShiJian = DateTime.Parse(dr["生效时间"].ToString());
                        }
                        catch { };
                        try
                        {
                            dModel.F_ShiXiaoShiJian = DateTime.Parse(dr["失效时间"].ToString());
                        }
                        catch { };
                        dModel.F_FaBuShiJian = DateTime.Now;

                       // dModel.F_Key = dr["关键词"].ToString();
                        dModel.F_YeWuMingCheng = dr["业务名称"].ToString();

                        dModel.F_ShenQingTiaoJian = dr["申请条件"].ToString();
                        dModel.F_ZhengCeYiJu = dr["政策依据"].ToString();
                        dModel.F_WangShangBanLiLianJie = dr["网上办理链接"].ToString();
                       // dModel.F_File = file;
                        dModel.F_BanLiCaiLiao = dr["办理材料"].ToString();
                        dModel.F_BanLiShiXian = dr["办理时限"].ToString();
                        dModel.F_BanLiDiDian = dr["办理地点"].ToString();

                        try
                        {
                            dModel.F_BanLiShiJian = DateTime.Parse(dr["办理时间"].ToString());
                        }
                        catch { };

                        dModel.F_BanLiDianHua = dr["办理电话"].ToString();
                        dModel.F_QiTaShuoMing = dr["其他说明"].ToString();
                        dModel.F_BanLiLiuCheng = dr["办理流程"].ToString();
                        dModel.F_BeiZhu = dr["备注"].ToString();

                        dModel.F_DianJiLiang = 0;
                        dModel.F_IsDelete = 0;
                        dModel.F_CreateUser = User.F_UserCode;
                        dModel.F_CreateTime = DateTime.Now;
                        
                        
                     

                        if (new BLL.T_Wiki_LawGuide().Add(dModel) <= 0)
                        {

                            msg = msg + "第" + headrow + "行，添加失败，未导入<br>";
                        }
                    }
                    if (string.IsNullOrEmpty(msg))
                        return Success("导入成功 ");
                    else
                        return Error(msg);
                }
            }
            return Error("数据源上传失败");

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelModel(string[] ids)
        {
            if (ids == null || ids.Length <= 0)
            {
                return Error("请选择要删除的选项");
            }

            var idStr = string.Join(",", ids);
            if (string.IsNullOrEmpty(idStr.Trim()))
            {
                return Error("请选择要删除的选项");
            }
            int n = DB.DbHelperSQL.ExecuteSql(" update T_Wiki_LawGuide set F_IsDelete=1,F_DeleteUser='" + User.F_UserCode + "',F_DeleteTime=getdate() where F_Id in (" + idStr + ")");
            if (n > 0)
            {
                return Success("删除成功");
            }
            return Error("删除失败");
        }

        /// <summary>
        /// 导出word
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportWord(int id)
        {
            var aw = new AsposeWord();
            aw.OpenWithTemplate(Server.MapPath("/Upload/Word/办事指南模板.doc"));
            var dt = DB.DbHelperSQL.Query("select a.*,(select  stuff((select ',' + stuff(F_FileName, 1,19,'') from T_Sys_Accessories  where F_FileId   in (select col from dbo.SplitToNvarchar(a.F_File,',' )) for xml path('')),1,1,'')) as fileurl,'B'+ RIGHT ('00000'+CONVERT (varchar(10),a.F_Id),6) as xh from T_Wiki_LawGuide a with(nolock) where a.F_Id=" + id).Tables[0];
            string F_key = dt.Rows[0]["F_key"].ToString();
            var dt2 = DB.DbHelperSQL.Query("SELECT * FROM View_KeysSplit WHERE id=" + F_key).Tables[0];
            aw.Builder();
            aw.CreateGuideWord(dt, dt2);
            var bt = aw.ExportAs();
            Response.AppendHeader("Access-Control-Expose-Headers", "Content-Disposition");
            return File(bt, "application/msword", DateTime.Now.Ticks.ToString() + ".doc");
        }
    }
}