using AutoMapper;
using OASystem.Domain;
using OASystem.Domain.Dtos.Resource;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Resource
{
    public class AskDataRepository : BaseRepository<Res_AskData, QueryAskDataDto>
    {
        private readonly IMapper _mapper;
        public AskDataRepository(SqlSugarClient sqlSugar, IMapper mapper) : base(sqlSugar)
        {
            _mapper = mapper;
        }
        

        public async Task<Result> QueryAskData(QueryAskDataDto dto)
        {

            string sqlWhere = string.Empty;
            if (!string.IsNullOrWhiteSpace(dto.Country))
            {
                sqlWhere += string.Format(@"And Country like '%{0}%'", dto.Country);
            }
            if (!string.IsNullOrWhiteSpace(dto.Area))
            {
                sqlWhere += string.Format(@"And Area like '%{0}%'", dto.Area);
            }
            if (!string.IsNullOrWhiteSpace(dto.Field))
            {
                sqlWhere += string.Format(@"And Field like '%{0}%'", dto.Field);
            }
            sqlWhere += string.Format(@"And IsDel={0}", 0);

            if (!string.IsNullOrEmpty(sqlWhere.Trim()))
            {
                Regex r = new Regex("And");
                sqlWhere = r.Replace(sqlWhere, "Where", 1);
            }
            string sql = string.Format(@"select * from Res_AskData {0} order by CreateTime desc", sqlWhere);
            List<Res_AskData> askDatd = await _sqlSugar.SqlQueryable<Res_AskData>(sql).ToListAsync();
            List<Grp_DelegationInfo> delegationInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(a => a.IsDel == 0).ToListAsync();
            var msg = string.Empty;
            if (askDatd.Count != 0 && delegationInfo.Count != 0) msg = "查询成功!";
            else msg = "查询成功!";

            return new Result() { Code = 0, Msg = msg, Data = new { askDatd = askDatd, delegationInfo = delegationInfo } };
        }

        /// <summary>
        /// 请示数据库操作(Status:1.新增,2.修改)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> OpAskData(OpAskDataDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                if (dto.Status == 1)//添加
                {
                    string selectSql = string.Format(@"select * from Res_AskData where Country='{0}' and Area='{1}' and UnitName='{2} and IsDel={3}'", dto.Country, dto.Area,dto.UnitName, 0);
                    var res_AskData = await _sqlSugar.SqlQueryable<Res_AskData>(selectSql).FirstAsync();//查询是否存在
                    if (res_AskData != null)
                    {
                        return result = new Result() { Code = -1, Msg = "该信息已存在,请勿重复添加!" };

                    }
                    else//不存在,可添加
                    {

                        Res_AskData _AskData = _mapper.Map<Res_AskData>(dto);
                        int id = await _sqlSugar.Insertable(_AskData).ExecuteReturnIdentityAsync();
                        if (id == 0)
                        {
                            return result = new Result() { Code = -1, Msg = "添加失败!" };

                        }
                        return result = new Result() { Code = 0, Msg = "添加成功!", Data = new { Id = id } };
                    }
                }
                else if (dto.Status == 2)//修改
                {
                    bool res = await UpdateAsync(a => a.Id == dto.Id, a => new Res_AskData
                    {
                        Country=dto.Country,
                        Area=dto.Area,
                        UnitName =dto.UnitName,
                        Field =dto.Field,
                        TalkCase =dto.TalkCase,
                        CreateUserId = dto.CreateUserId,
                        Remark = dto.Remark,
                    });
                    if (!res)
                    {
                        return result = new Result() { Code = -1, Msg = "修改失败!" };
                    }
                    return result = new Result() { Code = 0, Msg = "修改成功!", Data = new { Id = dto.Id } };
                }
                else
                {
                    return result = new Result() { Code = -1, Msg = "请传入Status参数,1添加 2修改!" };
                }
            }
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "程序错误!" };
            }
        }
    }
}