using BookingWeb.DB;
using BookingWeb.Helper;
using BookingWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BookingWeb.Controllers
{
    public class LogController : BaseController
    {
        private InfoDB infoDB = new InfoDB();

        public ActionResult LogView()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogData(ReqLogQuery req, int offset = 1, int limit = 10)
        {
            RespPageData resp = new RespPageData();

            var query = infoDB.Logs.Where(l => l.OpCompanyId == CurrentCompany.GID);
            #region 条件
            if (!string.IsNullOrWhiteSpace(req.DATE_START))
            {
                var dtStart = DateTime.Parse(req.DATE_START);
                query = query.Where(o => o.OpTime >= dtStart);
            }

            if (!string.IsNullOrWhiteSpace(req.DATE_END))
            {
                var dtEnd = DateTime.Parse(req.DATE_END).AddDays(1);
                query = query.Where(o => o.OpTime < dtEnd);
            }

            if (!string.IsNullOrWhiteSpace(req.MBLNO))
            {
                query = query.Where(o => o.MBLNO == req.MBLNO);
            }

            #endregion

            resp.Total = query.Count();
            var list = query.OrderByDescending(o => o.OpTime).Skip(offset).Take(limit).ToList();
            resp.DataList = list.AsListViewModelList();
            return Json(resp);
        }

        [HttpPost]
        public ActionResult ChangeData(int logId)
        {
            RespChangeLog resp = new RespChangeLog();
            var log = infoDB.Logs.First(l => l.LogId == logId);
            var preLog = infoDB.Logs.OrderByDescending(l => l.LogId).FirstOrDefault(l => l.BillNO == log.BillNO && l.Module == log.Module && l.LogId < log.LogId);
            if (preLog != null)
            {
                resp.Success = true;
                resp.ChangeList = ChangeLogHelper.Compare(preLog, log);
            }
            else
            {
                resp.Success = false;
                resp.Message = Resources.LangLog.MsgNoPreviousLog;
            }

            return Json(resp);
        }
    }
}