using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoTurnOver.Common;
using AutoTurnOver.Models;
using AutoTurnOver.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace AutoTurnOver.Controllers
{
    /// <summary>
    /// 子母sku
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MotherSkuController : Controller
    {

        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【子母sku】->【搜索】页面", 0)]
        public JsonResult Page([FromQuery]dc_base_mother_sku_search_dto search, [FromQuery]int limit, [FromQuery]int offset)
        {

            var total = 0;
            var service = new Services.MotherSkuServices();
            var list = service.Page(search, offset, limit, ref total);

            return new JsonResult(new
            {
                rows = list,
                total = total,
            });
        }


        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【子母sku 日志】->【搜索】页面", 0)]
        public JsonResult LogPage([FromQuery]dc_base_mother_sku_log_search_dto search, [FromQuery]int limit, [FromQuery]int offset)
        {

            var total = 0;
            var service = new Services.MotherSkuServices();
            var list = service.LogPage(search, offset, limit, ref total);

            return new JsonResult(new
            {
                rows = list,
                total = total,
            });
        }

        
        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【配置】->【子母sku 日志】->【搜索】页面", 0)]
        public JsonResult SearchSku([FromQuery]string name)
        {

            var service = new Services.MotherSkuServices();
            var list = service.SearchSku(name);

            return new JsonResult(list.Select(s=>new { id = s.id,text=$"【{s.sku}】【{s.warehouse_code}】【{s.warehouse_name}】"}));
        }


        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【子母sku】->【新增规则】->【保存】操作", 1)]
        public JsonResult Save([FromBody]dc_base_mother_sku m)
        {
            try
            {
                var user = AutoUtility.GetUser();
                new Services.MotherSkuServices().Save(m, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }
        
        }
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【子母sku】->【修改状态】->【保存】操作", 1)]
        public JsonResult UpdateStatus([FromBody]update_status_input_dto m)
        {
            try
            {
                var user = AutoUtility.GetUser();
                new Services.MotherSkuServices().UpdateStatus(m, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }
           
        }
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【配置】->【子母sku】->【移除子sku】->【保存】操作", 1)]
        public JsonResult RemoveMap([FromBody]remove_map_input_dto m)
        {
            try
            {
                var user = AutoUtility.GetUser();
                new Services.MotherSkuServices().RemoveMap(m, user);
                return new JsonResult(new { success =true});
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false,message = ex.Message });
            }
           
        }
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动周转列表】->【设置母sku】->【保存】操作", 1)]
        public JsonResult SetMainMap([FromBody]remove_map_input_dto m)
        {
            try
            {
                var user = AutoUtility.GetUser();
                new Services.MotherSkuServices().SetMainMap(m, user);
                return new JsonResult(new { success =true});
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false,message = ex.Message });
            }
           
        }
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动周转列表】->【设置母sku】->【保存】操作", 1)]
        public JsonResult BatchSet([FromBody]batch_set_input_dto m)
        {
            try
            {
                var user = AutoUtility.GetUser();
                new Services.MotherSkuServices().BatchSet(m, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }
          
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【子母sku设置】->【导入】操作", 1)]
        public async Task<ActionResult<RequestResultDto>> Import(IFormFile file)
        {
            try
            {
                var user = AutoUtility.GetUser();
                var dataTable = new Services.MotherSkuServices().Import(file.OpenReadStream(), user);

                var fileName = AppContext.BaseDirectory + $@"Result\子母导入结果.csv";

                CsvFileHelper.SaveCSV(dataTable, fileName);

                var memory = new MemoryStream();
                using (var stream = new FileStream(fileName, FileMode.Open))
                {
                    stream.CopyTo(memory);
                }
                memory.Position = 0;

                var fileData = await QiNiuCloudHelper.UploadAsync(memory, $"{user.UserName}-{DateTime.Now.ToString("yyyyMMddHHmmss")}子母导入结果.csv");
                return new RequestResultDto { success = true, data = fileData };
            }
            catch (Exception ex)
            {
                return new RequestResultDto { success = false, message = ex.Message, err_data = ex.StackTrace };
            }

        }
    }
}