using System.Web.Http;
using Model;
using System.Collections.Generic;
using System;
using BLL;
using System.Linq;
using static WebAPI.Controllers.HSSE.ImageRecognitionController;

namespace Mvc.Controllers
{
    public class CheckListController : ApiController
    {
        #region 根据项目日期获取巡检记录
        [HttpGet]
        public Model.ResponeData GetCheckList(string projectId, string checkDate)
        {
            var responeData = new Model.ResponeData();
 
                try
                {
                    DateTime mdate = Funs.GetNewDateTimeOrNow(checkDate);
                    var list = Funs.DB.Check_CheckControl.Where(q => q.CheckDate.Value.Year == mdate.Year
                                       && q.CheckDate.Value.Month == mdate.Month
                                       && q.CheckDate.Value.Day == mdate.Day);
                    if(string.IsNullOrEmpty(projectId)&& projectId!=null)
                    {
                        list = list.Where(p=>p.ProjectId == projectId);
                    }    
                    responeData.data = list.OrderBy(x=>x.CheckDate).ToList().Select(x => new
                    {
                        CheckControlCode = x.CheckControlCode, // ID
                        DocCode = x.DocCode,                    // 编号
                        ProjectId = x.ProjectId,                // 项目ID
                        ProjectName = Funs.DB.Base_Project.FirstOrDefault(p => p.ProjectId == x.ProjectId).ProjectName,
                        CheckMan = x.CheckMan,      // 巡检人ID
                        CheckManName = (from y in Funs.DB.Sys_User where y.UserId == x.CheckMan select y.UserName).First(),// 巡检人
                        CheckDate = String.Format("{0:yyyy-MM-dd}", x.CheckDate),                // 巡检日期
                        QuestionType = x.QuestionType,                // 问题类型
                        QuestionTypeName = Funs.DB.Base_QualityQuestionType.FirstOrDefault(e => e.QualityQuestionTypeId == x.QuestionType).QualityQuestionType,
                        States = x.State,
                        LimitDate = String.Format("{0:yyyy-MM-dd}", x.LimitDate),
                        QuestionDef = x.QuestionDef,
                    }); ;

                }
                catch (Exception ex)
                {
                    responeData.code = 0;
                    responeData.message = ex.Message;
                }

           
            return responeData;
        }
        #endregion
        //
        // 质量巡检
        // GET: /Draw/
        [HttpGet]
        public ResponseData<object> Index(string projectId, int index, int page, string state, string name)
        {
            ResponseData<object> res = new ResponseData<object>();
            try
            {res.successful = true;
            res.resultValue = BLL.CheckControlService.GetListDataForApi(state, name, projectId, index, page);

            }
            catch (Exception e)
            {
                res.successful = false;
                res.message = e.Message;
            }
            
            return res;
        }

        /// <summary>
        /// 根据code获取详情
        /// </summary>
        /// <param name="CheckControlCode"></param>
        /// <returns></returns>
        public ResponseData<object> GetCheckControl(string code)
        {
            ResponseData<object> res = new ResponseData<object>();
            object checkControl = BLL.CheckControlService.GetCheckControlForApi(code);
            res.successful = true;
            res.resultValue = checkControl;
            return res;
        }

        [HttpGet]
        public ResponseData<string> Conut(string projectId, string searchWord, string unitId = null, string unitWork = null, string problemType = null, string professional = null, string dateA = null, string dateZ = null)
        {
            ResponseData<string> res = new ResponseData<string>();
            res.successful = true;
            res.resultValue = BLL.CheckControlService.GetListCountStr(projectId, searchWord, unitId, unitWork, problemType, professional, dateA, dateZ);
            return res;
        }
        [HttpGet]
        public ResponseData<List<Check_CheckControl>> Search(string state, string projectId, int index, int page, string unitId = null, string unitWork = null, string problemType = null, string professional = null, string dateA = null, string dateZ = null)
        {
            ResponseData<List<Check_CheckControl>> res = new ResponseData<List<Check_CheckControl>>();

            res.successful = true;
            res.resultValue = BLL.CheckControlService.GetListDataForApi(state, unitId, unitWork, problemType, professional,dateA, dateZ, projectId, index, page);
            return res;
        }

    
        /// <summary>
        /// 根据code获取 审核记录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ResponseData<List<Check_CheckControlApprove>> GetApproveByCode(string code)
        {
            ResponseData<List<Check_CheckControlApprove>> res = new ResponseData<List<Check_CheckControlApprove>>();

            res.successful = true;
            res.resultValue = BLL.CheckControlApproveService.GetListDataByCodeForApi(code);
            return res;
        }
        public ResponseData<Check_CheckControlApprove> GetCurrApproveByCode(string code)
        {
            ResponseData<Check_CheckControlApprove> res = new ResponseData<Check_CheckControlApprove>();

            res.successful = true;
            res.resultValue = BeanUtil.CopyOjbect<Check_CheckControlApprove>(BLL.CheckControlApproveService.getCurrApproveForApi(code), true);
            return res;
        }
        [HttpPost]
        public ResponseData<string> AddCheckControl([FromBody]Model.Check_CheckControl CheckControl)
        {
            ResponseData<string> res = new ResponseData<string>();
            try
            {
                if (string.IsNullOrEmpty(CheckControl.CheckControlCode))
                {
                    if (string.IsNullOrEmpty(CheckControl.DocCode))
                    {
                        CheckControl.DocCode = BLL.SQLHelper.RunProcNewId("SpGetNewCode5ByProjectId", "dbo.Check_CheckControl", "DocCode",CheckControl.ProjectId, "QXJ-");
                    }
                    CheckControl.CheckControlCode = Guid.NewGuid().ToString();
                    BLL.CheckControlService.AddCheckControlForApi(CheckControl);
                    res.resultValue = CheckControl.CheckControlCode;
                }
                else
                {
                    BLL.CheckControlService.UpdateCheckControlForApi(CheckControl);
                    res.resultValue = CheckControl.CheckControlCode;
                }

                res.successful = true;

            }
            catch (Exception e)
            {
                res.resultHint = e.StackTrace;
                res.successful = false;
            }
            return res;

        }

        /// <summary>
        /// 
        /// </summary>
        public static void SaveAttachFile(string dataId, string menuId, string url)
        {
            Model.ToDoItem toDoItem = new Model.ToDoItem
            {
                MenuId = menuId,
                DataId = dataId,
                UrlStr = url,
            };
            APIUpLoadFileService.SaveAttachUrl(toDoItem);
        }

        [HttpPost]
        public ResponseData<string> AddApprove([FromBody]Model.Check_CheckControlApprove approve)
        {
            ResponseData<string> res = new ResponseData<string>();
            try
            {

                Model.Check_CheckControl CheckControl = new Model.Check_CheckControl();
                CheckControl.CheckControlCode = approve.CheckControlCode;
                CheckControl.State=approve.ApproveType;
                BLL.CheckControlService.UpdateCheckControlForApi(CheckControl);

                if (approve.ApproveType != "1" && approve.ApproveType != "7")
                {

                    var userid = Request.Headers.TryGetValues("token", out IEnumerable<string> token);
                    var user =  BLL.APIUserService.getUserByUserId(token.FirstOrDefault());
                    APICommonService.SendSubscribeMessage(approve.ApproveMan, "质量巡检问题待办理", user.UserName, string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));

                }
                res.resultValue = BLL.CheckControlApproveService.AddCheckControlApproveForApi(approve);
                res.successful = true;

            }
            catch (Exception e)
            {
                res.resultHint = e.StackTrace;
                res.successful = false;
            }
            return res;

        }
        [HttpPost]
        public ResponseData<string> UpdateApprove([FromBody]Model.Check_CheckControlApprove approve)
        {
            ResponseData<string> res = new ResponseData<string>();
            try
            {
                // Model.Check_CheckControlApprove approve1 = BLL.CheckControlApproveService.GetCheckControlApproveByCheckControlId(approve.CheckControlCode);
                
                approve.ApproveDate = DateTime.Now;
                BLL.CheckControlApproveService.UpdateCheckControlApproveForApi(approve);
                res.successful = true;

            }
            catch (Exception e)
            {
                res.resultHint = e.StackTrace;
                res.successful = false;
            }
            return res;

        }
        // GET: /Draw/
        [HttpGet]
        public ResponseData<string> see(string dataId, string userId)
        {
            ResponseData<string> res = new ResponseData<string>();
            res.successful = true;
            BLL.CheckControlApproveService.See(dataId, userId);
            return res;
        }
    }
}