using AutoMapper;
using EyeSoft.Runtime.InteropServices;
using OASystem.Domain;
using OASystem.Domain.Dtos.Statistics;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.Groups;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Groups
{
    /// <summary>
    /// 客户拜访 仓储
    /// </summary>
    public class VisitingClientsRepository : BaseRepository<Grp_VisitingClients, VisitingClientsView>
    {

        private readonly IMapper _mapper;
        private readonly JsonView _view; 
        public VisitingClientsRepository(SqlSugarClient sqlSugar, IMapper mapper)
            : base(sqlSugar)
        {
            _mapper = mapper;
            _view = new JsonView() { Code = StatusCodes.Status400BadRequest, Msg = BusStatusCode.Failed.GetEnumDescription() };
        }

        /// <summary>
        /// 获取客户拜访列表
        /// </summary>
        /// <param name="portType"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="diId"></param>
        /// <param name="search"></param>
        /// <returns></returns>
        public async Task<JsonView> _List(int portType,int pageIndex, int pageSize,int diId,string search)
        {
            if (portType ==1 || portType == 2 || portType == 3)
            {
                string sql  = string.Format(@$"Select
	ROW_NUMBER() Over(Order By BeginDt Asc) As RowNumber,
	vc.Id,
	vc.DiId,
	vc.BeginDt,
	vc.EndDt,
	vc.CustomerUnit,
	vc.CustomerJob,
	vc.CustomerName,
	vc.CustomerContact,
	u.CnName As Operator,
	vc.CreateTime As OperationDt,
	vc.Remark
From Grp_VisitingClients vc 
Left Join Sys_Users u On vc.CreateUserId = u.Id
Where vc.Isdel = 0 And vc.DiId = {diId}");

                RefAsync<int > total = 0;
                var data = await _sqlSugar.SqlQueryable<VisitingClientsListView>(sql).ToPageListAsync(pageIndex, pageSize, total);

                _view.Code = StatusCodes.Status200OK;
                _view.Msg = MsgTips.Succeed;
                _view.Data = data;
                _view.Count = total;
            }

            return _view;
        }

        /// <summary>
        /// 团组客户拜访 Add Or Edit
        /// </summary>
        /// <param name="_dto"></param>
        /// <returns></returns>
        public async Task<JsonView> _AddOrEdit(MarketingSalesVCOperrateDto _dto)
        {
            var info = _mapper.Map<Grp_VisitingClients>(_dto);

            if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3)
            {
                if (info.Id > 0) //编辑
                {
                    var update = await _sqlSugar.Updateable(info).IgnoreColumns(it => new { it.CreateTime, it.CreateUserId, it.DeleteUserId, it.DeleteTime, it.IsDel }).ExecuteCommandAsync();
                    if (update <= 0) return new JsonView() { Code = (int)BusStatusCode.UpdateFailed, Msg = BusStatusCode.UpdateFailed.GetEnumDescription() };
                }
                else //新增
                {
                    info.CreateUserId = _dto.UserId;
                    var add = await _sqlSugar.Insertable(info).ExecuteCommandAsync();
                    if (add <= 0) return new JsonView() { Code = (int)BusStatusCode.AddFailed, Msg = BusStatusCode.AddFailed.GetEnumDescription() };
                }
                return new JsonView() { Code = (int)BusStatusCode.Success, Msg = BusStatusCode.Success.GetEnumDescription() };
            }
            else return new JsonView() { Code = (int)BusStatusCode.PortTypeError, Msg = BusStatusCode.PortTypeError.GetEnumDescription() };
        }


        public async Task<JsonView> _Save(MarketingSalesVCSaveDto _dto)
        {
            var infos = _mapper.Map<List<Grp_VisitingClients>>(_dto.Items);

            if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3)
            {
                if (_dto.DiId < 1)
                {
                    return new JsonView() { Code = (int)BusStatusCode.DiIdValueError, Msg = BusStatusCode.DiIdValueError.GetEnumDescription() };
                }


                //int diid = infos[0].DiId;
                int userId = _dto.UserId;
                //if (diid < 1) return new JsonView() { Code = (int)BusStatusCode.DiIdValueError, Msg = BusStatusCode.DiIdValueError.GetEnumDescription() };

                if (userId < 1) return new JsonView() { Code = (int)BusStatusCode.UserIdValueError, Msg = BusStatusCode.UserIdValueError.GetEnumDescription() };

                //执行逻辑删除
                var update = await _sqlSugar.Updateable<Grp_VisitingClients>()
                                            .SetColumns(it => new Grp_VisitingClients() { IsDel = 1, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DeleteUserId = _dto.UserId })
                                            .Where(it => it.DiId == _dto.DiId)
                                            .ExecuteCommandAsync();

                if (infos.Count > 0)
                {
                    infos.ForEach(it =>
                    {
                        it.CreateUserId = _dto.UserId;
                    });

                    //执行添加
                    var add = await _sqlSugar.Insertable(infos).ExecuteCommandAsync();

                    if (add > 0) return new JsonView() { Code = (int)BusStatusCode.Success, Msg = BusStatusCode.Success.GetEnumDescription() };

                }
                else
                {
                  return  new JsonView() { Code = (int)BusStatusCode.Success, Msg = BusStatusCode.Success.GetEnumDescription() };
                }
            }
            else return new JsonView() { Code = (int)BusStatusCode.PortTypeError, Msg = BusStatusCode.PortTypeError.GetEnumDescription() };

            return new JsonView() { Code = (int)BusStatusCode.Failed, Msg = BusStatusCode.Failed.GetEnumDescription() };
        }

        /// <summary>
        /// 团组客户拜访 del
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<JsonView> _Del(int id, int userId)
        {
            var info = new Grp_VisitingClients() { Id = id, IsDel = 1, DeleteUserId = userId, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")};
            var update = await _sqlSugar.Updateable(info)
                                        .UpdateColumns(it => new { it.IsDel, it.DeleteUserId, it.DeleteTime })
                                        .WhereColumns(it => it.Id)
                                        .ExecuteCommandAsync();
            if (update <= 0) return new JsonView() { Code = (int)BusStatusCode.DeleteFailed, Msg = BusStatusCode.DeleteFailed.GetEnumDescription() };
            return new JsonView() { Code = (int)BusStatusCode.Success, Msg = BusStatusCode.Success.GetEnumDescription() };

        }
    }
}
