using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Dapper;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis.Model;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.ToolRepository.Entities;
using Siger.Middlelayer.ToolRepository.Repositories.Interface;
using Siger.Middlelayer.ToolRepository.Request;

namespace Siger.ApiTools.Controllers
{
    public class ToolChangeManagementDevController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        readonly ISigerToolChangeRecordRepository _sigerToolChangeRecord;
        readonly ISigerProjectToolSpindleTrueRepository _sigerProjectToolSpindleTrueRepository;
        readonly ISigerProjectToolCutterLocationTrueRepository _sigerProjectToolCutterLocationTrueRepository;

        public ToolChangeManagementDevController(IUnitOfWork unitOfWork, ISigerToolChangeRecordRepository sigerToolChangeRecord, ISigerProjectToolSpindleTrueRepository sigerProjectToolSpindleTrueRepository, ISigerProjectToolCutterLocationTrueRepository sigerProjectToolCutterLocationTrueRepository)
        {
            _unitOfWork = unitOfWork;
            _sigerToolChangeRecord = sigerToolChangeRecord;
            _sigerProjectToolSpindleTrueRepository = sigerProjectToolSpindleTrueRepository;
            _sigerProjectToolCutterLocationTrueRepository = sigerProjectToolCutterLocationTrueRepository;
        }

        [HttpGet]
        public IActionResult GetMachineList(int sectionID)
        {
            return new ObjectResult(_sigerToolChangeRecord.GetMachineList(sectionID, ProjectId));
        }
        [HttpGet]
        public IActionResult GetSpindleList(int machine_id)
        {
            var result=_sigerProjectToolSpindleTrueRepository.GetList(f => f.equipid == machine_id && f.status == (int)RowState.Valid).Select(f=>
            new
            {
                spindle_id=f.id,
                spindle_name=f.name
            });
            if (!result.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(result);
        }
        /// <summary>
        /// 刀位号下拉 刀具更换记录添加表单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCutterLocationList(int spindle_id)
        {
            var result=_sigerProjectToolCutterLocationTrueRepository.GetList(
                f=>f.spindleid==spindle_id &&
                    f.status==(int)RowState.Valid &&f.is_processing_program!=(int)ProcessProgram.NoConfig
            ).Select(f=>new { cutter_location_name = f.name }).Distinct();
            if (!result.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(result);
        }

        [HttpGet]
        public IActionResult GetChangeRecordDetail(int id)
        {
            var result = _sigerToolChangeRecord.GetList(f => f.id == id).Select(f => new
            {
                f.id,
                machine_code = f.equip_code,
                machine_name = f.equip_name,
                f.tool_name,
                drawingcode = f.tool_drawno,
                cutter_location_name = f.tool_no,
                ratedlife = f.rating_life,
                residual_life = f.residual_life ?? 0,
                surplus_life = f.true_residual_life,
                change_time = UnixTimeHelper.ConvertIntDateTime(f.change_time),
                f.comment,
                spindle_name = f.mainaxis,
                f.supplier,
                f.change_reason,
                f.programno,
                f.url_path
            }).FirstOrDefault();
            if (result == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            return new ObjectResult(result);
        }

        [HttpGet]
        public IActionResult GetChangeRecordOtherInfo(int machine_id, int spindle_id, string cutter_location_name)
        {
            var result=_sigerProjectToolCutterLocationTrueRepository.GetChangeRecordOtherInfo(ProjectId,CompanyId, machine_id,spindle_id,cutter_location_name);
            if (result != null)
            {
                return new ObjectResult(result);
            }
            throw new BadRequestException(CommonEnum.RecordNotFound);
        }

        [HttpPost]
        public IActionResult ChangeRecordEdit([FromBody]RequestTooChangeModify changeModify)
        {
            var record = _sigerToolChangeRecord.Get(changeModify.id.ToInt());
            var originalRecord = record;
            if (record == null || record.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            record.true_residual_life = changeModify.surplus_life;
            record.residual_life = changeModify.residual_life;
            record.change_time = UnixTimeHelper.GetUnixByShortDate(changeModify.change_time);
            record.comment = changeModify.comment;
            record.change_reason = changeModify.change_reason;
            record.url_path = changeModify.url_path;
            _sigerToolChangeRecord.Update(record);
            //GrayImage info
            //_sigerProjectToolChangeExtend.Insert(new SigerProjectToolChangeExtend
            //{
            //    MachineID = changeRecord.machine_id,
            //    Spindle = int.Parse(changeRecord.spindle_name),
            //    Tool = int.Parse(changeRecord.cutter_location_name),
            //    Program = changeRecord.programno,
            //    ChangeTime = UnixTimeHelper.GetUnixByShortDate(changeRecord.change_time),
            //    Project = ProjectId

            //});
            if (_unitOfWork.Commit() > 0)
            {
                try
                {
                    var redis = new ChangeToolRepository(CompanyId, ProjectId);
                    //1.5.2
                    var dapper = new ToolAlarmRepository(CompanyId, ProjectId);
           
                    var actime = DateTime.Now;
                    var spTime = dapper.GetSlicePeriod(record.programno, record.machine_id);
                    if (spTime != null)
                    {
                        var spTimeS = UnixTimeHelper.GetUnixByShortDate(spTime.starttime.ToStr());
                        var spTimeE = UnixTimeHelper.GetUnixByShortDate(spTime.endtime.ToStr());
                        var ChangeTime = UnixTimeHelper.GetUnixByShortDate(record.change_time.ToStr());

                        if (ChangeTime >= spTimeS && ChangeTime <= spTimeE)
                            actime = UnixTimeHelper.ConvertStringDateTime(ChangeTime.ToStr());
                        else
                            actime = UnixTimeHelper.ConvertStringDateTime(spTimeE.ToStr());
                    }

                    var modelOri = Mapper<siger_tool_change_record, RedisChangeRecordModel>.Map(originalRecord);
                    var model = Mapper<siger_tool_change_record, RedisChangeRecordModel>.Map(record);
                    redis.UpdateChangeToolsRecord(modelOri, model, actime);
                }
                catch (Exception exception)
                {
                    Logger.WriteLineError("Sync update ToolChangeRecord failed :error:" + exception.Message);
                }
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}