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

namespace CallCenterApi.Interface.Controllers.Client
{
    
    public class ApplicationsRefreshController : BaseController
    {
        BLL.T_Client_Applications bll = new BLL.T_Client_Applications();

        [Authority]
        /// <summary>
        /// 获取所有库列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllList()
        {
            DataTable dt = new DataTable();
            string appliName = HttpUtility.UrlDecode(RequestString.GetQueryString("appliName"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strstarttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = " and F_IsDelete=0 ";
            if (appliName.Trim() != "") {
                sql += " and F_AppliName like '%" + appliName + "%'";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                    "T_Client_Applications",
                    "F_Id",
                    "*",
                    sql,
                    "ORDER BY F_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取一条详细信息
        /// </summary>
        /// <param name="infoid"></param>
        /// <returns></returns>
        public ActionResult GetInfo(string infoid,bool isNew=false)
        {
            //如果为true 获取最新的版本信息 Wap端用到
            if (isNew) {
                int n = bll.GetMaxId();
                if (n > 0)
                {
                    infoid = (bll.GetMaxId() - 1).ToString();
                }
            }
            if (infoid != null && infoid.Trim() != "")
            {
                Model.T_Client_Applications model = bll.GetModel(int.Parse(infoid.Trim()));
                if (model != null)
                {
                    return Success("获取成功", model);
                }
                else
                {
                    return Error("获取失败");
                };
            }
            else {
                return Error("获取参数失败");
            }
        }

        [Authority]
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile()
        {
            string name = string.Empty;
            string appliName = RequestString.GetFormString("appliName");
            string versionCode = RequestString.GetFormString("versionCode");
            //if (string.IsNullOrWhiteSpace(appliName))
            //{
            //    return Error("应用名称不能为空");
            //}
            if (string.IsNullOrWhiteSpace(versionCode))
            {
                return Error("版本号不能为空");
            }
            var listmodel = bll.GetModelList(" F_IsDelete = 0 AND F_VersionCode = '" + versionCode + "' ").FirstOrDefault();  //F_AppliName = '" + appliName + "' or 
            if (listmodel != null)
            {
                return Error("应用名称或版本号已存在");
            }
            HttpFileCollection files = RequestString.GetFiles();
            if (files.Count > 0)
            {
                string path = "Upload/version/";   // + 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 fileExtension = ".apk";
                    if (!fileExtension.Contains((System.IO.Path.GetExtension(file.FileName).ToLower())))
                    {
                        return Error("app格式不正确");
                    }
                    name = fu.Upload(file, path, versionCode);  //appliName + 
                }

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

        [Authority]
        /// <summary>
        /// 保存信息
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveInfo()
        {
            int id = RequestString.GetInt("id", 0);
            string appliName = RequestString.GetFormString("appliName");
            string versionName = RequestString.GetFormString("versionName");
            string versionCode = RequestString.GetFormString("versionCode");
            string downUrl = RequestString.GetFormString("files");
            int userId = RequestString.GetInt("userId", 0);
            string userCode = RequestString.GetFormString("userCode");
            int isDelete = RequestString.GetInt("isDelete", 0);
            int order = RequestString.GetInt("order", 0);
            string note = RequestString.GetFormString("note");

            //string fileName = string.Empty;
            //HttpPostedFile _upfile = RequestString.GetFile("upFile");
            //string path = "/Upload/versionDown/";  //" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "
            //if (_upfile != null)
            //{
            //    byte[] buffer = new Byte[(int)_upfile.InputStream.Length]; //声明文件长度的二进制类型
            //    _upfile.InputStream.Read(buffer, 0, buffer.Length); //将文件转成二进制
            //    FileUp fu = new FileUp();
            //    fileName = fu.Upload(_upfile, path, appliName + versionCode);   //应用名称+版本号
            //    downUrl = path + fileName;
            //}

            //if (string.IsNullOrWhiteSpace(appliName))
            //{
            //    return Error("应用名称不能为空");
            //}
            if (string.IsNullOrWhiteSpace(versionCode))
            {
                return Error("版本号不能为空");
            }
            var listmodel = bll.GetModelList("  F_IsDelete = 0 AND F_VersionCode = '" + versionCode + "' ").FirstOrDefault();
            if (listmodel != null)
            {
                return Error("应用名称或版本号已存在");
            }
            Model.T_Client_Applications model = new Model.T_Client_Applications();
            if (id == 0)
            {
                model.F_AppliName = appliName;
                model.F_VersionName = versionName;
                model.F_VersionCode = versionCode;
                if (!string.IsNullOrEmpty(downUrl))
                {
                    model.F_DownUrl = downUrl;
                }
                model.UserId = userId;
                model.UserCode = userCode;
                model.F_CreateTime = DateTime.Now;
                //model.F_UpdateTime = DateTime.Now;
                //model.F_DeleteTime = DateTime.Now;
                model.F_IsDelete = 0;
                model.F_Order = 0;
                model.F_Note = note;
                int n = bll.Add(model);
                if (n > 0)
                {
                    return Success("添加成功", n);
                }
                else
                {
                    return Error("添加失败");
                }
            }
            else
            {
                model = bll.GetModel(id);
                if (model != null)
                {
                    model.F_Id = id;
                    model.F_AppliName = appliName;
                    model.F_VersionName = versionName;
                    model.F_VersionCode = versionCode;
                    if (!string.IsNullOrEmpty(downUrl))
                    {
                        model.F_DownUrl = downUrl;
                    }
                    model.UserId = userId;
                    model.UserCode = userCode;
                    model.F_CreateTime = model.F_CreateTime;
                    model.F_UpdateTime = DateTime.Now;
                    //model.F_DeleteTime = model.F_DeleteTime;
                    model.F_IsDelete = isDelete;
                    model.F_Order = order;
                    model.F_Note = note;
                    if (bll.Update(model))
                    {
                        return Success("修改成功");
                    }
                    else
                    {
                        return Error("修改失败");
                    }
                }
                return Error("信息不存在");
            }
        }

        [Authority]
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelInfo(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                string sql = "update T_Client_Applications set F_IsDelete=1 where F_Id in(" + idd.TrimEnd(',') + ")";
                if (!string.IsNullOrEmpty(idd.Trim()))
                {
                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                    {
                        return Success("删除成功");
                    }
                    else
                    {
                        return Error("删除失败");
                    }
                }
                else
                {
                    return Error("获取参数失败");
                }
                //if (bll.DeleteList(idd.TrimEnd(',')))
                //{
                //    return Success("删除成功");
                //}
                //else
                //    return Error("删除失败");
            }
            else
            {
                return Error("获取参数失败");
            }
        }


    }
}