using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common.Extensions;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Request;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Repository.Repositories.Interface;
using System.IO;

namespace Siger.ApiACC.Controllers
{

    public class PrintRelationController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerPrinterLebleFile _printerLebleFile;
        private readonly ISigerPrinterRelationRepository _printerRelation;
        private readonly ISnListRepository _snListRepository;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSectionRepository;

        public PrintRelationController(ISigerPrinterLebleFile sigerPrinterLebleFile, ISigerPrinterRelationRepository sigerPrinterRelationRepository,
            IUnitOfWork unitOfWork, ISnListRepository snListRepository,ISigerProjectLevelSectionRepository sigerProjectLevelSectionRepository)
        {
            _printerLebleFile = sigerPrinterLebleFile;
            _printerRelation = sigerPrinterRelationRepository;
            _unitOfWork = unitOfWork;
            _snListRepository = snListRepository;
            _sigerProjectLevelSectionRepository = sigerProjectLevelSectionRepository;
        }

        /// <summary>
        /// 解析txt文件
        /// </summary>
        /// <param name="labletype">模板类型</param>
        /// <param name="printtype">打印类型</param>
        /// <param name="productcode">产品信息</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTxtParameters(string labletype, int printtype, string productcode)
        {
            var data = _printerLebleFile.GetFileUrl(labletype, printtype, productcode, ProjectId).FirstOrDefault();
            if (data == null)
            {
                throw new BadRequestException(RequestEnum.File_urlNotNull);
            }
            if (string.IsNullOrEmpty(data.file_url))
            {
                throw new BadRequestException(RequestEnum.File_urlNotNull);
            }
            if(!data.file_url.EndsWith(".txt"))
            {
                throw new BadRequestException(RequestEnum.OnlyTxtFile);
            }
            var fileSetting = Config<FileSettings>.Get();
            if (fileSetting == null)
            {
                throw new BadRequestException(CommonEnum.GetCommCfgFailed);
            }

            var truePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, data.file_url).Replace("Files", "TemporaryFiles");

            if (!System.IO.File.Exists(truePath))
            {
                Logger.WriteLineError($"program getContent from:{truePath} failed");
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }
            var txtfile = FileHelper.ReadFile(truePath);

            var response = new List<ResponsePrintparameters>();
            var parameters = new List<string>();
            var reg = new Regex(@"<(.+?)>");

            foreach (Match item in reg.Matches(txtfile))
            {
                parameters.Add(item.Groups[1].Value.Trim());
            }

            response.Add(new ResponsePrintparameters
            {
                file_url = data.file_url,
                fileid = data.fileid,
                filename = data.filename,
                image = data.image,
                txtparameters = parameters
            });

            return new ObjectResult(response);
        }
        /// <summary>
        /// 根据table获取 cloums
        /// </summary>
        /// <param name="fileid"></param>
        /// <param name="parameter"></param>
        /// <param name="tableid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTableField(int fileid, string parameter, int tableid)
        {
            var response = new ResponsePrintlableParam
            {
                FileId = fileid
            };
            switch (tableid)
            {
                case (int)PrintLabeTable.SNList:
                    {
                        response.TableName = (int)PrintLabeTable.SNList;
                        var colums =ClassHelper.GetPropertyInfoArray<SigerTrSnList>();
                        foreach (var col in colums)
                        {
                           // if (_printerRelation.IsExist(f => f.fileid == fileid && f.table_name == (int)PrintLabeTable.SNList && f.table_parameters == col.Name && f.txt_parameters == parameter && f.status == (int)RowState.Valid))
                            if (_printerRelation.IsExist(f =>f.fileid==fileid && f.table_name == (int)PrintLabeTable.SNList && f.table_parameters== col.Name && f.txt_parameters == parameter && f.status == (int)RowState.Valid))
                            {//已维护
                                response.Columns.Add(SetObj(col.Name, 1));
                            }
                            else
                            {//未维护
                                response.Columns.Add(SetObj(col.Name, 0));
                            }
                        }
                        break;
                    }
                case (int)PrintLabeTable.PackBoxlist:
                    {
                        response.TableName = (int)PrintLabeTable.PackBoxlist;
                        var colums = ClassHelper.GetPropertyInfoArray<SigerTrPackBoxList>();
                        foreach (var col in colums)
                        {
                            if (_printerRelation.IsExist(f => f.fileid == fileid && f.table_name == (int)PrintLabeTable.PackBoxlist && f.table_parameters == col.Name && f.txt_parameters == parameter  && f.status == (int)RowState.Valid))
                            {//已维护
                                response.Columns.Add(SetObj(col.Name,1));
                            }
                            else
                            {//未维护
                                response.Columns.Add(SetObj(col.Name, 0));
                            }
                        }
                        break;
                    }
                default:
                    break;
            }
            return new ObjectResult(response);
        }
        /// <summary>
        /// 根据txt params 获取 table cloums
        /// </summary>
        /// <param name="fileid"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTableFieldByParam(int fileid,string parameter)
        {
            var response = new ResponsePrintlableParam
            {//默认第一个
                TableName= (int)PrintLabeTable.SNList,
                FileId=fileid,
            };
            var data = _printerRelation.GetList(f => f.projectId == ProjectId && f.fileid==fileid &&  f.txt_parameters == parameter);
           
            if(!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var tblname = data.FirstOrDefault().table_name;
            response.TableName = tblname;
            if (tblname== (int)PrintLabeTable.SNList)
            {
                var colums = ClassHelper.GetPropertyInfoArray<SigerTrSnList>();
                foreach (var col in colums)
                {
                    if (_printerRelation.IsExist(f => f.fileid == fileid && f.table_name == (int)PrintLabeTable.SNList && f.table_parameters == col.Name && f.txt_parameters == parameter && f.status == (int)RowState.Valid))
                    {//已维护
                        response.Columns.Add(SetObj(col.Name, 1));
                    }
                    else
                    {//未维护
                        response.Columns.Add(SetObj(col.Name, 0));
                    }
                }
            }
            else if (tblname == (int)PrintLabeTable.PackBoxlist)
            {
                var colums = ClassHelper.GetPropertyInfoArray<SigerTrPackBoxList>();
                foreach (var col in colums)
                {
                    if (_printerRelation.IsExist(f => f.fileid == fileid && f.table_name == (int)PrintLabeTable.PackBoxlist && f.table_parameters == col.Name && f.txt_parameters == parameter && f.status == (int)RowState.Valid))
                    {//已维护
                        response.Columns.Add(SetObj(col.Name, 1));
                    }
                    else
                    {//未维护
                        response.Columns.Add(SetObj(col.Name, 0));
                    }
                }
            }
            return new ObjectResult(response);

        }
        ResponsePrintlableColumn SetObj(string name,int set)
        {
            return new ResponsePrintlableColumn
            {
                 Name=name,
                 Set=set
            };
        }

        [HttpPost]
        public IActionResult Add([FromBody] RequestPrinterRelation req)
        {
            var check = _printerRelation.Get(t => t.fileid == req.fileid && t.txt_parameters==req.txt_parameters && t.status == (int)RowState.Valid && t.projectId == ProjectId);
            if (check != null)
            {
                check.txt_parameters = req.txt_parameters;
                check.table_name = req.table_name;
                check.table_parameters = req.table_parameters;
                _printerRelation.Update(check);
            }
            else
            {
                _printerRelation.Insert(new SigerTrPrinterRelation
                {
                    projectId = ProjectId,
                    fileid = req.fileid,
                    txt_parameters = req.txt_parameters,
                    table_name = req.table_name,
                    table_parameters = req.table_parameters
                });
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 铭牌标签打印
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PrintLable([FromBody] RequestPrintLableFile req)
        {
            var data = _printerLebleFile.GetLabelRelation(req.labletype, req.printtype, req.productcode, ProjectId);
            if (!data.Any())
            {
                throw new BadRequestException(RequestEnum.LableNotMaintain);
            }

            var fileUrl = data.FirstOrDefault();
            var fileSetting = Config<FileSettings>.Get();
            if (fileSetting == null)
            {
                throw new BadRequestException(CommonEnum.GetCommCfgFailed);
            }
            var truePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileUrl.fileurl).Replace("Files", "TemporaryFiles");
            if (!System.IO.File.Exists(truePath))
            {
                Logger.WriteLineError($"program getContent from:{truePath} failed");
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }

            var txtList = new List<string>();
            var response = new List<ResponsePrintparameters>();

            var reg = new Regex(@"<(.+?)>");
            foreach (var snInfo in req.sngroup)
            {
                var txtfile = FileHelper.ReadFile(truePath);
                var snList = _snListRepository.Get(s => s.SN == snInfo.sn && s.status == (int)RowState.Valid && s.projectId == ProjectId);
                if (snList == null)
                {
                    throw new BadRequestException(AccEnum.Busi_SN_Null);
                }

                snList.printCount += 1;
                _snListRepository.Update(snList);
                if (_unitOfWork.Commit() <= 0)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }

                foreach (var item in data)
                {
                    if (item.tablename == (int)PrintLabeTable.SNList)
                    {
                        foreach (Match match in reg.Matches(txtfile))
                        {
                            var actVal = match.Groups[1].Value.Trim();
                            var repChar = $"{'<'}{actVal}{'>'}";
                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.SN) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.SN);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.ProductId) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.ProductId.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.ProductCode) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.ProductCode);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.Line) && item.txtparamter == actVal)
                            {
                                var lineName = _sigerProjectLevelSectionRepository.Get(s => s.id == snList.Line && s.status == (int)RowState.Valid);
                                if (lineName == null)
                                {
                                    throw new BadRequestException(AccEnum.LevelInvalid);
                                }
                                txtfile = txtfile.Replace(repChar, lineName.title);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.WoType) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.WoType);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.WO) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.WO);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.MaterialId) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.MaterialId.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.PN) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.PN);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.ResultStatus) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.ResultStatus);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.InputDateTime) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.InputDateTime.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.TransDateTime) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.TransDateTime.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.printCount) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.printCount.ToStr());
                            }
                        }
                    }
                }
                txtList.Add(txtfile);
            }
            return new ObjectResult(txtList);
        }

        /// <summary>
        /// 证书标签打印
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PrintCertificateLable([FromBody] RequestPrintLableFiles req)
        {
            var txtList = new List<string>();
            var response = new List<ResponsePrintparameters>();
            foreach (var items in req.ModelList)
            {
                var data = _printerLebleFile.GetLabelRelation(items.labletype, items.printtype, req.productcode, ProjectId);
                if (!data.Any())
                {
                    throw new BadRequestException(RequestEnum.LableNotMaintain);
                }

                var fileUrl = data.FirstOrDefault();
                var fileSetting = Config<FileSettings>.Get();
                if (fileSetting == null)
                {
                    throw new BadRequestException(CommonEnum.GetCommCfgFailed);
                }
                var truePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileUrl.fileurl).Replace("Files", "TemporaryFiles");
                if (!System.IO.File.Exists(truePath))
                {
                    Logger.WriteLineError($"program getContent from:{truePath} failed");
                    throw new BadRequestException(RequestEnum.ErrorFilePath);
                }

                var reg = new Regex(@"<(.+?)>");

                var txtfile = FileHelper.ReadFile(truePath);
                var snList = _snListRepository.Get(s => s.SN == req.sn && s.status == (int)RowState.Valid && s.projectId == ProjectId);
                if (snList == null)
                {
                    throw new BadRequestException(AccEnum.Busi_SN_Null);
                }

                snList.printCount += 1;
                _snListRepository.Update(snList);
                if (_unitOfWork.Commit() <= 0)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }

                foreach (var item in data)
                {
                    if (item.tablename == (int)PrintLabeTable.SNList)
                    {
                        foreach (Match match in reg.Matches(txtfile))
                        {
                            var actVal = match.Groups[1].Value.Trim();
                            var repChar = $"{'<'}{actVal}{'>'}";
                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.SN) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.SN);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.ProductId) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.ProductId.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.ProductCode) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.ProductCode);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.Line) && item.txtparamter == actVal)
                            {
                                var lineName = _sigerProjectLevelSectionRepository.Get(s => s.id == snList.Line && s.status == (int)RowState.Valid);
                                if (lineName == null)
                                {
                                    throw new BadRequestException(AccEnum.LevelInvalid);
                                }
                                txtfile = txtfile.Replace(repChar, lineName.title);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.WoType) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.WoType);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.WO) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.WO);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.MaterialId) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.MaterialId.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.PN) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.PN);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.ResultStatus) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.ResultStatus);
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.InputDateTime) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.InputDateTime.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.TransDateTime) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.TransDateTime.ToStr());
                            }

                            if (item.tableparamter == EnumHelper.GetEnumDesc(SnList.printCount) && item.txtparamter == actVal)
                            {
                                txtfile = txtfile.Replace(repChar, snList.printCount.ToStr());
                            }
                        }
                    }
                }
                txtList.Add(txtfile);
            }
            return new ObjectResult(txtList);
        }
    }
}
