using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;

namespace ynhtm.BLL
{
    using Common;
    using DBUtility;

    /// <summary>
    /// 简历操作。
    /// </summary>
    public class JobTry
    {
        public const string SQL_TABLE = DAL.JobTry.SQL_TABLE + " INNER JOIN " + DAL.Job.SQL_TABLE + " ON " + DAL.JobTry.SQL_TABLE + "." + DAL.JobTry.JOBID + " = " + DAL.Job.SQL_TABLE + "." + DAL.Job.JOBID;
        public const string SQL_ORDER = "ORDER BY " + DAL.JobTry.SQL_TABLE + "." + DAL.JobTry.TRYID + " DESC";
        public static readonly string SQL_FIELD;

        public static readonly IDictionary<int, string> WEDDINGS;

        static JobTry()
        {
            SQL_FIELD = Regex.Replace(DAL.JobTry.SQL_FIELD, @"(^|,)([^,]+)", "$1" + DAL.JobTry.SQL_TABLE + ".$2", RegexOptions.Compiled) + "," + DAL.Job.SQL_TABLE + "." + DAL.Job.NAME + " AS JobName" + "," + DAL.Job.SQL_TABLE + "." + DAL.Job.URL + " AS JobUrl";

            WEDDINGS = new Dictionary<int, string>();
            WEDDINGS.Add(1, "未婚");
            WEDDINGS.Add(2, "已婚");
        }

        /// <summary>
        /// 插入简历实例到数据库。
        /// </summary>
        /// <param name="item">简历实例。</param>
        public void Insert(Model.JobTry item)
        {
            DAL.JobTry.Insert(item);
            using (var db = DbBase.GetDb())
                db.ExecuteNonQuery("UPDATE " + DAL.Job.SQL_TABLE + " SET " + DAL.Job.TRYCOUNT + " = " + DAL.Job.TRYCOUNT + " + 1 WHERE " + DAL.Job.JOBID + " = @" + DAL.Job.JOBID, db.CreateParameter(DAL.Job.JOBID, item.JobID));
        }

        #region TryID

        /// <summary>
        /// 取得简历实例。
        /// </summary>
        /// <param name="tryID">简历编号。</param>
        /// <returns>返回简历实例，没有将返回 null 。</returns>
        public Model.JobTry GetByTryID(int tryID)
        {
            return DAL.JobTry.GetByTryID(tryID);
        }

        /// <summary>
        /// 更新简历。
        /// </summary>
        /// <param name="item">简历实例。</param>
        /// <returns>返回受到影响的行数。</returns>
        public int Update(Model.JobTry item)
        {
            return DAL.JobTry.Update(item);
        }

        /// <summary>
        /// 删除简历。
        /// </summary>
        /// <param name="tryID">简历编号。</param>
        /// <returns>返回受到影响的行数。</returns>
        public int Delete(int tryID)
        {
            using (var db = DbBase.GetDb())
                db.ExecuteNonQuery("UPDATE " + DAL.Job.SQL_TABLE + " SET " + DAL.Job.TRYCOUNT + " = " + DAL.Job.TRYCOUNT + " - 1 WHERE " + DAL.Job.JOBID + " IN (SELECT " + DAL.JobTry.JOBID + " FROM " + DAL.JobTry.SQL_TABLE + " WHERE " + DAL.JobTry.TRYID + " = @" + DAL.JobTry.TRYID + ")", db.CreateParameter(DAL.JobTry.TRYID, tryID));
            return DAL.JobTry.Delete(tryID);
        }

        #endregion

        /// <summary>
        /// 取得简历分页集合。
        /// </summary>
        /// <param name="recordCount">记录总数。</param>
        /// <param name="pageSize">分页大小。</param>
        /// <param name="pageIndex">要返回的页数。</param>
        /// <param name="query">查询条件。</param>
        /// <param name="order">排序方式。</param>
        /// <returns>返回分页数据。</returns>
        public DataTable GetList(ref int recordCount, int pageSize, int pageIndex = 1, IQuery query = null, string order = SQL_ORDER)
        {
            using (var db = DbBase.GetDb())
                return db.GetPage(ref recordCount, SQL_TABLE, order, pageSize, pageIndex, query, SQL_FIELD);
        }

        /// <summary>
        /// 取得简历婚姻状况文字描述。
        /// </summary>
        /// <param name="type">婚姻状况的数据类型。</param>
        /// <returns>返回婚姻状况文字描述，没有符合的描述将返回 null。</returns>
        public string GetWedding(int? wedding)
        {
            if (wedding == null) return null;
            return WEDDINGS[wedding.Value].ToString();
        }

        /// <summary>
        /// 提交新评论。
        /// </summary>
        /// <param name="request">客户端 Web 请求。</param>
        /// <param name="response">客户端 HTTP 响应的信息。</param>
        /// <param name="session">Session 对象。</param>
        /// <param name="server">Web 请求的 Helper 方法。</param>
        /// <returns>返回一个 Ajax 结果。</returns>
        public Model.AjaxResult Post(HttpRequest request, HttpResponse response, HttpSessionState session, HttpServerUtility server)
        {
            var code = session[Setting.AUTHCODEKEY];
            if (code == null || !string.Equals(request["Authcode"], code.ToString())) return new Model.AjaxResult(-1, "验证码不正确！");
            var item = new Model.JobTry();
            item.JobID = int.Parse(request["JobID"]);
            item.RealName = request["RealName"];
            item.Sex = Utils.TryGet(request["Sex"], int.Parse);
            item.Wedding = Utils.TryGet(request["Wedding"], int.Parse);
            item.Bday = Utils.TryGet(request["Bday"], DateTime.Parse);
            item.School = request["School"];
            item.Contact = request["Contact"];
            item.Addr = request["Addr"];
            item.EducationNote = request["EducationNote"];
            item.WorkNote = request["WorkNote"];
            item.Remark = request["Remark"];
            item.IPAddr = request.UserHostAddress;
            if (item.RealName.IsNullOrWhiteSpace()) return new Model.AjaxResult(-2, "姓名不能为空！");
            if (item.Contact.IsNullOrWhiteSpace()) return new Model.AjaxResult(-3, "联系方式不能为空！");
            var file = request.Files["File"];
            if (file != null && file.ContentLength > 0)
            {
                var fileName = file.FileName;
                if (!Regex.IsMatch(fileName, BLL.Setting.ALLOWEDEXTS, RegexOptions.IgnoreCase | RegexOptions.Compiled)) return new Model.AjaxResult(-4, "附件格式不允许上传！");
                var path = BLL.Setting.UPFILEPATH + "/JobTry/";
                Directory.CreateDirectory(server.MapPath(path));
                path += DateTime.Now.Ticks.ToString("X") + Path.GetExtension(fileName);
                file.SaveAs(server.MapPath(path));
                item.FileUrl = new Uri(request.Url, path).ToString();
            }
            this.Insert(item);
            return new Model.AjaxResult(0, "投递简历成功！");
        }
    }
}
