using Ropin.Inspection.Model;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Model.SearchModel;
using Ropin.Inspection.Model.ViewModel;
using Ropin.Inspection.Model.ViewModel.DEV;
using Ropin.Inspection.Repository.DEV.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ropin.Inspection.Repository.DEV
{
    public class dev_HandRepository : RepositoryBase<TDEV_Hand, Guid>, Idev_HandRepository
    {
        public dev_HandRepository(InspectionDbContext DbContext) : base(DbContext)
        {

        }
        public Task<IEnumerable<devHandViewModel>> GetConditionAsync(TdevHandSearchModel searchModel)
        {
            MySqlConnector.MySqlParameter[] parameters = new[] {
                new MySqlConnector.MySqlParameter("Status", searchModel.C_Status),
                new MySqlConnector.MySqlParameter("name",  "%"+searchModel.C_Name+"%"),
                new MySqlConnector.MySqlParameter("OrgCode", searchModel.C_OrgCode),
                new MySqlConnector.MySqlParameter("StoreCode", searchModel.C_StoreCode),
                new MySqlConnector.MySqlParameter("Id ", searchModel.C_ID.ToString())
            };
            StringBuilder sql = new StringBuilder();
            sql.Append("select h.*,g.C_Name as C_OrgName,ifnull(rh.bindCut,0) as bindCut from TDEV_Hand h LEFT JOIN TSYS_Org g on (h.C_OrgCode=g.C_Code) LEFT JOIN TPNT_StoreOrg stororg on (g.C_Code=stororg.C_OrgCode)  LEFT JOIN (select C_HandCode,count(C_RoleCode) as bindCut from TSYS_RoleHand group by C_HandCode) rh on (rh.C_HandCode=h.C_ID) where 1=1");

            if (!string.IsNullOrEmpty(searchModel.C_Status))
            {
                sql.Append(" and h.C_Status=@Status ");
            }
            else
            {
                sql.Append(" and h.C_Status!='0' ");
            }
            if (!string.IsNullOrEmpty(searchModel.C_Name))
            {
                sql.Append(" and h.C_Name like @name");
            }
            if (!string.IsNullOrEmpty(searchModel.C_OrgCode))
            {
                sql.Append(" and h.C_OrgCode=@OrgCode ");
            }
            if (!string.IsNullOrEmpty(searchModel.C_StoreCode))
            {
                sql.Append(" and stororg.C_StoreCode=@StoreCode ");
            }
            if (searchModel.C_ID!=Guid.Empty)
            {
                sql.Append(" and h.C_ID=@Id ");
            }
            sql.Append(" order by I_Sort ");

            IEnumerable<devHandViewModel> recordItemlist = EntityFrameworkCoreExtensions.GetList<devHandViewModel>(DbContext.Database, sql.ToString(), parameters);
            searchModel.TotalCount = recordItemlist.First() != null ? recordItemlist.ToList().Count : 0;
            return Task.FromResult(searchModel.IsPagination ? recordItemlist.Skip((searchModel.PageIndex - 1) * searchModel.PageSize).Take(searchModel.PageSize) : recordItemlist);
        }
    }
}