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

namespace Siger.ApiCNC.Controllers
{
    public class ProductChangeController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IProductPlanRepository _planRepository;
        private readonly IProjectProductPlanChangeRecordReponsitory _projectProductPlanChangeRecordReponsitory;
        public ProductChangeController(IUnitOfWork unitOfWork, IProductPlanRepository planRepository, IProjectProductPlanChangeRecordReponsitory projectProductPlanChangeRecordReponsitory)
        {
            _unitOfWork = unitOfWork;
            _planRepository = planRepository;
            _projectProductPlanChangeRecordReponsitory = projectProductPlanChangeRecordReponsitory;      
        }

        /// <summary>
        /// 计划变更记录查询
        /// </summary>
        /// <param name="ordernumber">订单号</param>
        /// <param name="product_name">产品名称</param>
        /// <param name="startTime">变更时间开始</param>
        /// <param name="endTime">变更时间结束</param>
        /// <param name="audit_state">变更状态</param>
        /// <param name="page">第几页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDataList(string ordernumber,string product_name, string startTime, string endTime, int audit_state,
           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 = _projectProductPlanChangeRecordReponsitory.GetPagedProductPlan(product_name, ordernumber, dtStart,
                dtEnd, audit_state, ProjectId, page, pagesize);
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        /// <summary>
        /// 计划变更记录审核
        /// </summary>
        /// <param name="id">数据id</param>
        /// <param name="audit_state">审核状态</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult UpdateAuditState(int id,int audit_state) 
        {
            var data= _projectProductPlanChangeRecordReponsitory.Get(f => f.id == id && f.audit_state == (int)AuditState.WaitState && f.projectid == ProjectId);
            if (data==null)
            {
                return new ObjectResult(CommonEnum.RecordNotFound);
            }
            var entity = _planRepository.Get(f => f.id == data.plan_id && f.projectid == ProjectId);
            if (entity==null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (audit_state == (int)AuditState.Reviewed)
            {
                //判断是哪个字段变更
                if (data.change_project == PlanChange.OrderNumber)
                {
                    entity.ordernumber = data.change_after;
                }
                else if (data.change_project == PlanChange.Quantity)
                {
                    entity.quantity = data.change_after.ToInt();
                }
                else if (data.change_project == PlanChange.InstallCount)
                {
                    entity.install_count = data.change_after.ToInt();
                }
                else if (data.change_project == PlanChange.DeliveryTime)
                {
                    entity.delivery_time = UnixTimeHelper.GetUnixByShortDate(data.change_after);
                }
                _planRepository.Update(entity);
            }
            data.audit_state = audit_state;
            _projectProductPlanChangeRecordReponsitory.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 GetDate(int id)
        {
            var data = _projectProductPlanChangeRecordReponsitory.Get(f => f.id == id && f.projectid == ProjectId && f.audit_state == 0);
            if (data != null)
            {
                return new ObjectResult(CncEnum.DataAlreadyExists);
            }           
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 订单变更
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult EditOrdeChange([FromBody]RequestProductPlanChangeRecord request)
        {
            if (request == null)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            var entity = _planRepository.Get(f => f.id == request.id && f.projectid == ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (request.quantity > 5000)
            {
                throw new BadRequestException(CncEnum.PlanQuanlityOverFlow);
            }
            if (_projectProductPlanChangeRecordReponsitory.IsExist(f=>f.plan_id==entity.id && f.audit_state==1))
            {
                throw new BadRequestException(CncEnum.PlanHasUnApprovRecord);
            }
            var datas = new List<siger_project_product_plan_change_record>();
            if (request.ordernumber != entity.ordernumber)
            {
                var data = GetData(entity, request,(int)PlanChange.OrderNumber);
                datas.Add(data);
            }
            if (request.quantity != entity.quantity)
            {
                var data = GetData(entity, request,(int)PlanChange.Quantity);
                datas.Add(data);
            }
            if (request.install_count != entity.install_count)
            {
                var data = GetData(entity, request,(int)PlanChange.InstallCount);
                datas.Add(data);
            }
            if (request.delivery_time != UnixTimeHelper.ConvertIntDate(entity.delivery_time))
            {
                var data = GetData(entity, request,(int)PlanChange.DeliveryTime);
                datas.Add(data);               
            }
            if (!datas.Any())
            {
                throw new BadRequestException(CncEnum.PlanNoChangeData); 
            }
            _projectProductPlanChangeRecordReponsitory.Insert(datas);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 订单变更功能
        /// </summary>
        /// <param name="entity">原数据值</param>
        /// <param name="request">传参</param>
        /// <param name="type">变更类别</param>
        /// <returns></returns>
        public siger_project_product_plan_change_record GetData(siger_project_product_plan entity, RequestProductPlanChangeRecord request, int type)
        {
            var changeEntity = new siger_project_product_plan_change_record()
            {
                projectid = ProjectId,
                plan_id = entity.id,
                ordernumber = entity.ordernumber,
                code = entity.code,
                product_name = entity.product_name,
                product_code = entity.product_code,
                draw_number = entity.draw_number,
                quantity = entity.quantity,
                install_count = entity.install_count,
                delivery_time = entity.delivery_time,
                audit_state = (int)AuditState.WaitState,
                change_time = UnixTimeHelper.GetNow()
            };
            switch (type)
            {
                case 1:
                    changeEntity.change_project = PlanChange.OrderNumber;
                    changeEntity.change_before = entity.ordernumber;
                    changeEntity.change_after = request.ordernumber;
                    break;
                case 2:
                    changeEntity.change_project = PlanChange.Quantity;
                    changeEntity.change_before = entity.quantity.ToStr();
                    changeEntity.change_after = request.quantity.ToStr();
                    break;
                case 3:
                    changeEntity.change_project = PlanChange.InstallCount;
                    changeEntity.change_before = entity.install_count.ToStr();
                    changeEntity.change_after = request.install_count.ToStr();
                    break;
                case 4:
                    changeEntity.change_project = PlanChange.DeliveryTime;
                    changeEntity.change_before = UnixTimeHelper.ConvertIntDate(entity.delivery_time);
                    changeEntity.change_after = request.delivery_time;
                    break;
            }
            return changeEntity;
        }
    }
}
