using CallCenter.Utility;
using CallCenterApi.DB;
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 ProfessorController : BaseController
    {
        // GET: Professor

        /// <summary>
        /// 上传专家图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadTX(string name)
        {
            string path = string.Empty;
            HttpPostedFile _upfile = RequestString.GetFile("upFile");
            if (_upfile != null)
            {
                ImageUpload iu = new ImageUpload();
                iu.SavePath = "/Upload/ZJTX/";
                iu.PostFile = _upfile;
                if (!string.IsNullOrEmpty(name))
                {
                    iu.InFileName = name + ".jpg";
                    iu.SaveType = 1;
                }
                iu.Upload();
                path = "/Upload/ZJTX/" + iu.OutFileName;

                return Success("成功", path);
            }
            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 page = 1, int pagesize = 10, int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";

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

            if (!string.IsNullOrEmpty(keyvalue))
            {
                sql += " and (F_XingMing like '%" + keyvalue + "%' or F_ShouJi like '%" + keyvalue + "%' )";
            }
 
         

            if (isdc > 0)
            {
                string cols = "'A'+ RIGHT ('00000'+CONVERT (varchar(10),a.F_Id),6) as 序号,F_HangYe as 所属行业 ,F_DanWei as 专家单位,F_XingMing as 专家姓名,F_KeShi as 科室,F_ZhiWu as 职务,F_ShouJi as 手机号码,F_DianHua as 办公电话,F_FaBuShiJian as 发布日期,F_FaBuRen as 发布人,F_FaBuDanWei as 上报单位,F_BiaoShiBianMa as 标识编码";
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Wiki_Professor a with(nolock) 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_Professor a with(nolock)",
                "F_Id",
                "a.*,'A'+ 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)
            {
                DB.DbHelperSQL.ExecuteSql(" update T_Wiki_Professor set F_DianJiLiang=F_DianJiLiang+1 where F_Id=" + id);
                return Success("成功", new BLL.T_Wiki_Professor().GetModel(id));
            }
            else
            {
                return Error("参数错误");
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddModel(int id=0)
        {
            string xingming = RequestString.GetFormString("xingming");
            string danwei = RequestString.GetFormString("danwei");
            string keshi = RequestString.GetFormString("keshi");
            string zhiwu = RequestString.GetFormString("zhiwu");
            string shouji = RequestString.GetFormString("shouji");
            string dianhua = RequestString.GetFormString("dianhua");
            string diqu = RequestString.GetFormString("diqu");
            string hangye = RequestString.GetFormString("hangye");
            string shengxiaoshijian = RequestString.GetFormString("shengxiaoshijian");
            string shixiaoshijian = RequestString.GetFormString("shixiaoshijian");
            string fabushijian = RequestString.GetFormString("fabushijian");
            string faburen = RequestString.GetFormString("faburen");
            string fabudanwei = RequestString.GetFormString("fabudanwei");
            string biaoshibianma = RequestString.GetFormString("biaoshibianma");
            string touxiang = RequestString.GetFormString("touxiang");
            string zhuanyelingyujianjie = RequestString.GetFormString("zhuanyelingyujianjie");

            Model.T_Wiki_Professor dModel = new Model.T_Wiki_Professor();
            if (id == 0)
            {
                var list = new BLL.T_Wiki_Professor().GetList(" F_XingMing='" + xingming + "' and F_IsDelete=0 ").Tables[0];
                if (list.Rows.Count > 0)
                {
                    return Error("已经存在");
                }
                else
                {
                   
                    dModel.F_XingMing = xingming;
                    dModel.F_DanWei = danwei;
                    dModel.F_KeShi = keshi;
                    dModel.F_ZhiWu = zhiwu;
                    dModel.F_ShouJi = shouji;
                    dModel.F_DianHua = dianhua;
                    dModel.F_DiQu = diqu;
                    dModel.F_HangYe = hangye;
                    try
                    {
                        dModel.F_ShengXiaoShiJian = DateTime.Parse(shengxiaoshijian);
                    }
                    catch { };
                    try
                    {
                        dModel.F_ShiXiaoShiJian = DateTime.Parse(shixiaoshijian);
                    }
                    catch { };
                    dModel.F_FaBuShiJian = DateTime.Now;

                    dModel.F_FaBuRen = User .F_UserName ;
                    dModel.F_FaBuDanWei = fabudanwei;
              
                    dModel.F_TouXiang = touxiang;
                    dModel.F_ZhuanYeLingYuJianJie = zhuanyelingyujianjie;
                    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_Professor().Add(dModel);
                    if (n > 0)
                    {
                        DB.DbHelperSQL.ExecuteSql("update T_Wiki_Professor  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_Professor().GetModel(id);
                if (dModel != null)
                {
                    var list = new BLL.T_Wiki_Professor().GetList(" F_XingMing='" + xingming + "' and F_IsDelete=0 and F_Id!='" + id + "' ").Tables[0];
                    if (list.Rows.Count > 0)
                    {
                        return Error("已经存在");
                    }
                    else
                    {
                        dModel.F_XingMing = xingming;
                        dModel.F_DanWei = danwei;
                        dModel.F_KeShi = keshi;
                        dModel.F_ZhiWu = zhiwu;
                        dModel.F_ShouJi = shouji;
                        dModel.F_DianHua = dianhua;
                        dModel.F_DiQu = diqu;
                        dModel.F_HangYe = hangye;
                        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_FaBuRen = faburen;
                        dModel.F_FaBuDanWei = fabudanwei;
                        dModel.F_BiaoShiBianMa = biaoshibianma;
                        dModel.F_TouXiang = touxiang;
                        dModel.F_ZhuanYeLingYuJianJie = zhuanyelingyujianjie;
                        if (new BLL.T_Wiki_Professor().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;
                        if (string.IsNullOrEmpty(dr["专家姓名"].ToString()))
                        {
                            msg = msg + "第" + headrow + "行，姓名，未导入<br>";
                            continue;
                        }
                        var list = new BLL.T_Wiki_Professor().GetList(" F_XingMing='" + dr["专家姓名"].ToString() + "' and F_IsDelete=0 ").Tables[0];
                        if (list.Rows.Count > 0)
                        {
                            msg = msg + "第" + headrow + "行，该专家已存在，未导入<br>";
                            continue;
                        }
                        Model.T_Wiki_Professor dModel = new Model.T_Wiki_Professor();
                        dModel.F_XingMing = dr["专家姓名"].ToString(); 
                        dModel.F_DanWei = dr["专家单位"].ToString();
                        dModel.F_KeShi = dr["科室"].ToString(); 
                        dModel.F_ZhiWu = dr["职务"].ToString();
                        dModel.F_ShouJi = dr["手机号码"].ToString();
                        dModel.F_DianHua = dr["办公电话"].ToString();
                        dModel.F_DiQu = dr["地区"].ToString();
                        dModel.F_HangYe = 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_FaBuRen = User.F_UserName;
                        dModel.F_FaBuDanWei = dr["发布单位"].ToString();

                       // dModel.F_TouXiang = touxiang;
                        dModel.F_ZhuanYeLingYuJianJie = 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_Professor().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 = DbHelperSQL.ExecuteSql(" update T_Wiki_Professor 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'+ RIGHT ('00000'+CONVERT (varchar(10),F_Id),6) as xh from T_Wiki_Professor with(nolock) where F_Id=" + id).Tables[0];
            aw.Builder();
            aw.CreateProfessorWord(dt);
            var bt = aw.ExportAs();
            Response.AppendHeader("Access-Control-Expose-Headers", "Content-Disposition");
            return File(bt, "application/msword", DateTime.Now.Ticks.ToString() + ".doc");
        }
    }
}