using Dapper;
using Ewide.Core;
using Ewide.Core.Extension;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ewide.Application.Service
{
    /// <summary>
    /// 房屋任务（巡查任务/建档任务）
    /// </summary>
    [ApiDescriptionSettings(Name = "HouseTask", Order = 190)]
    public class HouseTaskService : IHouseTaskService, IDynamicApiController, ITransient
    {
        private readonly IRepository<BsHouseTask> _houseTaskRep;
        private readonly IRepository<BsHouseInfo> _houseInfoRep;
        private readonly IDapperRepository _dapperRepository;
        private readonly IUserManager _userManager;

        private readonly IHouseLogService _houseLogService;

        public HouseTaskService(IRepository<BsHouseTask> HouseTaskRep, IRepository<BsHouseInfo> HouseInfoRep, IDapperRepository dapperRepository, IUserManager userManager, IHouseLogService houseLogService)
        {
            _houseTaskRep = HouseTaskRep;
            _houseInfoRep = HouseInfoRep;
            _dapperRepository = dapperRepository;
            _userManager = userManager;

            _houseLogService = houseLogService;
        }

        [HttpPost("/houseTask/page")]
        public async Task<dynamic> QueryPage([FromBody] QueryHouseTaskInput input)
        {
            var sql = @"SELECT T.Id,AA.Name AreaName,RA.Name RoadName,CA.Name CommName,Proj.AreaCode,Proj.Note,Proj.Name,CONCAT(Proj.`Name`, IFNULL(CONCAT('(',Proj.Note,')'), '')) FullProjName,HC.HouseCode,HC.Address,T.EndTime,HC.Type,HC.Industry,HC.No,T.Status,IFNULL(HI.State,0) State FROM `bs_house_task` T
LEFT JOIN bs_house_code HC ON T.HouseCodeId = HC.Id
LEFT JOIN bs_house_info HI ON HI.HouseCodeId = T.HouseCodeId
LEFT JOIN bs_house_projectinfo Proj ON Proj.Id=HC.ProjectId
LEFT JOIN sys_area_code CA ON CA.Code = Proj.AreaCode
LEFT JOIN sys_area_code RA ON RA.AdCode = SUBSTR(CA.AdCode,1,9)
LEFT JOIN sys_area_code AA ON AA.AdCode = SUBSTR(CA.AdCode,1,6)
WHERE T.IsEnabled = 1 {0}";
            var user = await _userManager.CheckUserAsync();
            if (user == null) throw Oops.Oh("登录信息丢失");

            var userRoles = await _userManager.GetUserRoleList();
            var userOrg = await _userManager.GetUserOrgInfo();
            var param = new DynamicParameters();
            if (userRoles.Where(r => r.Code == Enum.GetName(HouseManagerRole.HouseSecurityManager).ToUnderScoreCase()).Any())
            {
                sql = String.Format(sql, " AND T.UserID=@UserID ");
                param.Add("UserID", user.Id);
            }

            if (userRoles.Where(r => r.Code == Enum.GetName(HouseManagerRole.ZoneManager).ToUnderScoreCase()).Any())
            {
                sql = String.Format(sql, " AND (T.Status=3 OR T.Status=6) AND HC.ZoneId = @ZoneId ");
                param.Add("ZoneId", userOrg.Id);
            }
            
            return await _dapperRepository.QueryPageDataDynamic(sql, input, param, filterFields: new string[] { "Type", "Address", "HouseCode", "Status","State" });
        }

        [HttpPost("/houseTask/submit")]
        [UnitOfWork]
        [AllowAnonymous]
        public async Task Submit([FromBody] SubmitHouseTaskInput input)
        {
            //获取任务实体
            var houseTask = await _houseTaskRep.DetachedEntities.FirstOrDefaultAsync(t => t.Id == input.TaskId);
            if (houseTask == null) throw Oops.Oh("任务不存在");
            houseTask.Status = 2;
            houseTask.LastSubmitTime = DateTime.Now;
            if (!houseTask.SubmitTime.HasValue) houseTask.SubmitTime = houseTask.LastSubmitTime;
            await houseTask.UpdateExcludeAsync(new string[] { nameof(BsHouseTask.TaskType) }, ignoreNullValues: true);

            if(houseTask.TaskType == 0)
            {
                var houseInfo = await _houseInfoRep.DetachedEntities.FirstOrDefaultAsync(h => h.HouseCodeId == houseTask.HouseCodeId);
                if (houseInfo == null) throw Oops.Oh("提交审核失败：请先保存后再提交");

                houseInfo.State = 5;
                await houseInfo.UpdateExcludeAsync(new[] { nameof(BsHouseInfo.HouseGrade) }, true);
            }

            // 提交时流转日志
            await _houseLogService.Done(houseTask.HouseCodeId);
        }
    }
}
