using Sugar.Enties;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NLog;

/// <summary>
/// 进度计划管理
/// </summary>
public class pmProgressManager : DbContext<pmProgress>
{
    /// <summary>
    /// 日志
    /// </summary>
    private static Logger Logger = NLog.LogManager.GetCurrentClassLogger();

    /// <summary>
    /// 根据lambda获取进度计划列表  SELECT * FROM pmProgress WHERE ProjectCode='100114' AND IsMaster IN (1,2) AND State<>4
    /// </summary>
    /// <param name="lambda"></param>
    /// <returns></returns>
    public List<pmProgress> GetPmProgresses(Expression<Func<pmProgress, bool>> lambda)
    {
        var list = Db.Queryable<pmProgress>().Where(lambda).ToList();
        return list;
    }
    /// <summary>
    /// 获取进度项列表
    /// </summary>
    /// <param name="expressIds">进度计划ID串</param>
    /// <param name="projectCode">项目编号</param>
    /// <returns></returns>
    public List<pmProgressDTO> GetPmProgressDTOs(string expressIds, string searchValue)
    {
        var sql = $"select a.id ProgressNodeId,p.projectcode,a.progressid,cast(null as varchar) as icon,p.progressname,p.ismaster,a.nodename,a.progresstype,a.status,a.completepercent,a.plannedstartdate,a.plannedfinishdate,a.actualstartdate,a.actualfinishdate,cast(null as varchar) as isexceed,a.outlinelevel,a.masternodeid,a.iscompanykey,cast(null as varchar) as lightstate from pmProgressNode as a join pmProgress as p on p.Id=a.ProgressId where  a.ProgressId in ({expressIds}) and (p.progressname like '%{searchValue}%' or a.nodename like '%{searchValue}%') and not exists (select * from pmProgressNode b where b.ProgressId = a.ProgressId and b.OutlineNumber like a.OutlineNumber + '.%') and not exists (select * from pmProgress p where p.MasterNodeId = a.Id)  order by p.progressname asc ";
        var list = Db.Ado.SqlQuery<pmProgressDTO>(sql);
        return list;
    }
    /// <summary>
    /// 获取进度主项步骤，先按名称排序，再按实际执行时间倒序
    /// </summary>
    /// <param name="expressIds"></param>
    /// <param name="projectCode"></param>
    /// <returns></returns>
    public List<pmProgressDTO> GetPmProgressDTOs(string expressIds)
    {
        var sql = $"select a.id ProgressNodeId,p.projectcode,a.progressid,cast(null as varchar) as icon,p.progressname,p.ismaster,a.nodename,a.progresstype,a.status,a.completepercent,a.plannedstartdate,a.plannedfinishdate,a.actualstartdate,a.actualfinishdate,cast(null as varchar) as isexceed,a.outlinelevel,a.masternodeid,a.iscompanykey,cast(null as varchar) as lightstate,a.Duration from pmProgressNode as a join pmProgress as p on p.Id=a.ProgressId where a.ProgressId in ({expressIds})  and not exists (select * from pmProgressNode b where b.ProgressId = a.ProgressId and b.OutlineNumber like a.OutlineNumber + '.%') and not exists (select * from pmProgress p where p.MasterNodeId = a.Id)   order by p.progressname asc";
        var list = Db.Ado.SqlQuery<pmProgressDTO>(sql);
        return list;
    }
    /// <summary>
    /// 根据节点id获取进度报告
    /// </summary>
    /// <param name="progressNodeId"></param>
    /// <returns></returns>
    public List<pmProgressReport> GetpmProgressReports(int progressNodeId)
    {
        var list = pmProgressReportDb.GetList(m => m.ProgressNodeId == progressNodeId && m.State == 2).OrderBy(m => m.ActualStartDate).ToList();
        return list;
    }
    /// <summary>
    /// 进度报告列表
    /// </summary>
    /// <param name="progressNodeId">工作项ID</param>
    /// <returns></returns>
    public List<pmProgressReportDTO> GetpmProgressReportDTOs(int progressNodeId)
    {
        var sql = $"SELECT  a.*,b.ProgressName,c.NodeName  FROM dbo.pmProgressReport a INNER JOIN dbo.pmProgress b ON a.ProgressId=b.Id INNER JOIN dbo.pmProgressNode c ON a.ProgressNodeId=c.Id where a.ProgressNodeId={progressNodeId}  order by a.id";
        var list = Db.Ado.SqlQuery<pmProgressReportDTO>(sql);
        return list;
    }
    /// <summary>
    /// 根据进度报告id获取进度报告实例
    /// </summary>
    /// <param name="progressReportId"></param>
    /// <returns></returns>
    public pmProgressReportDTO GetpmProgressReportDTO(int progressReportId)
    {
        var sql = $"SELECT  a.*,b.ProgressName,c.NodeName  FROM dbo.pmProgressReport a INNER JOIN dbo.pmProgress b ON a.ProgressId=b.Id INNER JOIN dbo.pmProgressNode c ON a.ProgressNodeId=c.Id where a.id={progressReportId}  ";
        var list = Db.Ado.SqlQuerySingle<pmProgressReportDTO>(sql);
        return list;
    }
    /// <summary>
    /// 插入进度报告
    /// </summary>
    /// <param name="report"></param>
    /// <returns></returns>
    public string InsertProgressReport(pmProgressReport report)
    {
        if (report.CompletePercent <= 0)
        {
            return "-1";  //进度不能小于等于0
        }
        if (report.CompletePercent > 100)
        {
            return "-2";    //进度不能大于100
        }
        if (report.CompletePercent < 100)
        {
            report.ActualFinishDate = null;
        }
        report.State = 0;
        var id = Db.Insertable(report).ExecuteReturnIdentity();
        return id.ToString();
    }

    /// <summary>
    /// 根据工作项ID，搜索所有父级ID及本级ID组合为列表
    /// </summary>
    /// <param name="nodeId">本级工作项ID</param>
    /// <returns></returns>
    public List<int> GetAllParentProgressNodeId(int nodeId)
    {
        var listNew = new List<int>();
        listNew.Add(nodeId);
        var sql = $"SELECT OutlineNumber,id,ProgressId  FROM pmprogressnode WHERE id={nodeId}";
        var entity = Db.Ado.SqlQuerySingle<pmProgressNodeDTO>(sql);

        var outlineNumber = entity.OutlineNumber;
        var arr = outlineNumber.Split('.');
        if (arr.Length > 1)
        {
            int i = 0;
            foreach (var item in arr)
            {
                if (arr.Length - 1 == i)
                {
                    break;
                }
                string outlineNumber1 = "";
                for (var j = 0; j <= i; j++)
                {
                    outlineNumber1 += arr[j] + ".";
                }
                if (outlineNumber1.EndsWith("."))
                {
                    outlineNumber1 = outlineNumber1.Substring(0, outlineNumber1.Length - 1);
                }
                sql = $"SELECT OutlineNumber,id,ProgressId  FROM pmprogressnode WHERE ProgressId={entity.ProgressId} and OutlineNumber='{outlineNumber1}'";
                var entity1 = Db.Ado.SqlQuerySingle<pmProgressNodeDTO>(sql);
                listNew.Add(entity1.Id);
                i++;
            }
        }
        return listNew;

    }
    /// <summary>
    /// 获取此节点拥有责任人权限的用户列表，或者是责任人用户，或者是查看人用户
    /// </summary>
    /// <param name="nodeIds">节点及其父节点集合</param> 
    /// <returns></returns>
    public List<string> GetNodeRightUserCodeList(List<int> nodeIds)
    {
        var list = pmProgressNodePersonDb.GetList(m => nodeIds.Contains((int)m.ProgressNodeId) && m.Type == 1);
        var usercodes = new List<string>();
        foreach (var item in list)
        {
            usercodes.Add(item.UserCode);
        }
        return usercodes;
    }
    /// <summary>
    /// 获取此进度计划查看人权限用户  查看人权限用户不分节点，在pmProgressNodePerson表中ProgressNodeId均为null
    /// </summary>
    /// <param name="progressId"></param>
    /// <returns></returns>
    public List<string> GetProgressRightUserCodeList(int progressId)
    {
        var list = pmProgressNodePersonDb.GetList(m => m.ProgressId == progressId && m.Type == 2);
        var usercodes = new List<string>();
        foreach (var item in list)
        {
            usercodes.Add(item.UserCode);
        }
        return usercodes;
    }



}
