using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.ToolRepository.Entities;
using Siger.Middlelayer.ToolRepository.Repositories.Interface;

namespace Siger.Middlelayer.ToolRepository.Repositories
{
    internal class SigerToolSendMessagetypeRepository : ApiToolRepositoryBase<SigerToolSendMessageType>
        , ISigerToolSendMessagetypeRepository
    {
        ApiToolDbContext apiToolDbContext;
        public SigerToolSendMessagetypeRepository(ApiToolDbContext context) : base(context)
        {
            apiToolDbContext = context;
        }

        /// <summary>
        /// 获取报警通讯详情
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="pid"></param>
        /// <param name="mid"></param>
        /// <param name="spindle"></param>
        /// <param name="tn"></param>
        /// <param name="pn"></param>
        /// <returns></returns>
        public SigerToolSendMessageType GetAlertSettingCommunicationDetail(int cid,int pid, int mid, string spindle, string tn, string pn)
        {
            var entity = Get(f => f.projectid == pid && f.mid == mid && f.spindle == spindle && f.tn == tn && f.pn == pn);
            if (entity == null)
                throw new BadRequestException(CommonEnum.NoData);
            return entity;
        }

        public List<CommunicationList> GetCommunicationList(int? sectionId, int ProjectID, int page, int pagesize, out int totalCount)
        {
            //var machineIDs = new List<int>();
            ////设备必选
            //machineIDs = GetMachineId((int)sectionId, ProjectID).Select(f => f.MachineId).ToList();

            ////获取设备信息
            //var machineInfo = apiToolDbContext.siger_project_machine.Where(f => machineIDs.Contains(f.id) && f.projectid == ProjectID && f.status == (int)RowState.Valid);
            ////所有主轴信息
            //var spindleInfo = apiToolDbContext.siger_project_tool_spindle_true.Where(f =>
            //     f.status == (int)RowState.Valid && machineIDs.Contains(f.equipid));
            //var spindleIDs = spindleInfo.Select(f => f.id);
            ////所有刀具信息
            //var toolInfo = apiToolDbContext.siger_project_tool_cutter_location_true.Where(f =>
            //      f.status == (int)RowState.Valid && spindleIDs.Contains(f.spindleid) && f.is_processing_program != (int)ProcessProgram.NoConfig);

         
            var machineIDs = GetMachineIds((int)sectionId, ProjectID);
            var query = from m in apiToolDbContext.siger_project_machine
                        join sp in apiToolDbContext.siger_project_tool_spindle_true on m.id equals sp.equipid
                        join tl in apiToolDbContext.siger_project_tool_cutter_location_true on sp.id equals tl.spindleid
                        where machineIDs.Contains(m.id) && m.status == (int)RowState.Valid && sp.status==(int)RowState.Valid && tl.status==(int)RowState.Valid
                        &&  tl.is_processing_program !=(int)ProcessProgram.NoConfig
                        select new ToolLocaltionTrue {
                            MachineName=m.title,
                            MachieCode=m.code,
                             MachineId=m.id,
                             SpindleId=sp.id,
                             SpindleName=sp.name,
                             ToolName=tl.name,
                             program=tl.is_processing_program==(int)ProcessProgram.MainProgram?tl.programno:tl.subprogramno,
                             IsProcessProgram=tl.is_processing_program,
                            // ToolId=tl.id

                        };

            var grpData = query.Where(f => !string.IsNullOrEmpty(f.program))
                .GroupBy(x => new { x.MachineName, x.MachieCode, x.MachineId, x.SpindleId, x.SpindleName, x.ToolName, x.program, x.IsProcessProgram })
                .Select(s=>new ToolLocaltionTrue {
                    MachineName =s.Key.MachineName,
                    MachieCode=s.Key.MachieCode,
                    MachineId=s.Key.MachineId,
                    SpindleId=s.Key.SpindleId,
                    SpindleName=s.Key.SpindleName,
                    ToolName=s.Key.ToolName,
                    program=s.Key.program,
                    IsProcessProgram=s.Key.IsProcessProgram
                });
            totalCount = grpData.Count();
            var toolInfo= grpData.OrderBy(o=>o.MachineId).ThenBy(o=>o.SpindleId).ThenBy(o=>o.program).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            //获取报警配置所有数据
            var configInfo = apiToolDbContext.siger_tool_send_message_type.Where(f => f.status == (int)RowState.Valid &&
             f.projectid == ProjectID);
            var data = new List<CommunicationList>();
            foreach (var item in toolInfo)
            {
                //获取此刀具对应的设备、主轴信息
                //var spindleData = spindleInfo.FirstOrDefault(f => f.id == item.spindleid);
                //if (spindleData == null)
                //{
                //    continue;
                //}
                //var machineData = machineInfo.FirstOrDefault(f => f.id == spindleData.equipid);
                //if (machineData == null)
                //{
                //    continue;
                //}

                //拼接报警配置信息
                //var configData = configInfo.FirstOrDefault(f=>f.mid==spindleData.equipid&&f.spindle== spindleData.name&&
                //    f.tn== item.name&&f.pn== item.programno&&f.projectid==ProjectID&&f.status==(int)RowState.Valid);
                var configData = configInfo.FirstOrDefault(f => f.mid == item.MachineId && f.spindle == item.SpindleName &&
                  f.tn == item.ToolName && f.pn == item.program && f.projectid == ProjectID && f.status == (int)RowState.Valid);
                CommunicationList finalData;
                if (configData == null)
                {
                    finalData = new CommunicationList();
                    finalData.value = "";
                    apiToolDbContext.siger_tool_send_message_type.Add(new SigerToolSendMessageType {
                        mid= item.MachineId,
                        spindle= item.SpindleName,
                        tn= item.ToolName,
                        pn= item.program,
                        projectid= ProjectID,
                        status= (int)RowState.Valid,
                        value= "11111,11111,00000,00000"
                    });
                    apiToolDbContext.SaveChanges();
                    finalData.lamp = 1;
                    finalData.alarmDialog = 1;


                }
                else
                {
                    finalData = Mapper<SigerToolSendMessageType, CommunicationList>.Map(configData);
                    var controlItem = configData.value.Split(',');
                    if(controlItem.Count()!=4)
                    {
                        continue;
                    }
                    else
                    {
                        if(controlItem[0].Contains('1'))
                        {
                            finalData.lamp = 1;
                        }
                        if (controlItem[1].Contains('1'))
                        {
                            finalData.alarmDialog = 1;
                        }
                        if (controlItem[2].Contains('1'))
                        {
                            finalData.pmcControl = 1;
                        }
                    }
                }
                finalData.mid = item.MachineId;
                finalData.machineCode = item.MachieCode;
                finalData.machineName = item.MachineName;
                finalData.spindleName = item.SpindleName;
                finalData.spindleid = item.SpindleId;
                finalData.pn = item.program;
                finalData.tn = item.ToolName;
                data.Add(finalData);
            }
            //totalCount = data.Count;
            //data = data.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            return data;
        }
        public void AlertSettingCommunicationEdit(int companyId,int projectId, int mid, int spindle, string tn, string pn, string value)
        {
            //检查数据是否存在
            var data=apiToolDbContext.siger_tool_send_message_type.FirstOrDefault(f=>f.mid== mid &&f.spindle==spindle.ToString()&&f.tn==tn&&f.pn==pn&& f.projectid==projectId&&f.status==(int)RowState.Valid);
            if(data!=null)
            {
                //修改
                data.value = value;
                data.status = (int)RowState.Valid;
                apiToolDbContext.siger_tool_send_message_type.Update(data);
            }
            else
            {
                //新增
                apiToolDbContext.siger_tool_send_message_type.Add(new SigerToolSendMessageType
                {
                    mid=mid,
                    spindle=spindle.ToString(),
                    tn=tn,
                    pn=pn,
                    value=value,
                    projectid=projectId,
                    status=(int)RowState.Valid
                });
            }
            try
            {
                if (apiToolDbContext.SaveChanges() <= 0)
                    throw new BadRequestException(CommonEnum.SystemExcetion);
            }
            catch (Exception)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
    }
}