using System.Linq;
using FreeSql;
using JXCMS.CMS.Attribute;
using JXCMS.CMS.Entity;
using JXCMS.CMS.Movie.Entity;
using JXCMS.CMS.Movie.Spider;
using JXCMS.CMS.Movie.Utils;
using Microsoft.AspNetCore.Mvc;

namespace JXCMS.CMS.Movie.Admin.Controllers
{
    [Area("Admin")]
    [AdminAuthentication]
    public class ClassifyController : Controller
    {
        public IActionResult Index(int pageNumber = 1, int pageSize = 20)
        {
            var list = ClassifyEntity.Select.Include(x => x.Parent).Count(out long count).Page(pageNumber, pageSize).ToList(
                x => new ClassifyEntity{Id = x.Id, Name = x.Name, Alias = x.Alias, ParentId = x.ParentId, Parent = x.Parent, UpdateTime = x.UpdateTime,
                    Count = MovieEntity.Select.Where(y => y.ClassifyId == x.Id).Count()});
            ViewBag.count = count;
            ViewBag.pageNumber = pageNumber;
            ViewBag.totlePage = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            return View(list);
        }

        public IActionResult ClassifyDialog(int id)
        {
            
            ClassifyEntity classifyEntity = null;
            if (id == 0)
            {
                classifyEntity = new ClassifyEntity();
                ViewBag.title = "添加新分类";
                ViewBag.classifyEntities = ClassifyEntity.Select.ToList();
            }
            else
            {
                classifyEntity = ClassifyEntity.Find(id);
                ViewBag.title = "修改分类" + classifyEntity.Name;
                ViewBag.classifyEntities = Classify.FindAllNotChildren(ClassifyEntity.Select.ToList(), id);
            }
            return View(classifyEntity);
        }

        public IActionResult DeleteClassify(int id)
        {
            if (MovieEntity.Select.Any(x => x.ClassifyId == id))
            {
                return Redirect(Url.Action("Index"));
            }

            if (ClassifyEntity.Select.Any(x => x.ParentId == id))
            {
                ClassifyEntity.Where(x => x.ParentId == id).ToUpdate().Set(x => x.ParentId, 0).ExecuteAffrows();
            }

            ClassifyEntity.Find(id).Delete();
            return Redirect(Url.Action("Index"));
        }

        public IActionResult ModifyClassify(ClassifyEntity classifyEntity)
        {
            if (classifyEntity.Id != 0 && 
                Classify.FindAllChildren(ClassifyEntity.Select.ToList(), classifyEntity.Id).Any(x => x.Id == classifyEntity.ParentId))
            {
                return Redirect(Url.Action("Index"));
            }
            classifyEntity.Save();
            return Redirect(Url.Action("Index"));
        }
    }
}