using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.ApiNingxiaShared.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Redis.Model;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Common.Log;
using Siger.ApiNingxiaShared.Response;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.WmsRepository.Repositories.Interface;
using Siger.Middlelayer.Common.FieldEnum;
using System.Net.Http;
using Newtonsoft.Json;
using System;
using System.Security.Policy;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.TlmRepository.Entities;
using System.IO;

namespace Siger.ApiNingxiaShared.Controllers
{
    public class ToolUnitController : BaseController
    {
        IUnitOfWork _unitOfWork;
        private readonly IToolLifeToolInstallRepository _toolInstallRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly Isiger_wms_stockRepository _stockRepository;
        private readonly IToolLifeToolRepository _toolRepository;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ISigerProjectProductRepository _productRepository;
        private readonly ISigerProjectUserRepository _userRepository;
        private readonly IProductRouteRepository _productRouteRepository;
        private readonly IToolLifeTechnologyRepository _toolLifeTechnologyRepository;
        private readonly IToolLifeToolTechRepository _toolLifeToolTechRepository;
        private int ProjectId = 160;

        public ToolUnitController(IUnitOfWork unitOfWork, IToolLifeToolInstallRepository toolInstallRepository, ISigerProjectMachineRepository machineRepository, Isiger_wms_stockRepository stockRepository
            , IToolLifeToolRepository toolRepository, IHttpClientFactory httpClientFactory, ISigerProjectProductRepository productRepository, ISigerProjectUserRepository userRepository
            , IProductRouteRepository productRouteRepository, IToolLifeTechnologyRepository toolLifeTechnologyRepository, IToolLifeToolTechRepository toolLifeToolTechRepository)
        {
            _unitOfWork = unitOfWork;
            _toolInstallRepository = toolInstallRepository;
            _machineRepository = machineRepository;
            _stockRepository = stockRepository;
            _toolRepository = toolRepository;
            _httpClientFactory = httpClientFactory;
            _productRepository = productRepository;
            _userRepository = userRepository;
            _productRouteRepository = productRouteRepository;
            _toolLifeTechnologyRepository = toolLifeTechnologyRepository;
            _toolLifeToolTechRepository = toolLifeToolTechRepository;
        }
        /// <summary>
        /// 刀具装刀查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [NoTokenValidateFilter]
        [HttpPost]
        public IActionResult GetToolInstallData([FromBody]RequestGetToolInstallData request)
        {
            var machineCode = _machineRepository.Get(f => f.id == request.machine_id)?.code ?? "";
            if (string.IsNullOrEmpty(machineCode))
            {
                Logger.WriteLineError($"GetToolInstallData -> {request.machine_id} MachineNotExist");
                throw new BadRequestException(RequestEnum.MachineNotExist);
            }
            var data = _toolInstallRepository.GetPagedList(new List<string> { machineCode }, request.tool_location, 0, 0, ProjectId, 0, request.loadtime).Data;

            if (data.Any())
            {
                var ret = new List<ResponseGetToolInstallData>();
                foreach (var item in data)
                {
                    ret.Add(new ResponseGetToolInstallData
                    {
                        loadtime = item.install_time,
                        load_user = item.install_user,
                        machine_id = request.machine_id,
                        tool_life = item.tool_life,
                        tool_location = item.cutter_number,
                        tool_number = item.tool_number,
                        tool_name = item.tool_name,
                        tool_type = item.tool_type == 0 ? "" : EnumHelper.GetEnumDesc((TlmSettingCategory)item.tool_type)
                    });
                }
                return new ObjectResult(ret);
            }
            throw new BadRequestException(CommonEnum.NoData);
        }

        /// <summary>
        /// 刀具实时库存查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [NoTokenValidateFilter]
        [HttpPost]
        public IActionResult GetToolStockData([FromBody]RequestGetToolStockData request)
        {
            var result = _stockRepository.GetList(0, "", ProjectId, 0, "", 0);
            if (result.Any())
            {
                var material = result.Select(s => s.material_name).Distinct();
                var ret = new List<ResponseGetToolStockData>();
                foreach (var item in material)
                {
                    ret.Add(new ResponseGetToolStockData
                    {
                        warehouse_qty = result.Sum(s => s.quantity),
                        tool_name = item,
                        warehouse_min = result.First(f => f.material_name == item).warehouse_min,
                        tool_number = result.First(f => f.material_name == item).tool_number,
                        tool_type = result.First(f => f.material_name == item).tool_type == 0 ? "" : EnumHelper.GetEnumDesc((TlmSettingCategory)result.First(f => f.material_name == item).tool_type)
                    });
                }
                if (!string.IsNullOrEmpty(request.tool_number))
                {
                    ret = ret.Where(f => f.tool_number == request.tool_number).ToList();
                }
                return new ObjectResult(ret);
            }
            throw new BadRequestException(CommonEnum.NoData);
        }

        [NoTokenValidateFilter]
        [HttpGet]
        public IActionResult AsynToolData(int get_type = 2)
        {
            var content = GetBaseProductData(get_type);
            try
            {
                var response = JsonConvert.DeserializeObject<RequestAsynToolModel>(content);
                if (response.success)
                {
                    var model = JsonConvert.DeserializeObject<List<RequestAsynToolData>>(response.aaData.ToString());
                    InsertBaseProductData(model, ProjectId);
                }
                else
                {
                    Logger.WriteLineError($"AsynToolData Failed {content}");
                    throw new BadRequestException(CommonEnum.Fail);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLineError($"AsynToolData Failed original is \r\n{content} \r\n error:{ex.Message}");
                throw new BadRequestException(CommonEnum.Fail);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        private void InsertBaseProductData(List<RequestAsynToolData> list, int projectId)
        {
            var now = UnixTimeHelper.GetNow();
            var userId = _userRepository.GetProjectManager(projectId)?.mid ?? 0;
            foreach (var item in list)
            {
                //product
                var product = _productRepository.Get(f => f.projectid == projectId && f.name == item.product_name && f.code == item.product_code && f.status != 0);
                if (product == null)
                {
                    product = new siger_project_product
                    {
                        code = item.product_code,
                        createtime = now,
                        drawingcode = item.product_code,//图纸号
                        creatorid = userId,
                        image = string.Empty,
                        remark = string.Empty,
                        name = item.product_name,
                        projectid = projectId,
                    };
                    product = _productRepository.InsertSigerProjectProductModel(product);
                    if (product.id <= 0)
                    {
                        Logger.WriteLineError($"InsertBaseProductData：insert product{item.product_code}插入失败！");
                        throw new BadRequestException(CommonEnum.Fail);
                    }
                }
                var productId = product.id;
                //route
                var route = _productRouteRepository.Get(f => f.projectId == projectId && f.status != 0 && f.productId == productId && f.name == item.product_order);
                if (route == null)
                {
                    var temp = _productRouteRepository.GetList(f => f.projectId == projectId && f.status != 0 && f.productId == productId).ToList();
                    var serialNumber = temp.Any() ? temp.Max(m => m.serialNumber) + 1 : 1;
                    route = new siger_project_product_route
                    {
                        addTime = UnixTimeHelper.ConvertStringDateTime(now.ToString()),
                        create_usermid = userId,
                        description = "接口插入信息：" + item.product_order,
                        name = item.product_order,
                        machine_type = item.machine_id,
                        prepare = 1,
                        working_hours = 1,
                        levelId = 0,
                        sectionId = 0,
                        productId = productId,
                        projectId = projectId,
                        route_code = string.Empty,
                        serialNumber = serialNumber,
                    };
                    route = _productRouteRepository.InsertProductRouteModel(route);
                    if (route.id <= 0)
                    {
                        Logger.WriteLineError($"InsertBaseProductData：insert route {item.product_code}插入失败！");
                        throw new BadRequestException(CommonEnum.Fail);
                    }
                }
                var routeId = route.id;
                //technology
                var technology = _toolLifeTechnologyRepository.Get(f => f.project_id == projectId && f.status != 0 && f.product_id == productId && f.route_id == routeId);
                if (technology == null)
                {
                    technology = new siger_project_toollife_technology
                    {
                        product_id = productId,
                        project_id = projectId,
                        create_id = userId,
                        create_time = UnixTimeHelper.ConvertStringDateTime(now.ToString()),
                        drawcode = product.drawingcode,
                        machine_type = item.machine_id,
                        remark = "接口插入信息：" + item.product_order + item.product_order,
                        program = string.Empty,
                        route_id = routeId,
                    };
                    _toolLifeTechnologyRepository.Insert(technology);
                    if (_unitOfWork.Commit() <= 0)
                    {
                        Logger.WriteLineError($"InsertBaseProductData：insert technology {item.product_code}插入失败！");
                        throw new BadRequestException(CommonEnum.Fail);
                    }
                }
                var technologyId = technology.id;
                var toolModel = _toolRepository.Get(f => f.project_id == projectId && f.status != 0 && f.number == item.tool_number);
                _toolLifeToolTechRepository.Insert(new siger_project_toollife_tech_tool
                {
                    technology_id = technologyId,
                    remark = "接口插入信息：" + item.product_order + item.product_order,
                    project_id = projectId,
                    cutter_number = item.tool_location,
                    down_length = string.Empty,
                    down_tolerance = string.Empty,
                    flute_count = 0,
                    flute_length = 0,
                    reach_length = string.Empty,
                    upper_tolerance = string.Empty,
                    tool_model = 0,
                    tool_code = item.tool_number,
                    handle_model = 0,
                    part_no = toolModel?.part_no ?? "",
                    quantity = item.tool_qty,
                    rated_life = string.Empty,
                    material_id = toolModel?.material_id ?? 0,
                });
                if (_unitOfWork.Commit() <= 0)
                {
                    Logger.WriteLineError($"InsertBaseProductData：insert ToolTech {item.product_code}插入失败！");
                    throw new BadRequestException(CommonEnum.Fail);
                }
            }

        }

        private string GetBaseProductData(int get_type)
        {
            try
            {
                var client = _httpClientFactory.CreateClient();
                using (var request = new HttpRequestMessage(HttpMethod.Post, @"http://119.3.12.32:8080/api/process/getDetailInfoList.do"))
                {
                    var requestContent = new MultipartFormDataContent();
                    requestContent.Add(new StringContent(get_type.ToString()), "getType");
                    request.Content = requestContent;
                    var result = client.SendAsync(request);
                    var content = result.Result.Content.ReadAsStringAsync().Result;
                    return content;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLineError($"GetBaseProductData Failed:{ ex.Message}");
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
    }
}