using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using TEAMModelOS.SDK.Models.Service;
using TEAMModelOS.Services.Common;

namespace TEAMModelOS.Controllers
{
    [Route("data-migration")]
    [ApiController]
    public class DataMigrationController : ControllerBase
    {
        ///Teacher表
        ///     
        ///     复制的数据  
        ///     Base  ==>>Student   //IES5&教研中心
        ///     迁移的数据   StuCourse  ==>> Student  //IES5
        ///                  Activity   ==>> Student  //IES5
        ///                  
      
        private readonly AzureStorageFactory _azureStorage;
        private readonly AzureRedisFactory _azureRedis;
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;
        public DataMigrationController(AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing)
        {
            _azureCosmos = azureCosmos;
            _azureRedis = azureRedis;
            _azureStorage = azureStorage;
            _dingDing = dingDing;
        }
        /// <summary>
        /// 迁移教师基础信息，并处理历史数据。
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher")]
        [HttpGet("restore-tmd-course&activity")]
        public async Task<IActionResult> RestoreTmdCourseAndActivity()
        {
            var client = _azureCosmos.GetCosmosClient();
            List<StuActivity> activities = new List<StuActivity>();
            List<StuCourse> stuCourses = new List<StuCourse>();
            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<StuActivity>(queryText: "select value(c) from c where c.pk='Activity'"))
            {
                await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync<StuActivity>(item, partitionKey: new PartitionKey(item.code));
                activities.Add(item);
            }
            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<StuCourse>(queryText: "select value(c) from c where c.pk='StuCourse'"))
            {
                await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync<StuCourse>(item, partitionKey: new PartitionKey(item.code));
                stuCourses.Add(item);
            }
            return Ok(new { activities, stuCourses });
        }

        /// <summary>
        /// 迁移教师基础信息，并处理历史数据。
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher")]
        [HttpGet("restore-tmduser")]
        public async Task<IActionResult> RestoreTmdUser()
        {
            var client = _azureCosmos.GetCosmosClient();
            List<TmdUser> users = new List<TmdUser>();
            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
            {
                ///修复历史数据
                if (item.size > 0)
                {
                    if (item.pk == null)
                    {
                        item.pk = "Teacher";
                        await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(item, item.id, partitionKey: new PartitionKey("Base"));
                    }
                    try
                    {
                        TmdUser user = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(item.id, partitionKey: new PartitionKey("Base"));
                        item.schools.ForEach(x => {
                            if (user.schools.Find(y => y.schoolId.Equals(x.schoolId)) == null)
                            {
                                user.schools.Add(new TmdUser.School { name = x.name, schoolId = x.schoolId, time = x.time, status = x.status });
                            }
                        });
                        users.Add(user);
                        await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(user, user.id, partitionKey: new PartitionKey("Base"));
                    }
                    catch (CosmosException ex)
                    {
                        if (ex.Status == 404)
                        {
                            TmdUser user = item.ToJsonString().ToObject<TmdUser>();
                            await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(user, partitionKey: new PartitionKey("Base"));
                            users.Add(user);
                        }
                    }
                }
                else
                {
                    await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemAsync<Teacher>(item.id, partitionKey: new PartitionKey("Base"));
                }
            }
            return Ok(new { users });
        }
    }
}
