using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.MediaCente
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MediaCenteController : BaseController
    {
        private readonly ISys_AreaRepository _sys_areaRepository;
        private readonly ISys_MediaCenteRepository  _sys_mediacenter_Repository;
        private readonly ISys_PlanManagemenRepository _sys_planmanagemenRepository;
        private readonly ISys_DictionaryValueRepository _sys_dictionaryRepository;
        private readonly ISys_MediaManagementRepository _sys_mediaManagement_Repository;
        private readonly IBus_ProductRepository _productRepository;
        private readonly ISys_DepartmentRepository _sys_departmentRepository;
        private readonly ISMS_InternalMessagesReposytory _sys_internalMessagesrepository;
        private readonly ISys_UserAccountRepository _sys_useraccountRepository;
        public MediaCenteController(ISys_MediaCenteRepository sys_mediacenter_Repository, ISys_PlanManagemenRepository sys_planmanagemenRepository, ISys_UserAccountRepository sys_useraccountRepository,
            ISys_DictionaryValueRepository sys_dictionaryRepository, ISys_MediaManagementRepository sys_mediaManagement_Repository, IBus_ProductRepository productRepository, ISys_DepartmentRepository sys_departmentRepository,ISys_AreaRepository sys_areaRepository, ISMS_InternalMessagesReposytory sys_internalMessagesrepository
           )
        {
            _sys_mediacenter_Repository = sys_mediacenter_Repository;
            _sys_planmanagemenRepository = sys_planmanagemenRepository;
            _sys_dictionaryRepository = sys_dictionaryRepository;
            _sys_mediaManagement_Repository = sys_mediaManagement_Repository;
            _productRepository = productRepository;
            _sys_departmentRepository = sys_departmentRepository;
            _sys_areaRepository = sys_areaRepository;
            _sys_internalMessagesrepository = sys_internalMessagesrepository;
            _sys_useraccountRepository = sys_useraccountRepository;

        }
        /// <summary>
        /// 产品列表
        /// </summary>
        /// <param name="input">筛选字段</param>
        /// <returns></returns>
        [HttpPost("getlistproduct")]
        public async Task<IActionResult> GetListByPage()
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });
            #endregion
            var list = await _productRepository.GetListALL(conModels , " F_AddTime DESC");
            var row = list.Where((x, i) => list.FindIndex(z => z.F_ProductNumber  == x.F_ProductNumber&&z.F_ProductNumberName==x.F_ProductNumberName) == i);
            return Success("成功", row);
        }

        /// <summary>
        /// 添加媒体投放
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync([FromBody]MediaCenteInput input)
        {
            if (input.F_Type <= 0)
                return Error("请选择投放类型");
            if (input.F_Name <= 0)
                return Error("请选择媒体名称");
            if (input.F_PlayPlanList!=null )
            {
                if (input.F_PlayPlanList.Count > 0)
                {
                    foreach (var it in input.F_PlayPlanList)
                    {
                        if (it.F_Type < 0)
                            return Error("请选择计划类型");
                    }
                }
            }
          if (input.F_MediaChangeList!=null )
            {
                if (input.F_MediaChangeList.Count > 0)
                {
                    foreach (var it in input.F_MediaChangeList)
                    {
                        if (it.F_Type < 0)
                            return Error("请选择媒体变更类型");
                    }
                }
            }
            
          // string user = "8000";
         string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = new T_Sys_MediaCente();
            model =  Transformation(model, input, user, 0);
            model.F_State = 0;
            var res = await _sys_mediacenter_Repository.Add(model);
            if (res > 0)
            {
                if (input.F_IsRemind >0)
                {
                    try
                    {
                        DateTime time = DateTime.Parse(input.F_ReminderTime.ToString());
                        bool n = new InternalMessages.InternalMessagesController(_sys_internalMessagesrepository, _sys_useraccountRepository).AddInternalMessagesInfo(res, "媒体中心提醒", _sys_mediaManagement_Repository.GetSingle(x => x.F_ID == input.F_Name).Result.F_Name + "媒体提醒", user, time, 1, 1, int.Parse(input.F_DeptId.Split(',')[input.F_DeptId.Split(',').Length - 1]), "", 0);
                    }
                    catch
                    {

                    }
                  
                }
               
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }
        /// <summary>
        /// 修改媒体投放
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync([FromBody]MediaCenteInput input)
        {
            if (input.F_ID <= 0)
                return Error("请选择正确的媒体");
            if (input.F_Type <= 0)
                return Error("请选择投放类型");
            if (input.F_Name <= 0)
                return Error("请选择媒体名称");
            if (input.F_PlayPlanList!=null )
            {
                foreach (var it in input.F_PlayPlanList)
                {
                    if (it.F_Type < 0)
                        return Error("请选择计划类型");
                }
            }
           if (input.F_MediaChangeList!=null )
            {
                foreach (var it in input.F_MediaChangeList)
                {
                    if (it.F_Type < 0)
                        return Error("请选择媒体变更类型");
                }
            }
           // string user = "8000";
            string user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = await _sys_mediacenter_Repository.GetSingle(x => x.F_ID == input.F_ID);
            if (model == null)
                return Error("操作失败");
            model = Transformation(model, input, user, 1);
            var res = await _sys_mediacenter_Repository.Update (model);
            if (res)
            {
                var InternalMessages = _sys_internalMessagesrepository.GetListALL(x => x.F_ID == model.F_ID && x.SMS_IsDelete == 0).Result.FirstOrDefault();
                if (InternalMessages!=null )
                {
                    if (input.F_IsRemind > 0)
                    {
                        try
                        {
                            InternalMessages.SMS_Content = _sys_mediaManagement_Repository.GetSingle(x => x.F_ID == input.F_Name).Result.F_Name + "媒体提醒";
                            InternalMessages.SMS_Remindertime = input.F_ReminderTime;
                            InternalMessages.SMS_Deptid = int.Parse(input.F_DeptId.Split(',')[input.F_DeptId.Split(',').Length - 1]);
                            bool n = await _sys_internalMessagesrepository.Update(InternalMessages);
                        }
                        catch
                        {

                        }
                    }
                }
                else
                {
                    if (input.F_IsRemind > 0)
                    {
                        try
                        {
                            bool n = new InternalMessages.InternalMessagesController(_sys_internalMessagesrepository, _sys_useraccountRepository).AddInternalMessagesInfo(model.F_ID, "媒体中心提醒", _sys_mediaManagement_Repository.GetSingle(x => x.F_ID == input.F_Name).Result.F_Name + "媒体提醒", user, DateTime.Parse(input.F_ReminderTime.ToString()), 1, 1, int.Parse(input.F_DeptId.Split(',')[input.F_DeptId.Split(',').Length - 1]), "", 0);
                        }
                        catch
                        {

                        }
                      
                      
                    }

                }
               
                return Success("修改成功");
            }
            else
            {
                return Error("修改失败");
            }
        }
        /// <summary>
        /// 删除媒体投放
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _sys_mediacenter_Repository.GetSingle(x => x.F_ID == item);
                    var message = await _sys_internalMessagesrepository.GetListALL(x => x.F_ID == item);
                    if (message != null)
                    {
                        foreach (var it in message)
                        {
                            it.SMS_IsDelete = (int)EnumUserCountState.Delete;
                            var n = _sys_internalMessagesrepository.Update(it);
                        }
                    }
                    model.F_IsDelete = (int)EnumUserCountState.Delete;
                    model.F_DeleteTime = DateTime.Now.ToLocalTime();
                    model.F_DeleteUser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    string[] sprite = null;
                    if (!string .IsNullOrEmpty(model.F_PlayPlan))
                      sprite = model.F_PlayPlan.Split(',');
                    if (sprite != null)
                    {
                        foreach (var it in sprite)
                        {
                            try
                            {
                                var plan = _sys_planmanagemenRepository.GetSingle(x => x.F_Id == int.Parse(it)).Result;
                                if (plan != null)
                                    plan.F_IsDelete = 1;
                                bool n = _sys_planmanagemenRepository.Update(plan).Result;
                            }
                            catch
                            {

                            }
                        }
                    }
                    if (_sys_mediacenter_Repository.Update(model).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 获取媒体投放列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListAsync(string type,string name,string tel,string phone,string commodity,  int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            if (!string.IsNullOrEmpty(name))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Name", ConditionalType = ConditionalType.Equal, FieldValue = name });
            }
           
            if (!string.IsNullOrEmpty(commodity))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Commodity", ConditionalType = ConditionalType.Like, FieldValue = commodity });
            }
            if (!string.IsNullOrEmpty(type))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Type", ConditionalType = ConditionalType.Equal, FieldValue = type });
            }
            if (!string.IsNullOrEmpty(tel))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Tel", ConditionalType = ConditionalType.Like, FieldValue = tel });
            }
            if (!string.IsNullOrEmpty(phone))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Phone", ConditionalType = ConditionalType.Like, FieldValue = phone });
            }
            #endregion
            int recordCount = 0;
            var list = await _sys_mediacenter_Repository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount });
            var obj = new
            {
                state = "success",
                message = "成功",
                rows =  ConvertAsync(list),
                total = list.Totals,
            };

            return Content(obj.ToJson());
        }
        /// <summary>
        /// 返回树形下拉框 菜单数据 
        /// </summary>
        /// <returns></returns>
        [HttpGet("getall")]
        public async Task<IActionResult> GetALL(int pid = 1)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });
            var list_ModuleInfo = await _sys_areaRepository.GetListALL(conModels, "F_Code asc");

            var treeList = new List<TreeModel>();
            foreach (var item in list_ModuleInfo)
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_Id;
                treeModel.iconcls = "";
                treeModel.text = item.F_AreaName;
                treeModel.parentid = item.F_ParentId.Value;
                treeList.Add(treeModel);
            }
            return Success("获取地区树成功", TreeRecursion(treeList, pid));
        }
        /// <summary>
        /// 递归算法
        /// </summary>
        /// <param name="data"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<TreeModel> TreeRecursion( List<TreeModel> data, int parentId = 0, int i = 0)
        {
            List<TreeModel> newList = new List<TreeModel>();
            List<TreeModel> item = data.FindAll(t => t.parentid == parentId);//data建议在调用此扩展方法前已经排序过
            if (i <= 2)
            {
                if (item.Count > 0)
                {
                    foreach (TreeModel entity in item)
                    {
                        var _list = TreeRecursion(data, entity.id, i + 1);
                        entity.children = _list.Count > 0 ? _list : null;
                        newList.Add(entity);
                    }
                }
            }
            return newList;
        }
        /// <summary>
        /// 操作媒体投放
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("operation")]
        public async Task<IActionResult> GetOperationAsync(int id,int state)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _sys_mediacenter_Repository.GetSingle(x => x.F_ID == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            model.F_State = state;
            var obj = await _sys_mediacenter_Repository.Update(model);
            if (obj)
                return Success("操作成功");
            else
                return Error ("操作失败");
        }
        /// <summary>
        /// 获取媒体投放详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _sys_mediacenter_Repository.GetSingle(x => x.F_ID == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！",  Convert(model,1));
        }


        #region 私有方法
        private  MediaCenteInput  Convert(T_Sys_MediaCente it,int type=0)
        {
            MediaCenteInput MediaCente = new MediaCenteInput();
            MediaCente.F_ID = it.F_ID;
            if (it.F_Type!=null )
            {
                MediaCente.F_Type = (int)it.F_Type; //  投放类型od    字典MTTFLX
                MediaCente.F_TypeName = _sys_dictionaryRepository.GetSingle(x => x.F_ValueId == it.F_Type).Result != null ? _sys_dictionaryRepository.GetSingle(x => x.F_ValueId == it.F_Type).Result.F_Value : "";//  投放类型
            }
            if (it.F_Name!=null )
            {
                MediaCente.F_Name = (int)it.F_Name; // 媒体名称id   中央一套、中央二套等
                MediaCente.F_Name_MT = _sys_mediaManagement_Repository.GetSingle(x => x.F_ID == it.F_Name).Result != null ? _sys_mediaManagement_Repository.GetSingle(x => x.F_ID == it.F_Name).Result.F_Name : "";// 媒体名称
            }
            MediaCente.F_Tel = it.F_Tel; //刊登号码 
            MediaCente.F_Phone = it.F_Phone; //400号码
            MediaCente.F_Commodity = it.F_Commodity; //绑定商品id
            MediaCente.F_CommodityName = "";//绑定商品
            if (!string .IsNullOrEmpty (it.F_Commodity))
            {
                string[] spritcom = it.F_Commodity.Split(',');
                try
                {
                    foreach (var ib in spritcom)
                    {
                        if (MediaCente.F_CommodityName == "")
                            MediaCente.F_CommodityName = _productRepository.GetSingle(x => x.F_ProductId ==ib).Result.F_ProductNumberName;
                        else
                            MediaCente.F_CommodityName+=","+ _productRepository.GetSingle(x => x.F_ProductId ==ib).Result.F_ProductNumberName;
                    }
                }
                catch
                {

                }
               
            }
            MediaCente.F_LaunchTime = it.F_LaunchTime; //投放日期
            MediaCente.F_DailyExpenses = it.F_DailyExpenses; //日费用
            MediaCente.F_PlayPlan = it.F_PlayPlan; //日费用
            if (type >0)
            {
                MediaCente.F_PlayPlanList = new List<PlanManagemenInput>();
                string[] spritplay= it.F_PlayPlan.Split(',');
                try
                {
                    foreach (var ib in spritplay)
                    {
                        PlanManagemenInput t_Sys_PlanManagemen = new PlanManagemenInput();
                        var planplay = _sys_planmanagemenRepository.GetSingle(x => x.F_Id == int.Parse(ib)).Result ;
                        if (planplay.F_Type!=null )
                        t_Sys_PlanManagemen.F_Type =(int ) planplay.F_Type;//0计划1媒体变更 
                        t_Sys_PlanManagemen.F_StartTime = planplay.F_StartTime;//计划开始时间
                        t_Sys_PlanManagemen.F_EndTime = planplay.F_EndTime;// 计划结束时间
                        t_Sys_PlanManagemen.F_PlayDate = planplay.F_PlayDate;//播放日期
                        t_Sys_PlanManagemen.F_BroadcastTime = planplay.F_BroadcastTime;//播出时间
                        if (planplay.F_Name!=null )
                        {
                            t_Sys_PlanManagemen.F_Name = planplay.F_Name;//广告名称（字典）
                            t_Sys_PlanManagemen.F_Name_MT = _sys_dictionaryRepository.GetSingle(x => x.F_ValueId == planplay.F_Name).Result.F_Value;//  广告名称
                        }
                        t_Sys_PlanManagemen.F_BroadcastDuration = planplay.F_BroadcastDuration;//播出时长
                        t_Sys_PlanManagemen.F_PlayCount = planplay.F_PlayCount;//播放次数
                        t_Sys_PlanManagemen.F_State = planplay.F_State.ToString ();//状态
                        t_Sys_PlanManagemen.F_Describe = planplay.F_Describe;//说明
                        MediaCente.F_PlayPlanList.Add(t_Sys_PlanManagemen);
                    }
                }
                catch
                {

                }
            }
            MediaCente.F_IsRemind = (int)it.F_IsRemind; //是否提醒
            MediaCente.F_DeptId = it.F_DeptId; //提醒部门
            string deptmsg = "";
            if (!string.IsNullOrEmpty(it.F_DeptId))
            {
                try
                {

                    string[] sprit = it.F_DeptId.Split(',');
                    foreach (var iv in sprit)
                    {

                        if (deptmsg == "")
                            deptmsg = _sys_departmentRepository.GetSingle(x => x.F_DeptId == int.Parse(iv)).Result != null ? _sys_departmentRepository.GetSingle(x => x.F_DeptId == int.Parse(iv)).Result.F_DeptName : "";
                        else
                            deptmsg = deptmsg + "," + _sys_departmentRepository.GetSingle(x => x.F_DeptId == int.Parse(iv)).Result != null ? _sys_departmentRepository.GetSingle(x => x.F_DeptId == int.Parse(iv)).Result.F_DeptName : "";

                    }

                }
                catch
                {

                }

            }
            MediaCente.F_DeptName = deptmsg;
            MediaCente.F_ReminderTime = it.F_ReminderTime; //提醒时间
            MediaCente.F_MediaChange = it.F_MediaChange; //媒体变更  ID
            if (type > 0)
            {
                MediaCente.F_MediaChangeList = new List<PlanManagemenInput>();
                string[] spritplay = it.F_MediaChange.Split(',');
                try
                {
                    foreach (var ib in spritplay)
                    {
                        PlanManagemenInput t_Sys_PlanManagemen = new PlanManagemenInput();
                        var planplay = _sys_planmanagemenRepository.GetSingle(x => x.F_Id == int.Parse(ib)).Result;
                        if (planplay.F_Type!=null )
                        {
                            t_Sys_PlanManagemen.F_Type = (int)planplay.F_Type;//0计划1媒体变更 
                           
                        }
                            t_Sys_PlanManagemen.F_ChangeType = planplay.F_ChangeType != null ? (int)planplay.F_ChangeType : 0;//变更类型字典
                        t_Sys_PlanManagemen.F_ChangeTypeName= _sys_dictionaryRepository.GetSingle(x => x.F_ValueId == planplay.F_ChangeType).Result.F_Value;//  /变更类型
                        t_Sys_PlanManagemen.F_ChangeTime = planplay.F_ChangeTime;//变更时间
                        t_Sys_PlanManagemen.F_Describe = planplay.F_Describe;//变更说明
                        MediaCente.F_MediaChangeList.Add(t_Sys_PlanManagemen);
                    }
                }
                catch
                {

                }
            }
            MediaCente.F_CreateTime = it.F_CreateTime; //创建时间
            MediaCente.F_CreateUser = it.F_CreateUser; //
            MediaCente.F_State = it.F_State; //
            return MediaCente;
        }
        /// <summary>
        /// Input转Model
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private T_Sys_MediaCente Transformation(T_Sys_MediaCente model, MediaCenteInput input,string user ,int type=0)
        {
            model.F_Type = input.F_Type;//投放类型    字典MTTFLX
            model.F_Name = input.F_Name;//媒体名称   中央一套、中央二套等 下拉
            model.F_Tel = input.F_Tel;//刊登号码
            model.F_Phone = input.F_Phone;//400号码
            model.F_Commodity = input.F_Commodity;//绑定商品
            model.F_LaunchTime = input.F_LaunchTime;//投放日期
            model.F_DailyExpenses = input.F_DailyExpenses;//日费用 单位 元
            string Planid = "";
            if (input.F_PlayPlanList!=null )
            {
                string[] sprite = null;
                if (!string .IsNullOrEmpty(model.F_PlayPlan))
                  sprite = model.F_PlayPlan.Split(',');
                if (input.F_PlayPlanList.Count >0)

                 {
                    foreach (var it in input.F_PlayPlanList)
                    {
                        T_Sys_PlanManagemen t_Sys_PlanManagemen = new T_Sys_PlanManagemen();
                        if (it .F_Id >0)
                         {
                            t_Sys_PlanManagemen = _sys_planmanagemenRepository.GetSingle(x => x.F_Id == it.F_Id).Result;
                         }
                        if (sprite!=null )
                        {
                            bool exists = sprite.Contains(it.F_Id.ToString());
                            if (exists)
                                sprite.Remove(it.F_Id.ToString());
                        }
                        t_Sys_PlanManagemen.F_Type = it.F_Type;//0计划1媒体变更 
                        t_Sys_PlanManagemen.F_StartTime = it.F_StartTime;//计划开始时间
                        t_Sys_PlanManagemen.F_EndTime = it.F_EndTime;// 计划结束时间
                        t_Sys_PlanManagemen.F_PlayDate = it.F_PlayDate;
                        t_Sys_PlanManagemen.F_BroadcastTime = it.F_BroadcastTime;//播出时间
                        t_Sys_PlanManagemen.F_Name = it.F_Name;//广告名称（字典）
                        t_Sys_PlanManagemen.F_BroadcastDuration = it.F_BroadcastDuration;//播出时长
                        t_Sys_PlanManagemen.F_PlayCount = it.F_PlayCount;//播放次数
                        t_Sys_PlanManagemen.F_Describe = it.F_Describe;//播放说明
                        if (string.IsNullOrEmpty(it.F_State))
                        {
                            it.F_State = "1";
                        }
                        t_Sys_PlanManagemen.F_State = int .Parse (it.F_State);//状态
                        t_Sys_PlanManagemen.F_CreateTime = DateTime.Now;
                        t_Sys_PlanManagemen.F_CreateUser  = user;
                        t_Sys_PlanManagemen.F_IsDelete = 0;
                        int a = 0;
                        if (it.F_Id > 0)
                        {
                            a = it.F_Id;
                            var re = _sys_planmanagemenRepository.Update (t_Sys_PlanManagemen).Result ;
                        }
                        else
                        {
                            a = _sys_planmanagemenRepository.Add(t_Sys_PlanManagemen).Result ;
                        }
                       
                        if (a >0)
                        {
                            if (Planid=="")
                                Planid += a + "";
                            else
                                Planid += "," + a;
                        }
                    }
                }
                if (sprite!=null )
                {
                    foreach (var it in sprite)
                    {
                       try
                        {
                         var plan= _sys_planmanagemenRepository.GetSingle(x => x.F_Id == int .Parse (it)).Result;
                            if (plan != null)
                                plan.F_IsDelete = 1;
                            bool n = _sys_planmanagemenRepository.Update(plan).Result ;
                        }
                        catch
                        {

                        }
                    }
                }

            }

            model.F_PlayPlan =   Planid;// 播放计划  ID
            model.F_IsRemind = input.F_IsRemind;// 是否提醒 0否1是
            if (model.F_IsRemind>0)
            {
               
               
                model.F_DeptId = input.F_DeptId;// 提醒部门
                model.F_ReminderTime = input.F_ReminderTime;// 提醒时间
                
            }
            string MediaChangeid = "";
            if (input.F_MediaChangeList != null)
            {
                if (input.F_MediaChangeList.Count > 0)
                {
                    foreach (var it in input.F_MediaChangeList)
                    {
                        T_Sys_PlanManagemen t_Sys_PlanManagemen = new T_Sys_PlanManagemen();
                        if (it.F_Id > 0)
                        {
                            t_Sys_PlanManagemen = _sys_planmanagemenRepository.GetSingle(x => x.F_Id == it.F_Id).Result;
                        }
                        t_Sys_PlanManagemen.F_Type = it.F_Type;//0计划1媒体变更 
                       // t_Sys_PlanManagemen.F_State =int .Parse ( it.F_State);//状态
                        t_Sys_PlanManagemen.F_ChangeType = it.F_ChangeType;//变更类型字典
                        t_Sys_PlanManagemen.F_ChangeTime = it.F_ChangeTime;//变更时间
                        t_Sys_PlanManagemen.F_Describe = it.F_Describe;//变更说明
                        t_Sys_PlanManagemen.F_CreateTime = DateTime.Now;
                        t_Sys_PlanManagemen.F_CreateUser = user;
                        t_Sys_PlanManagemen.F_IsDelete = 0;
                        int a = 0;
                        if (it.F_Id > 0)
                        {
                            a = it.F_Id;
                            var re = _sys_planmanagemenRepository.Update(t_Sys_PlanManagemen).Result;
                        }
                        else
                        {
                            a = _sys_planmanagemenRepository.Add(t_Sys_PlanManagemen).Result;
                        }
                        if (a > 0)
                        {
                            if (MediaChangeid == "")
                                MediaChangeid += a + "";
                            else
                                MediaChangeid += "," + a;
                        }
                    }
                }
            }
            model.F_MediaChange = MediaChangeid;
            if (type==0)
            {
                model.F_CreateUser = user;
                model.F_CreateTime = DateTime.Now;
            }
            else
            {
                model.F_CreateUser = model.F_CreateUser;
                model.F_CreateTime = model.F_CreateTime;
                model.F_UpdateUser  = user;
                model.F_UpdateTime  = DateTime.Now;
            }
           
            model.F_IsDelete = 0;
            return model;
        }

        /// model转input
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private  List<MediaCenteInput> ConvertAsync(PageData<T_Sys_MediaCente> model)
        {
            List<MediaCenteInput> input = new List<MediaCenteInput>();
            if (model != null)
            {

                foreach (var it in model.Rows)
                {
                    MediaCenteInput marketing = new MediaCenteInput();
                    marketing =  Convert(it);
                    input.Add(marketing);
                }
            }
            return input;
        }
        #endregion




    }
}