using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Filters;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.CncRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Siger.Middlelayer.Common.Extensions;

namespace Siger.ApiCNC.Controllers
{
    /// <summary>
    /// 计划外派工控制器
    /// </summary>
    public class ProductPlanOutDispatchController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProjectProductPlanOutDispatchReponsitory _projectProductPlanOutDispatchReponsitory;
        private readonly IProductRouteRepository _productRouteRepository;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        public ProductPlanOutDispatchController(IUnitOfWork unitOfWork, IProjectProductPlanOutDispatchReponsitory projectProductPlanOutDispatchReponsitory,
            IProductRouteRepository productRouteRepository, ISigerProjectUserRepository projectUserRepository)
        {
            _unitOfWork = unitOfWork;
            _projectProductPlanOutDispatchReponsitory = projectProductPlanOutDispatchReponsitory;
            _productRouteRepository = productRouteRepository;
            _projectUserRepository = projectUserRepository;
        }

        /// <summary>
        /// 计划外派工查询
        /// </summary>
        /// <param name="tasknumber">任务编号</param>
        /// <param name="executive">执行人员</param>
        /// <param name="starttime">派工日期开始</param>
        /// <param name="endtime">派工日期结束</param>
        /// <param name="taskname">任务名称</param>
        /// <param name="page">第几页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetOutDataList(string tasknumber, string executive, string starttime, string endtime,string  taskname,int page, int pagesize)
        {
            var dtStart = string.IsNullOrWhiteSpace(starttime) ? 0 : UnixTimeHelper.GetUnixByShortDate(starttime);
            var dtEnd = string.IsNullOrWhiteSpace(endtime) ? 0 : UnixTimeHelper.GetUnixByShortDate(endtime) + 86400 - 1;
            var data = _projectProductPlanOutDispatchReponsitory.GetPagedProductPlanOutDispatch(tasknumber, executive, dtStart, dtEnd, taskname, ProjectId, page, pagesize);
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="request">参数</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddData([FromBody]RequestProductPlanOutDispatch request)
        {
            var data = _projectProductPlanOutDispatchReponsitory.GetData(ProjectId);
            var userData = _projectUserRepository.Get(f=>f.mid== UserId);
            var userName = "";
            if (userData!=null)
            {
                userName = userData.name;
            }
            var plan = new siger_project_product_plan_out_dispatch
            {
                projectid = ProjectId,
                createuser = userName,
                state = (int)PlanOutDispatch.UnReport,
                createtime = UnixTimeHelper.GetNow(),
                tasknumber = GetTaskNumber(data.count),
                groupid=request.group,
                planexecutor =request.planexecutor,
                expectedtime=request.expectedtime,
                taskname = request.taskname,
                taskcontent=request.taskcontent,
            };
            _projectProductPlanOutDispatchReponsitory.Insert(plan);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 获取任务编号值--固定格式  “JHW-”+时间yyyyMMdd+"-"+000三位编码
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public string GetTaskNumber(int count) 
        {
            var str = "JHW-";
            var dateStr =DateTime.Now.ToString("yyyyMMdd") + "-";
            var countStr = "000".Remove(3 - (count + 1).ToStr().Length, (count + 1).ToStr().Length) + (count + 1);
            var lastStr = str + dateStr + countStr;
            return lastStr;
        }

        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="id">数据id</param>
        /// <returns></returns>
        [HttpGet]
        //[NoTokenValidateFilter]
        public IActionResult ToVoid(int id) 
        {
            var data = _projectProductPlanOutDispatchReponsitory.Get(f=>f.id==id);
            if (data==null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (data.state!=1)
            {
                throw new BadRequestException(CncEnum.DataToVoid);
            }
            data.state = 5;
            _projectProductPlanOutDispatchReponsitory.Update(data);
                      
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 获取报工得数据
        /// </summary>
        /// <param name="id">数据id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReportData(int id) 
        {
            var data = _projectProductPlanOutDispatchReponsitory.GetReport(id,ProjectId);
            if (data == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new  ObjectResult(data);
        }

        /// <summary>
        /// 报工
        /// </summary>
        /// <param name="id">数据id</param>
        /// <param name="actualtime">实际工时</param>
        /// <param name="actualexecutor">实际执行人</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ToReport(int id,string actualtime,string actualexecutor)
        {
            var data = _projectProductPlanOutDispatchReponsitory.Get(f => f.id == id && f.projectid == ProjectId);
            if (data == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (data.state != 1)
            {
                throw new BadRequestException(CncEnum.DataToReport);
            }
            data.state = (int)PlanOutDispatch.HasReport;
            data.actualtime = actualtime.ToDouble();
            data.actualexecutor = actualexecutor.ToInt();
            data.reportingtime = UnixTimeHelper.GetNow();
            _projectProductPlanOutDispatchReponsitory.Update(data);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id">数据id</param>
        /// <param name="yesorno">通过或不通过 ---1或2</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ToExamine(int id,int yesorno)
        {
            var data = _projectProductPlanOutDispatchReponsitory.Get(f => f.id == id && f.projectid == ProjectId);
            if (data == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (data.state != (int)PlanOutDispatch.HasReport)
            {
                throw new BadRequestException(CncEnum.DataToExamine);
            }
            if (yesorno==1)
            {
                data.state = (int)PlanOutDispatch.Reviewed;
            }
            else
            {
                data.state = (int)PlanOutDispatch.UnReviewed;
            }
            _projectProductPlanOutDispatchReponsitory.Update(data);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 计划外报工 -app 获取计划详情
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetOutPlanOrder(string orderNo)
        {
            var obj = _projectProductPlanOutDispatchReponsitory.Get(f => f.tasknumber == orderNo && f.status == (int)RowState.Valid);
            return new ObjectResult(obj);

        }
    }
}
