﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

using OneDream.Models;
using OneDream.SiteUtils;
using OneDream.BLL;
using OneDream.Configuration;
using OneDream.Enum;

using X.Common;
using PagedList;

namespace OneDream.Controllers.CMS
{
    public class _ProductController : CMSBaseController
    {
        public ActionResult ProductList(string kw, int? c, int? pi)
        {
            int pageIndex = pi == null ? defaultPageIndex : (int)pi;
            int cid = c == null ? defaultIntValue : (int)c;
            TempData["cid"] = cid;

            kw = !string.IsNullOrEmpty(kw) ? kw : "";
            string keyword = siteUtil.UrlDecode(kw);
            TempData["keyword"] = keyword;
            TempData["kw"] = kw;

            ViewData[setCfgInstance.PAGE_INDEX_VIEWDATA_KEY] = pageIndex;
            ViewData["ps"] = defaultPageSize;

            int total = 0;

            ProductSearchConditionModel sc = new ProductSearchConditionModel();
            sc.Keyword = keyword;
            sc.CategoryID = cid;
            ProductBLL bll = new ProductBLL();
            var list = bll.GetProductListByCondition(sc, pageIndex, defaultPageSize, out total);
            var pagedList = new StaticPagedList<ProductModel>(list, pageIndex, defaultPageSize, total);

            ViewData[setCfgInstance.TOTAL_ITEM_VIEWDATA_KEY] = total;

            return View(pagedList);
        }

        public ActionResult ProductDetail(string id, string redirect)
        {
            if (string.IsNullOrEmpty(id) || TypeConverter.StrToInt(id) == defaultIntValue)
            {
                return Redirect(Utils.UrlDecode(redirect));
            }

            return View();
        }

        public ActionResult ProductEdit(string act, int? id, string redirect)
        {
            ActionEnum action = string.IsNullOrEmpty(act) ? ActionEnum.Add : (ActionEnum)(TypeConverter.StrToInt(act, (int)ActionEnum.Add));
            redirect = string.IsNullOrEmpty(redirect) ? "/cms/_product/productlist" : redirect;
            OD_Product p = new OD_Product();
            if (action == ActionEnum.Edit)
            {
                if (id == null)
                {
                    return Redirect(Utils.UrlDecode(redirect));
                }
                var model = (new ProductBLL()).GetProductInfoByID((int)id);
                p = model.Info;
            }

            TempData[setCfgInstance.REDIRECT_TEMPDATA_KEY] = HttpUtility.UrlDecode(redirect);

            return View(p);
        }

        [HttpPost]
        public ActionResult ProductEdit(int? action, OD_Product model, string redirect)
        {

            TempData[setCfgInstance.REDIRECT_TEMPDATA_KEY] = HttpUtility.UrlDecode(redirect);

            return View(model);
        }
    }
}
