using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.KpiRespository.Request;
using Siger.Middlelayer.KpiRespository.Respose;
using Siger.Middlelayer.Share.ModuleEnum;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common.AppSettings;
using System.IO;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Common.Extensions;

namespace Siger.ApiKPI.Controllers
{
    public class TasklistController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerKpiAuthority _kpiAuthority;
        private readonly ISigerKpiTasklist _kpiTasklist;
        private readonly ISigerKpiItem _kpiItem;
        private readonly ISigerKpiPushMessage _sigerKpiPushMessage;
        private readonly ISigerKpiItemDisplayPosition _itemDisplayPosition;

        /// <summary>
        /// 基本 数据维护
        /// </summary>
        /// <param name="unitOfWork"></param>
        /// <param name="kpiAuthority"></param>
        /// <param name="kpiTasklist"></param>
        /// <param name="kpiItem"></param>
        /// <param name="kpiPushMessage"></param>
        /// <param name="itemDisplayPosition"></param>
        public TasklistController(IUnitOfWork unitOfWork, ISigerKpiAuthority kpiAuthority, ISigerKpiTasklist kpiTasklist, ISigerKpiItem kpiItem,  ISigerKpiPushMessage kpiPushMessage, ISigerKpiItemDisplayPosition itemDisplayPosition)
        {
            _unitOfWork = unitOfWork;
            _kpiAuthority = kpiAuthority;
            _kpiTasklist = kpiTasklist;
            _kpiItem = kpiItem;
            _sigerKpiPushMessage = kpiPushMessage;
            _itemDisplayPosition = itemDisplayPosition;
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="status"></param>
        /// <param name="exception"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="taskResult"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetList(int section, string item, string begin, string end, int status, int exception, int page, int pageSize, int taskResult)
        {
            var data = _kpiTasklist.GetTaskItemPagedList(section, item, begin.ToDateTime(), end.ToDateTime(), status, exception, ProjectId, page, pageSize, taskResult);
            return new PagedObjectResult(data.Data, data.Total, page, pageSize);
        }
        /// <summary>
        /// 手机端
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="status"></param>
        /// <param name="exception"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult MoblieGetList(int section, string item, DateTime begin, DateTime end, int status, int exception, int page, int pageSize)
        {
            var itemobj = _kpiItem.Get(f => f.projectId == ProjectId && f.Item==item);
            if (itemobj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var beginDate = KpiCycleEnumHelper.GetCycleDate(itemobj.KpiCycle, begin);
            var data = _kpiTasklist.GetTaskItemMoblie(section, item, begin, end, status, exception, ProjectId, page, pageSize);
            return new PagedObjectResult(data.Data, data.Total, page, pageSize);
        }

        /// <summary>
        /// 面板展示 
        /// </summary>
        /// <param name="section"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DashboardDisplay(int section, DateTime date)
        {
            var dtTime = DateTimeHelper.GetDate(date);
            var result = new List<ResponseDashboardDisplay>();
            var displaySetting = _itemDisplayPosition.GetList(f => f.projectId == ProjectId && f.Section == section && f.Position!=0).OrderBy(o=>o.Position).ToList();
            foreach(var setting in displaySetting)
            {
                var itemObj = _kpiItem.Get(f => f.id == setting.Item);
                if (itemObj == null)
                    continue;
                var displayObj = new ResponseDashboardDisplay
                {
                    Position = setting.Position,
                    BackColor = setting.Color,
                    Unit=itemObj.Unit,
                    ItemId=itemObj.id,
                    ItemDesc = itemObj.Item,
                    TargetVal = itemObj.TargetVal,
                    Cycle =EnumHelper.GetEnumDesc(itemObj.KpiCycle),
                    Result= (int)KpiTaskResult.NoConfg,
                    ResultDesc = EnumHelper.GetEnumDesc(KpiTaskResult.NoConfg),
                    Section=itemObj.Section
                };
                var task = GetDisplayTask(itemObj, dtTime, itemObj.Section);
                if (task != null)
                {
                    displayObj.TaskId = task.id;
                    displayObj.CycleDesc = task.cycle;
                    displayObj.TargetVal = task.TargetVal;
                    displayObj.ActVal = task.ActVal;
                    displayObj.Result =(int)task.Result;
                    displayObj.ResultDesc = EnumHelper.GetEnumDesc(task.Result);
                }
                result.Add(displayObj);
            }
            return new ObjectResult(result);
        }
        private string GetDescrption(int result)
        {
            switch(result)
            {
                case 1:
                    return EnumHelper.GetEnumDesc(KpiTaskResult.NoConfg);
                case 2:
                    return EnumHelper.GetEnumDesc(KpiTaskResult.Exception);
                case 3:
                    return EnumHelper.GetEnumDesc(KpiTaskResult.Normal);
            }
            return string.Empty;
        }
        private SigerProjectKpiTasklist GetDisplayTask(siger_project_kpi_item kpiItem,DateTime currDate, int section)
        {
            DateTime cDate = currDate;
            switch(kpiItem.KpiCycle)
            {
                case KpiCycleEnum.Year:
                    {
                        cDate = currDate.AddYears(-1);
                        break;
                    }
                case KpiCycleEnum.Quarter:
                    {
                        cDate = currDate.AddMonths(-1 * 3);
                        break;
                    }
                case KpiCycleEnum.Month:
                    {
                        cDate = currDate.AddMonths(-1);
                        break;
                    }
                case KpiCycleEnum.Week:
                    {
                        cDate = currDate.AddDays(-1 * 7);
                        break;
                    }
                case KpiCycleEnum.Day:
                    {
                        break;
                    }
            }
            var querter = DateTimeHelper.GetQuarterByMonth(cDate.Month);
            var weekofYear = DateTimeHelper.GetWeekOfYear(cDate);
            var cycleText = KpiCycleEnumHelper.CycleTypeText(kpiItem.KpiCycle, querter, weekofYear, cDate);
            var task = _kpiTasklist.Get(f => f.Section == section && f.ItemId == kpiItem.id && f.cycle == cycleText);
            return task;
        }
        /// <summary>
        /// 月度 指标柱状显示
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMothItem(int section, int item, DateTime date)
        {
            var itemobj = _kpiItem.Get(f => f.projectId == ProjectId && f.id == item);
            if (itemobj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var beginDate = KpiCycleEnumHelper.GetCycleDate(itemobj.KpiCycle, date);
            var Data = _kpiTasklist.GetTaskItem(section, item, beginDate, date, ProjectId);
            var result = new ResponsChartData();
           

            DateTime dtDay;
            var cycleText = string.Empty;
            for (dtDay = beginDate; dtDay.CompareTo(date) <= 0; dtDay = dtDay.AddDays(1))
            {
                var stepStarTime = dtDay;
                var querter = DateTimeHelper.GetQuarterByMonth(stepStarTime.Month);
                var weekofYear = DateTimeHelper.GetWeekOfYear(stepStarTime);
                cycleText = KpiCycleEnumHelper.CycleTypeText(itemobj.KpiCycle, querter, weekofYear, stepStarTime);

                var obj = Data.FirstOrDefault(f => f.CycleText == cycleText);
                if (result.Date.Exists(f=>f.Contains(cycleText)))
                    continue;
                result.Date.Add(cycleText);

                if (obj != null)
                {
                    result.Item.Add(obj);
                    result.TargetVal.Add(obj.Target);
                    result.AddVal.Add(obj.AddVal);
                }
                else
                {
                    result.Item.Add(new ResponseTasklist
                    {
                        Busidate = cycleText,
                        ItemId = itemobj.id,
                        Item = itemobj.Item,
                        Val = "0",
                        Target = itemobj.TargetVal,
                        Unit = itemobj.Unit,
                        CycleText=cycleText
                    });
                    result.TargetVal.Add(itemobj.TargetVal);
                    result.AddVal.Add(0d);
                }
            }

            return new ObjectResult(result);
        }
        
        /// <summary>
        /// 月度 指标显示 异常列表
        /// </summary>
        /// <param name="section"></param>
        /// <param name="item"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMothItemException(int section, int item, DateTime date)
        {
            var itemobj = _kpiItem.Get(f => f.projectId == ProjectId && f.id == item);
            if (itemobj==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var beginDate = KpiCycleEnumHelper.GetCycleDate(itemobj.KpiCycle, date);
            var Data = _kpiTasklist.GetTaskItemRepeat(section, item, beginDate, date, ProjectId);
            return new ObjectResult(Data);
        }
        /// <summary>
        /// 添加KPI 任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody]RequestTasklist request)
        {
            var busidate = DateTimeHelper.GetDate(request.Busidate);
            var task = _kpiTasklist.Get(f => f.projectId == ProjectId && f.Busidate == busidate && f.ItemId == request.Item);
            if (task != null)
                throw new BadRequestException(CommonEnum.RecordExits);
            //var state = (int)KpiTaskResult.NoConfg;
            var tasktype = (int)KpiTaskType.Normal;

            var itemObj = _kpiItem.Get(request.Item);
            if (itemObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var state = _kpiTasklist.GetState(request.ActVal,task.TargetVal, itemObj);
            if (state == KpiTaskResult.Exception)
                tasktype = (int)KpiTaskType.Exception;

            _kpiTasklist.Insert(new SigerProjectKpiTasklist
            {
                Busidate = busidate,
                ActVal = request.ActVal,
                projectId = ProjectId,
                ItemId = request.Item,
                Result = state,
                Section = request.Section,
                Excption =KpiExecption.Default,
                Type = tasktype,
                status = (int)RowState.Valid
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        /// 编辑 kpi 任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody]RequestTasklist request)
        {
            //var busidate = DateTimeHelper.GetDate(request.Busidate);
            var task = _kpiTasklist.Get(request.Id);
            if (task == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var item = _kpiItem.Get(task.ItemId);
            if (item == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            task.ActVal = request.ActVal;
            task.Result = _kpiTasklist.GetState(request.ActVal,task.TargetVal, item);
            if (task.Result == KpiTaskResult.Exception)
            {
                task.Type = (int)KpiTaskType.Exception;

                if (!_sigerKpiPushMessage.IsExist(f => f.ProjectId == ProjectId && f.TaskId == task.id &&f.SectionId==task.Section && f.ItemId == item.id))
                {
                    _sigerKpiPushMessage.Insert(new SigerProjectKpiTaskMessage
                    {
                        ProjectId = ProjectId,
                        TaskId = task.id,
                        SectionId = task.Section,
                        ItemId = item.id,
                        Mode = Module.Kpi,
                        CreateTime=DateTime.Now,
                        LastUpdate = DateTime.Now,
                        LevelType = KpiPushSettingType.Exception,
                        Push = 0,
                        status = (int)RowState.Valid
                    });
                }
            }
            _kpiTasklist.Update(task);

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Delete(int id)
        {
            _kpiTasklist.Delete(id);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);
        }

        /// <summary>
        ///  导出
        /// </summary>
        /// <param name="section"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <param name="item"></param>
        /// <param name="exception"></param>
        /// <param name="resultstatus"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public IActionResult ExportAll(int section, string item, DateTime begin, DateTime end, int status, int exception, int resultstatus)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var data = _kpiTasklist.GetTaskItemPagedList(section, item, begin, end, status, exception, ProjectId, 1, 999999);
            var dataList = new List<KpiTasklistTemplate>();
            foreach (var _item in data.Data)
            {
                dataList.Add(new KpiTasklistTemplate
                {
                    SectionDesc = _item.SectionDesc,
                    Range = _item.Cycle,
                    Kpi = _item.Item,
                    Busidate = _item.Busidate,
                    Value = _item.Val,
                    Unit = _item.Unit,
                    Target = _item.Target,
                    Condition = _item.Condition,
                    ResultStatus = _item.TaskResultDesc,
                    Reposible = _item.ResponsiblePersion,
                    Plantime = _item.Plantime,
                    Solution = _item.Solution,
                    Remark = _item.Remark,
                    Reason = _item.Cause,
                    ActualFinishTime = _item.Operatetime
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<KpiTasklistTemplate> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<KpiTasklistTemplate>();
                    var temporaryFileName = $"KPI行动计划-{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("ExportKPIbase failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            return new ObjectResult(CommonEnum.Fail);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetlistByItem([FromBody]RequestInputTasklist request)
        {
            var item = _kpiItem.Get(f =>f.projectId==ProjectId &&f.Section==request.Section && f.id == request.ItemId);
            if (item==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            if (string.IsNullOrEmpty(request.BeginDate) || string.IsNullOrEmpty(request.EndDate)||request.BeginDate== "-0" )
                throw new BadRequestException(RequestEnum.ParameterMiss);
            var dateArry = GetRange(item, request.Section, request.BeginDate, request.EndDate);
            var data = _kpiTasklist.GetInputTasklists(request.Section, request.ItemId,item.KpiCycle, ProjectId, dateArry[0], dateArry[1],request.Page,request.PageSize);
            return new ObjectResult(data);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdValue([FromBody]RequestModifyInput input)
        {
            
            var task = _kpiTasklist.Get(f => f.projectId == ProjectId && f.id == input.TaskId);
            if (task==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            
            var permission = _kpiAuthority.VerifyPermission(UserId, task.Section);
            if (!permission)
                throw new BadRequestException(CommonEnum.NoDepartPermission);

            if (input.InputType == KpiUpdValue.Actval)
            {
                if (string.IsNullOrEmpty(input.ActVal))
                {
                    //清空 实际值时，重置状态未
                    task.ActVal = 0d;
                    task.Result = KpiTaskResult.NoConfg;
                    task.Type = (int)KpiTaskType.Normal;
                    task.Excption = KpiExecption.Default;
                }
                else
                {
                    if (!double.TryParse(input.ActVal, out double _actval))
                        throw new BadRequestException(RequestEnum.ParameterError);
                    var item = _kpiItem.Get(f => f.projectId == ProjectId && f.id == task.ItemId);
                    task.ActVal = _actval;
                    task.Result = _kpiTasklist.GetState(_actval, task.TargetVal, item);
                    if (task.Result == KpiTaskResult.Exception)
                    {
                        task.Type = (int)KpiTaskType.Exception;
                        task.Excption = KpiExecption.Default;
                        if (!_sigerKpiPushMessage.IsExist(f => f.ProjectId == ProjectId && f.TaskId == task.id && f.SectionId == task.Section && f.ItemId == item.id))
                        {
                            _sigerKpiPushMessage.Insert(new SigerProjectKpiTaskMessage
                            {
                                ProjectId = ProjectId,
                                TaskId = task.id,
                                SectionId = task.Section,
                                ItemId = item.id,
                                Mode = Module.Kpi,
                                CreateTime = DateTime.Now,
                                LastUpdate = DateTime.Now,
                                LevelType = KpiPushSettingType.Exception,
                                Push = 0,
                                status = (int)RowState.Valid
                            });
                        }
                    }
                    else
                    {
                        task.Type = (int)KpiTaskType.Normal;
                    }
                }
            }
            else if (input.InputType == KpiUpdValue.AddVal)
            {
                if (!double.TryParse(input.AddVal, out double _addval))
                    throw new BadRequestException(RequestEnum.ParameterError);
                task.AddVal = _addval;
            }
            else if (input.InputType == KpiUpdValue.TartgetVal)
            {
                if (!double.TryParse(input.TargetVal, out double _targetval))
                    throw new BadRequestException(RequestEnum.ParameterError);
                task.TargetVal = _targetval;
                var item = _kpiItem.Get(f => f.projectId == ProjectId && f.id == task.ItemId);
                task.Result = _kpiTasklist.GetState(task.ActVal, _targetval, item);
                if (task.Result == KpiTaskResult.Exception)
                {
                    task.Type = (int)KpiTaskType.Exception;
                    task.Excption = KpiExecption.Default;
                    if (!_sigerKpiPushMessage.IsExist(f => f.ProjectId == ProjectId && f.TaskId == task.id && f.SectionId == task.Section && f.ItemId == item.id))
                    {
                        _sigerKpiPushMessage.Insert(new SigerProjectKpiTaskMessage
                        {
                            ProjectId = ProjectId,
                            TaskId = task.id,
                            SectionId = task.Section,
                            ItemId = item.id,
                            Mode = Module.Kpi,
                            CreateTime = DateTime.Now,
                            LastUpdate = DateTime.Now,
                            LevelType = KpiPushSettingType.Exception,
                            Push = 0,
                            status = (int)RowState.Valid
                        });
                    }
                }
                else
                {
                    task.Type = (int)KpiTaskType.Normal;
                }

            }
            else
            {
                task.Remark = input.Remark;
            }

            _kpiTasklist.Update(task);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            else
                return new ObjectResult(CommonEnum.Fail);

        }
        private List<DateTime> GetRange(siger_project_kpi_item item,int section,string beginDate,string endDate)
        {
            var lstResult = new List<DateTime>();
            DateTime dtBegin = DateTime.MinValue;
            DateTime dtEnd = DateTime.MinValue;
            switch(item.KpiCycle)
            {
                case KpiCycleEnum.Year:
                    {
                        var beginYearStr = $"{beginDate}-01-01";
                        var endYearStr = $"{endDate}-01-01";
                        DateTime.TryParse(beginYearStr, out DateTime cDate);
                        DateTime.TryParse(endYearStr, out DateTime cDate2);
                        dtBegin = cDate;
                        dtEnd = cDate2;
                        var quarterStep = Math.Round(dtEnd.Subtract(dtBegin).TotalDays / 365);
                        int.TryParse(quarterStep.ToString(), out int step);
                        ValidateData(item,section,step, dtBegin);
                        break;
                    }
                case KpiCycleEnum.Quarter:
                    {
                        var beginArry = beginDate.Split('-');
                        var endArry = endDate.Split('-');
                        if (beginArry.Length > 1 && endArry.Length > 1)
                        {
                            var formatSYearStr = $"{beginArry[0]}-01-01";
                            int.TryParse(beginArry[1], out int querter);
                            var formatEYearStr = $"{endArry[0]}-01-01";
                            int.TryParse(endArry[1], out int querter2);
                            DateTime.TryParse(formatSYearStr, out DateTime cDate);
                            DateTime.TryParse(formatEYearStr, out DateTime cDate2);
                            if (querter==1)
                                dtBegin = cDate;
                            else
                                dtBegin = cDate.AddMonths(3 * querter).AddMonths(-1);

                            dtEnd = cDate2.AddMonths(3 * querter2).AddSeconds(-1);
                            if (dtBegin > dtEnd)
                                break;
                            var dayStep = Math.Round(dtEnd.Subtract(dtBegin).TotalDays / (30 * 3));
                            int.TryParse(dayStep.ToString(), out int step);
                            ValidateData(item, section, step, dtBegin);
                        }
                        break;
                    }
                case KpiCycleEnum.Month:
                    {
                        var beginArry = beginDate.Split('-');
                        var endArry = endDate.Split('-');
                        if (beginArry.Length > 1 && endArry.Length > 1)
                        {
                            var beginMonthStr = $"{beginDate}-01";
                            int.TryParse(beginArry[1], out int month);
                            var endMonthStr = $"{endDate}-01";
                            int.TryParse(endArry[1], out int month2);
                            DateTime.TryParse(beginMonthStr, out DateTime cDate);
                            DateTime.TryParse(endMonthStr, out DateTime cDate2);
                            dtBegin = cDate;
                            dtEnd = cDate2.AddMonths(1).AddSeconds(-1);
                            if (dtBegin > dtEnd)
                                break;
                            var dayStep = Math.Round(dtEnd.Subtract(dtBegin).TotalDays / 30);
                            int.TryParse(dayStep.ToString(), out int step);
                    
                            ValidateData(item, section, step, dtBegin);
                        }
                        break;
                    }
                case KpiCycleEnum.Week:
                    {
                        DateTime.TryParse(beginDate, out DateTime convertBeginDate);
                        DateTime.TryParse(endDate, out DateTime convertEndDate);
                        dtBegin = convertBeginDate;
                        dtEnd = convertEndDate.AddDays(1).AddSeconds(-1);

                        var dayStep = Math.Round(dtEnd.Subtract(dtBegin).TotalDays / 7);
                        int.TryParse(dayStep.ToString(), out int step);
                        ValidateData(item, section, step, dtBegin);
                        break;
                    }
                case KpiCycleEnum.Day:
                    {
                        DateTime.TryParse(beginDate, out DateTime convertBeginDate);
                        DateTime.TryParse(endDate, out DateTime convertEndDate);
                        dtBegin = convertBeginDate;
                        dtEnd = convertEndDate.AddDays(1);
                       
                        var dayStep = dtEnd.Subtract(dtBegin).TotalDays;
                        int.TryParse(dayStep.ToString(), out int step);
                        ValidateData(item, section, step-1, dtBegin);
                        break;
                    }
            }
            var sdt = dtBegin.Date.ToString("yyyy-MM-dd");
            var edt = dtEnd.Date.ToString("yyyy-MM-dd");
            DateTime.TryParse(sdt, out DateTime sdtime);
            DateTime.TryParse(edt, out DateTime edtime);
            lstResult.Add(sdtime);
            lstResult.Add(edtime);
            return lstResult;
        }

        private void ValidateData(siger_project_kpi_item item,int section,int step, DateTime beginDate)
        {
            switch (item.KpiCycle)
            {
                case KpiCycleEnum.Year:
                    {
                        for(var i=0;i <= step; i ++)
                        {
                            var currDate= beginDate.AddYears(i);
                            var cycleText = KpiCycleEnumHelper.CycleTypeText(item.KpiCycle, 0, 0, currDate);
                            if (!_kpiTasklist.IsExist(f=>f.projectId==ProjectId && f.ItemId==item.id && f.cycle==cycleText))
                            {
                                _kpiTasklist.Insert(new SigerProjectKpiTasklist
                                {
                                      projectId=ProjectId,
                                      Busidate=currDate,
                                      ItemId=item.id,
                                      Section=section,
                                      cycle=cycleText,
                                      TargetVal=item.TargetVal,
                                      status=(int)RowState.Valid
                                });
                                var ret=_unitOfWork.Commit();
                            }
                        }
                        
                        break;
                    }
                case KpiCycleEnum.Quarter:
                    {
                        for (var i = 0; i <= step; i++)
                        {
                            var currDate = DateTime.MinValue;
                            if (i == 0)
                                currDate = beginDate;
                            else
                                currDate = beginDate.AddMonths(3 * i);

                            var querter = DateTimeHelper.GetQuarterByMonth(currDate.Month);
                            var weekofYear = DateTimeHelper.GetWeekOfYear(currDate);
                            var cycleText = KpiCycleEnumHelper.CycleTypeText(item.KpiCycle, querter, weekofYear, currDate);
                            if (!_kpiTasklist.IsExist(f => f.projectId == ProjectId && f.ItemId == item.id && f.cycle == cycleText))
                            {
                                _kpiTasklist.Insert(new SigerProjectKpiTasklist
                                {
                                    projectId = ProjectId,
                                    Busidate = currDate,
                                    ItemId = item.id,
                                    Section = section,
                                    cycle = cycleText,
                                    TargetVal = item.TargetVal,
                                    status = (int)RowState.Valid
                                });
                                var ret = _unitOfWork.Commit();
                            }
                        }
                        break;
                    }
                case KpiCycleEnum.Month:
                    {
                        for (var i = 0; i <= step; i++)
                        {
                            var currDate = DateTime.MinValue;
                            if (i == 0)
                                currDate = beginDate;
                            else
                                currDate = beginDate.AddMonths(i);
                            var querter = DateTimeHelper.GetQuarterByMonth(currDate.Month);
                            var weekofYear = DateTimeHelper.GetWeekOfYear(currDate);
                            var cycleText = KpiCycleEnumHelper.CycleTypeText(item.KpiCycle, querter, weekofYear, currDate);
                            if (!_kpiTasklist.IsExist(f => f.projectId == ProjectId && f.ItemId == item.id && f.cycle == cycleText))
                            {
                                _kpiTasklist.Insert(new SigerProjectKpiTasklist
                                {
                                    projectId = ProjectId,
                                    Busidate = currDate,
                                    ItemId = item.id,
                                    Section = section,
                                    cycle = cycleText,
                                    TargetVal = item.TargetVal,
                                    status = (int)RowState.Valid
                                });
                                var ret = _unitOfWork.Commit();
                            }
                        }
                        break;
                    }
                case KpiCycleEnum.Week:
                    {
                        for (var i = 0; i <= step; i++)
                        {
                            var currDate = DateTime.MinValue;
                            if (i == 0)
                                currDate = beginDate;
                            else
                                currDate = beginDate.AddDays(7 * i);
                            var querter = DateTimeHelper.GetQuarterByMonth(currDate.Month);
                            var weekofYear = DateTimeHelper.GetWeekOfYear(currDate);
                            var cycleText = KpiCycleEnumHelper.CycleTypeText(item.KpiCycle, querter, weekofYear, currDate);
                            if (!_kpiTasklist.IsExist(f => f.projectId == ProjectId && f.ItemId == item.id && f.cycle == cycleText))
                            {
                                _kpiTasklist.Insert(new SigerProjectKpiTasklist
                                {
                                    projectId = ProjectId,
                                    Busidate = currDate,
                                    ItemId = item.id,
                                    Section = section,
                                    cycle = cycleText,
                                    TargetVal = item.TargetVal,
                                    status = (int)RowState.Valid
                                });
                                var ret = _unitOfWork.Commit();
                            }
                        }
                        break;
                    }
                case KpiCycleEnum.Day:
                    {
                        for (var i = 0; i <= step; i++)
                        {
                            var currDate = DateTime.MinValue;
                            if (i == 0)
                                currDate = beginDate;
                            else
                                currDate = beginDate.AddDays(i);
                            var querter = DateTimeHelper.GetQuarterByMonth(currDate.Month);
                            var weekofYear = DateTimeHelper.GetWeekOfYear(currDate);
                            var cycleText = KpiCycleEnumHelper.CycleTypeText(item.KpiCycle, querter, weekofYear, currDate);
                            if (!_kpiTasklist.IsExist(f => f.projectId == ProjectId && f.ItemId == item.id && f.cycle == cycleText))
                            {
                                _kpiTasklist.Insert(new SigerProjectKpiTasklist
                                {
                                    projectId = ProjectId,
                                    Busidate = currDate,
                                    ItemId = item.id,
                                    Section = section,
                                    cycle = cycleText,
                                    TargetVal = item.TargetVal,
                                    status = (int)RowState.Valid
                                });
                                var ret = _unitOfWork.Commit();
                            }
                        }
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
    }
}
