using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.workorder
{
    public class MaterialManageController : BaseController
    {
        BLL.T_Wo_MaterialManage mmBLL = new BLL.T_Wo_MaterialManage();
        BLL.T_Sys_DictionaryValue dvBLL = new BLL.T_Sys_DictionaryValue();
        BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
        // 获取物料列表
        public ActionResult GetList(string MaterialCode, string MaterialName, string Model, string Specs, string Brand, string Pipeline, int pageindex = 1, int pagesize = 10)
        {
            string sql = " and F_IsDelete=0";
            #region 筛选
            if (!string.IsNullOrWhiteSpace(MaterialCode))
            {//先验证物料编码为11位纯数字，再查询
                if (!valcode(MaterialCode))
                    return Error("物料编号必须是11位数字");
                sql += " and F_MaterialCode='" + MaterialCode + "'";
            }
            if(!string.IsNullOrWhiteSpace(MaterialName))
            {
                sql += " and F_MaterialName like '%" + MaterialName + "%'";
            }

            if (!string.IsNullOrWhiteSpace(Model))
            {
                sql += " and F_Model like '%" + Model + "%'";
            }

            if (!string.IsNullOrWhiteSpace(Specs))
            {
                sql += " and F_Specs like '%" + Specs + "%'";
            }

            if (!string.IsNullOrWhiteSpace(Brand))
            {
                sql += " and F_Brand like '%" + Brand + "%'";
            }

            if (!string.IsNullOrWhiteSpace(Pipeline))
            {
                sql += " and F_Pipeline like '%" + Pipeline + "%'";
            }
            #endregion
            int recordCount = 0;
            DataTable dt = BLL.PagerBLL.GetListPager(
                "T_Wo_MaterialManage",
                "F_Id",
                "*,dbo.GetUserName(F_CreateBy) as F_CreateByName",
                sql,
                "ORDER BY F_Id desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }
        //根据物料编码获取物料信息
        public ActionResult GetCodeModel(string code)
        {
            if (code != null && code.Trim() != "")
            {
                Model.T_Wo_MaterialManage dModel = mmBLL.GetModel(code.Trim());
                if (dModel != null)
                {
                    var dvList = dvBLL.GetModelList(" F_DictionaryFlag in ('WLPP','WLFHFFX','WLCPX') ");
                    var createusername = userBLL.GetModel(dModel.F_CreateBy);
                    var obj = new
                    {
                        model = dModel,
                        CreateByName = createusername
                    };

                    return Success("获取物料信息成功", obj);
                }
                else
                {
                    return Success(null );
                }
            }
            else
            {
                return Success("请输入物料编码", null);
            }
        }

        //获取物料
        public ActionResult GetModel(string id)
        {
            if (id != null && id.Trim() != "")
            {
                Model.T_Wo_MaterialManage dModel = mmBLL.GetModel(int.Parse(id.Trim()));
                if (dModel != null)
                {
                    var dvList = dvBLL.GetModelList(" F_DictionaryFlag in ('WLPP','WLFHFFX','WLCPX') ");
                    var createusername = userBLL.GetModel(dModel.F_CreateBy);
                    var obj = new
                    {
                        model = dModel,
                        CreateByName = createusername
                    };

                    return Success("获取物料信息成功", obj);
                }
                else
                {
                    return Error("获取物料信息失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }
        //[Authority]
        //添加物料
        public int  Add(string materialcode,string materialname,string model,string specs,
      string      level1,string level2,string level3,string brand,string materialeffect,string
           craft,string pipeline,string remark,int id=0)
        {
         
            Model.T_Wo_MaterialManage dModel = new Model.T_Wo_MaterialManage();
            if (id >0)
             dModel = new BLL.T_Wo_MaterialManage().GetModel(id);
            #region 验证物料编码为11位纯数字
            #endregion
            #region
            dModel.F_MaterialCode = materialcode;//物料编号
            dModel.F_MaterialName = materialname;//物料名称
            dModel.F_Model = model;//型号
            dModel.F_Specs = specs;//规格
            dModel.F_Level1 = level1;//一级分类
            dModel.F_Level2 = level2;//二级分类
            dModel.F_Level3 = level3;//三级分类
            dModel.F_Brand = brand;//品牌
            dModel.F_MaterialEffect = materialeffect;//复合肥肥效
            dModel.F_Craft = craft;//工艺
            dModel.F_Pipeline = pipeline;//产品线
            dModel.F_Remark = remark;

            dModel.F_IsDelete = 0;
            dModel.F_CreateOn = DateTime.Now;
            dModel.F_CreateBy ="系统外添加";
            #endregion
            if (id >0)
            {
                bool b = mmBLL.Update(dModel);
                if (b)
                {
                    addoptlog("系统外添加", DTRequest.GetIP(), EnumOpt.edit.ToString(), dModel.F_Id.ToString(), "编辑成功，物料编号为" + dModel.F_MaterialCode + "的资料");
                    return id ;
                }
                else
                {
                    return 0;
                }

            }
            else
            {
                int b = mmBLL.Add(dModel);
                if (b > 0)
                {
                    addoptlog("系统外添加", DTRequest.GetIP(), EnumOpt.add.ToString(), b.ToString(), "添加成功，物料编号为" + dModel.F_MaterialCode + "的资料");
                    return b;
                }
                else
                {
                    return 0;
                }
            }
            

        }
        //[Authority]
        //添加物料
        public ActionResult AddModel(WoMaterialManageInput input)
        {
            Model.T_Wo_MaterialManage dModel = new Model.T_Wo_MaterialManage();
            #region 验证物料编码为11位纯数字
            if (string.IsNullOrEmpty(input.F_MaterialCode))
            {
                return Error("请输入物料编码");
            }
            if (!string.IsNullOrWhiteSpace(input.F_MaterialCode))
            {
                if (!valcode(input.F_MaterialCode))
                    return Error("物料编号必须是11位数字");
            }
            #endregion
            #region
            dModel.F_MaterialCode = input.F_MaterialCode;//物料编号
            dModel.F_MaterialName = input.F_MaterialName;//物料名称
            dModel.F_Model = input.F_Model;//型号
            dModel.F_Specs = input.F_Specs;//规格
            dModel.F_Level1 = input.F_Level1;//一级分类
            dModel.F_Level2 = input.F_Level2;//二级分类
            dModel.F_Level3 = input.F_Level3;//三级分类
            dModel.F_Brand = input.F_Brand;//品牌
            dModel.F_MaterialEffect = input.F_MaterialEffect;//复合肥肥效
            dModel.F_Craft = input.F_Craft;//工艺
            dModel.F_Pipeline = input.F_Pipeline;//产品线
            dModel.F_Remark = input.F_Remark;
            
            dModel.F_IsDelete = 0;
            dModel.F_CreateOn = DateTime.Now;
            dModel.F_CreateBy = CurrentUser.UserData.F_UserCode;
            #endregion
            int b = mmBLL.Add(dModel);
            if (b > 0)
            {
                addoptlog(CurrentUser.UserData.F_UserCode, DTRequest.GetIP(), EnumOpt.add.ToString(), b.ToString(), "添加成功，物料编号为"+ dModel.F_MaterialCode+"的资料");
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }

        }
        //[Authority]
        //编辑物料
        public ActionResult EditModel(WoMaterialManageInput input)
        {
            if (input.F_Id > 0)
            {
                Model.T_Wo_MaterialManage dModel = mmBLL.GetModel(input.F_Id);
                if (dModel != null)
                {
                    #region 验证物料编码为11位纯数字
                    if (string.IsNullOrWhiteSpace(input.F_MaterialCode))
                        return Error("物料编号不能为空");
                    if (!valcode(input.F_MaterialCode))
                        return Error("物料编号必须是11位数字");
                    #endregion
                    #region
                    dModel.F_MaterialCode = input.F_MaterialCode;//物料编号
                    dModel.F_MaterialName = input.F_MaterialName;//物料名称
                    dModel.F_Model = input.F_Model;//型号
                    dModel.F_Specs = input.F_Specs;//规格
                    dModel.F_Level1 = input.F_Level1;//一级分类
                    dModel.F_Level2 = input.F_Level2;//二级分类
                    dModel.F_Level3 = input.F_Level3;//三级分类
                    dModel.F_Brand = input.F_Brand;//品牌
                    dModel.F_MaterialEffect = input.F_MaterialEffect;//复合肥肥效
                    dModel.F_Craft = input.F_Craft;//工艺
                    dModel.F_Pipeline = input.F_Pipeline;//产品线
                    dModel.F_Remark = input.F_Remark;

                    dModel.F_UpdateBy = CurrentUser.UserData.F_UserCode;
                    dModel.F_UpdateOn = DateTime.Now;
                    dModel.F_UpdateCount += 1;
                    #endregion
                    bool b = mmBLL.Update(dModel);
                    if (b)
                    {
                        addoptlog(CurrentUser.UserData.F_UserCode, DTRequest.GetIP(), EnumOpt.edit.ToString(), dModel.F_Id.ToString(), "编辑成功，物料编号为" + dModel.F_MaterialCode + "的资料");
                        return Success("编辑成功");
                    }
                    else
                    {
                        return Success("编辑失败");
                    }
                }
                else
                    return Error("获取信息失败");
            }
            else
            {
                return Error("获取参数失败");
            }

        }
        //[Authority]
        //批量删除物料
        public bool  Del( string ids)
        {
            string optuser = "系统外删除";
            DateTime dtnow = DateTime.Now;
            if (new BLL.T_Wo_MaterialManage().DeleteList(ids, optuser, dtnow))
            {
                if (ids.Length > 1)
                    addoptlog(optuser, DTRequest.GetIP(), EnumOpt.deletion.ToString(), ids, "批量删除成功");
                else
                    addoptlog(optuser, DTRequest.GetIP(), EnumOpt.delete.ToString(), ids, "删除成功");
                return true ;
            }
            else
                return false ;
        }
        //[Authority]
        //批量删除物料
        public ActionResult DelModels(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                string optuser = CurrentUser.UserData.F_UserCode;
                DateTime dtnow = DateTime.Now;
                if (new BLL.T_Wo_MaterialManage().DeleteList(idd.TrimEnd(','), optuser, dtnow))
                {
                    if (ids.Length > 1)
                        addoptlog(optuser, DTRequest.GetIP(), EnumOpt.deletion.ToString(), idd.TrimEnd(','), "批量删除成功");
                    else
                        addoptlog(optuser, DTRequest.GetIP(), EnumOpt.delete.ToString(), idd.TrimEnd(','), "删除成功");
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 导入excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportExcel()
        {
            string userscode = CurrentUser.UserData.F_UserCode;
            string ip = DTRequest.GetIP();
            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
                #region 添加附件日志
                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 = newpath;//附件名称
                model_T_Sys_Accessories.F_FileType = aLastName;//附件类型
                model_T_Sys_Accessories.F_FileUrl = filepath;//附件地址
                model_T_Sys_Accessories.F_UserCode = userscode;//上传人  
                model_T_Sys_Accessories.F_OriName = oriname;
                int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                #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)
                    {
                        #region 数据入库
                        headrow = headrow + 1;
                        
                        if (dr["物料编码"].ToString() != "" && valcode(dr["物料编码"].ToString()))
                        {
                            if (!getunique(0, dr["物料编码"].ToString()))
                            {
                                Model.T_Wo_MaterialManage dModel = new Model.T_Wo_MaterialManage();
                                dModel.F_MaterialCode = dr["物料编码"].ToString();//物料编码
                                dModel.F_MaterialName = dr["物料名称"].ToString();//物料名称
                                dModel.F_Model = dr["型号"].ToString();//型号
                                dModel.F_Specs = dr["规格"].ToString();//规格
                                dModel.F_Level1 = dr["一级分类"].ToString();//一级分类
                                dModel.F_Level2 = dr["二级分类"].ToString();//二级分类
                                dModel.F_Level3 = dr["三级分类"].ToString();//三级分类
                                dModel.F_Brand = dr["品牌"].ToString();//品牌
                                dModel.F_MaterialEffect = dr["复合肥肥效"].ToString();//复合肥肥效
                                dModel.F_Pipeline = dr["产品线"].ToString();//产品线
                                dModel.F_Craft = dr["工艺"].ToString();//工艺
                                dModel.F_Remark  = dr["备注"].ToString();//工艺
                                dModel.F_CreateBy = userscode;
                                dModel.F_CreateOn = DateTime.Now;
                                dModel.F_IsDelete = 0;
                                var res = mmBLL.Add(dModel);
                                if (res > 0)
                                {
                                    addoptlog(userscode, ip, EnumOpt.import.ToString(), res.ToString(), "导入成功,导入的文件为：" + newpath + ",当前为第" + headrow + "行");
                                }
                                else
                                {
                                    msg = msg + "第" + headrow + "行，导入失败<br>";
                                }
                            }
                            else
                            {
                                msg = msg + "第" + headrow + "行，物料编码重复，未导入<br>";
                            }
                        }
                        else
                            msg = msg + "第" + headrow + "行，物料编码为空或格式不正确，未导入<br>";
                        #endregion
                    }
                    if (string.IsNullOrEmpty(msg))
                        return Success("导入成功 ");
                    else
                        return Error(msg);
                }

            }
            return Error("文件不能为空");
        }
        /// <summary>
        /// 验证客户编号是否唯一
        /// </summary>
        public  bool getunique(int id, string code)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_MaterialCode='" + code + "')";
            if (id > 0)
                sql += " and F_Id<>" + id;
            var count = mmBLL.GetModelList(sql).Count();

            return count > 0;
        }

        #region 上传附件
        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(ids))
            {
                dt = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + ids + ")").Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                }
            }
            return dt;
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            try
            {
                if (file == null) return Error("参数传入失败");
                if (Request.Files.Count == 0) return Error("保存失败");

                string userCode = CurrentUser.UserData.F_UserCode;
                string filePathName = string.Empty;
                #region 保存文件到本地路径
                string path = "/Upload/Files/" + DateTime.Now.ToString("yyyy/MM/dd") + "/";
                string localPath = Server.MapPath(Path.Combine(HttpRuntime.AppDomainAppPath, path));
                string ex = Path.GetExtension(file.FileName);
                string oriname = Path.GetFileNameWithoutExtension(file.FileName);
                filePathName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N") + ex;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                string physicalpath = Path.Combine(localPath, filePathName);
                file.SaveAs(physicalpath);
                #endregion
                #region 读取配置的上传路径-原文件和修改过格式的文件均上传至此
                string savedir = Configs.GetValue("saveloc");
                if (!System.IO.Directory.Exists(savedir))
                {
                    System.IO.Directory.CreateDirectory(savedir);
                }
                #endregion
                if (!string.IsNullOrEmpty(physicalpath))
                {
                    #region 上传到ftp
                    uploadFile upfile = new uploadFile();
                    //通过读取配置文件，获取数据库
                    string _ftp = Configs.GetValue("ftp");
                    string _acc = Configs.GetValue("account");
                    string _pwd = Configs.GetValue("password");

                    upfile.ftpPath = _ftp;
                    upfile.ftpUserID = _acc;
                    upfile.ftpPassword = _pwd;
                    //20180207 原文件同时保存
                    string uploadBeforres = upfile.UploadLocalToFtp(physicalpath);
                    #endregion
                    if (uploadBeforres.Equals("上传成功！"))
                    {
                        #region 添加日志
                        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 = filePathName;//附件名称
                        model_T_Sys_Accessories.F_FileType = type;//附件类型
                        model_T_Sys_Accessories.F_FileUrl = (filePathName).Replace('\\', '/');//附件地址
                        model_T_Sys_Accessories.F_Size = size;
                        model_T_Sys_Accessories.F_UserCode = userCode;//上传人  
                        model_T_Sys_Accessories.F_OriName = oriname;
                        int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                        #endregion
                        if (fid > 0)
                        {
                            //返回附件的ID
                            model_T_Sys_Accessories.F_FileId = fid;//修改为返回对象以便查看图片
                            return Success("文件上传成功", model_T_Sys_Accessories);
                        }
                        else
                            return Success("文件上传成功，日志记录失败");
                    }
                    else
                        return Error("文件上传失败，请重新上传，失败原因：" + uploadBeforres);
                }
                else
                    return Error("格式修改出错，请重新上传");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        #endregion

        #region 私有方法
        /// <summary>
        /// 验证物料编码为11位纯数字
        /// </summary>
        public  bool valcode(string code)
        {
            var res = false;
            //11位数字
            if (code.Length == 11 && Regex.IsMatch(code, @"^\d{11}$"))
                res = true;
            return res;
        }
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="usercode">操作人工号</param>
        /// <param name="ip">操作人IP</param>
        /// <param name="optcode">操作编号</param>
        /// <param name="optid">操作id</param>
        /// <param name="des">操作描述</param>
        private void addoptlog(string usercode, string ip, string optcode, string optid, string des)
        {
            new BLL.T_Sys_OperateLogs().AddOptLog("物料管理", usercode, ip, des, optcode, "T_Wo_MaterialManage", optid);
        }
        #endregion
    }
}