AttendanceService.cs 12 KB
using Hh.Mes.Common;
using Hh.Mes.Common.config;
using Hh.Mes.Common.Http;
using Hh.Mes.Common.Json;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Request;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.Repository;
using SqlSugar;
using System;
using System.Data;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Hh.Mes.Service
{
    /// <summary>
    /// 考勤打卡
    /// </summary>
    public class AttendanceService : RepositorySqlSugar<sys_punch_clock>
    {
        private base_work_station stations { get; set; }

        /// <summary>
        /// 刷脸打卡
        /// </summary>
        public dynamic FaceClockService(string webcam)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var res = ActionBefore();
                if (!res.Status) return res;

                #region  接口图片 识别
                var baseUrl = ConfigRead.GetInstance.GetAppsetConnection().FaceBaseUrl;
                var item = new HttpItem()
                {
                    URL = baseUrl + "faceSearch",
                    Method = "post",
                    ContentType = "application/x-www-form-urlencoded",//返回类型    可选项有默认值
                    Postdata = string.Format("file=\"{0}\"&groupId=101", webcam),
                };
                var httpResult = new HttpHelper().GetHtml(item);
                if (httpResult.StatusCode != HttpStatusCode.OK)
                {
                    res.Code = -200;
                    res.Message = httpResult.Html;
                    return res;
                }

                var result = DynamicJson.Parse(httpResult.Html);
                #endregion

                if (result.code == 0)
                {
                    string userName = result.data.name.Replace("\\", "").Replace('"', ' ').Trim();
                    var resultUser = GetSysUserByName(userName);
                    if (resultUser == null)
                    {
                        res.Code = -200;
                        res.Message = "人脸信息未绑定!请在系统管理-用户管理维护!";
                        return res;
                    }
                    //if (!Context.Queryable<base_station_user_rel>().Where(x => x.stationId == stations.id && x.userId == resultUser.id).Any())
                    //{
                    //    res.Code = -200;
                    //    res.Message = $"工位:{stations.code}未设置用户:{resultUser.account}打卡,请去工厂模型-工位人员设置!!";
                    //    return res;
                    //}
                    ShiftCodeMethod(resultUser);
                    var resultClock = base.Context.SaveQueues() > 0;
                    if (!resultClock)
                    {
                        res.Code = -200;
                        res.Message = "人脸打卡考勤失败,反复出现请联系管理员!";
                        return res;
                    }
                    res.Code = 200;
                    res.Result = resultUser;
                    return res;
                }

                res.Code = -200;
                res.Message = "人脸识别不匹配或者人脸信息未绑定,请在系统管理-用户管理维护!";
                return res;
            });
        }

        /// <summary>
        /// 刷卡打卡
        /// </summary>
        public dynamic IdCardClockService(string idCard)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var res = ActionBefore();
                if (!res.Status) return res;

                //查找卡号
                var user = Context.Queryable<sys_user>().First(x => x.idcard == idCard);
                if (user == null)
                {
                    res.Code = -200;
                    res.Message = "工卡信息未绑定!请在系统管理-用户管理维护!";
                    return res;
                }
                //if (!Context.Queryable<base_station_user_rel>().Where(x => x.stationId == stations.id && x.userId == user.id).Any())
                //{
                //    res.Code = -200;
                //    res.Message = $"工位:{stations.code}未设置用户:{user.account}打卡,请去工厂模型-工位人员设置!!";
                //    return res;
                //}
                ShiftCodeMethod(user);
                var result = base.Context.SaveQueues() > 0;
                if (!result)
                {
                    res.Code = -100;
                    res.Message = "刷卡打卡考勤失败,反复出现请联系管理员!";
                    return res;

                }
                res.Code = 200;
                res.Result = user;
                res.Message = "刷卡打卡考勤成功!";
                return res;
            });
        }


        private void ShiftCodeMethod(sys_user user)
        {
            var Time = Convert.ToDateTime("1900-01-01 " + DateTime.Now.Hour + ":" + DateTime.Now.Minute);
            var clock = new sys_punch_clock
            {
                createBy = sysWebUser?.Account,
                userCode = user.account
            };

            #region 补卡
            //if (end < start) { end= end.AddDays(1); shift_Time.timeSpanEnd = shift_Time.timeSpanEnd.AddDays(1); };//晚班加一天
            var endData = Context.Queryable<sys_punch_clock>().Where(x => x.userCode == user.account).OrderBy(x => x.createTime, OrderByType.Desc).First();
            var dayTime = DateTime.Now;
            var onATime = endData == null ? null : endData.createTime;
            var theLaidOff = true;
            //if (endData != null && (endData.mountGuard == "上岗" && !SqlFunc.DateIsSame(onATime, dayTime) 
            //                        || endData.stationCode != stations.stationCode && SqlFunc.DateIsSame(onATime, dayTime)))
            //{
            //    var shiftCode1 = Context.Queryable<product_shift, base_station, product_shift_time>((p, s, r) => 
            //                                       new JoinQueryInfos(JoinType.Inner, p.lineCode == s.lineCode && p.isDelete == 0,
            //                                                          JoinType.Inner, r.productShiftId == p.id))
            //                            .Where((p, s, r) => s.stationCode == endData.stationCode && r.timeSpanStart <= Time && SqlFunc.IIF(r.timeSpanEnd > Time, r.timeSpanStart.AddDays(1), r.timeSpanEnd) >= Time)
            //                            .Select((p, s, r) => p.code)
            //                            .ToArray();


            //    clock.equipmentIP = endData.equipmentIP;
            //    clock.stationCode = endData.stationCode;
            //    clock.shiftCode = shiftCode1[0];
            //    clock.mountGuard = "下岗";
            //    clock.isManual = false;
            //    clock.createTime = dayTime;
            //    base.Context.Insertable(clock).AddQueue();
            //    theLaidOff = false;
            //}
            #endregion

            //var shiftCode2 = Context.Queryable<product_shift, base_station, product_shift_time>((p, s, r) => 
            //                                  new JoinQueryInfos(JoinType.Inner, p.lineCode == s.lineCode && p.isDelete == 0, 
            //                                      JoinType.Inner, r.productShiftId == p.id))
            //                        .Where((p, s, r) => s.id == stations.id && r.timeSpanStart <= Time && SqlFunc.IIF(r.timeSpanEnd > Time, r.timeSpanStart.AddDays(1), r.timeSpanEnd) >= Time)
            //                        .Select((p, s, r) => p.code)
            //                        .ToArray();
            clock.equipmentIP = stations.monitorIP;
            clock.stationCode = stations.workStationCode;
            //clock.shiftCode = shiftCode2.Length == 0 ? "" : shiftCode2[0];
            clock.mountGuard = theLaidOff && endData != null && endData.mountGuard == "上岗" ? "下岗" : "上岗";
            clock.isManual = true;
            clock.createTime = dayTime.AddSeconds(1);
            base.Context.Insertable(clock).AddQueue();
        }

        #region 考勤管理 列表
        /// <summary>
        /// //获取 sys_punch_clock 列表
        /// </summary>
        public Task<DataSet> Load(PageReq pageReq, sys_punch_clock clock)
        {
            string orderBy = (pageReq == null || string.IsNullOrEmpty(pageReq.field)) ? " id desc" : $"{pageReq.field} {pageReq.order} ";
            string sqlWhere = SqlWhere(clock);
            var stringBuilder = new StringBuilder();
            //页码,页数
            //Exel ture 不分页
            if (!clock.Exel && pageReq != null)
            {
                stringBuilder.Append("declare @pageIndex int,@pageSize int,@offset int");
                stringBuilder.AppendLine($"  select @pageIndex={pageReq.page}, @pageSize={pageReq.limit}, @offset=(@pageIndex - 1) * @pageSize");
            }

            stringBuilder.AppendLine($@" select t1.*,t2.shiftName from sys_punch_clock t1  left join product_shift t2 on t1.shiftCode=t2.code
                                         where {sqlWhere}
                                         order by {orderBy} ");
            var parameters = new
            {
                name = clock.userCode,
                equipmentIP = clock.equipmentIP,
                stationCode = clock.stationCode
            };

            //Exel false 分页
            if (!clock.Exel)
            {
                stringBuilder.AppendLine("  offset @offset row fetch next @pageSize row only ");
                stringBuilder.Append($" select rowTotal= count(*) from sys_punch_clock  t1 with(nolock) where {sqlWhere}");
            }
            return base.Context.Ado.GetDataSetAllAsync(stringBuilder.ToString(), parameters);
        }


        public string SqlWhere(sys_punch_clock model)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("1=1");
            if (!string.IsNullOrEmpty(model.userCode))
            {
                stringBuilder.Append($" and  t1.UserCode like '%'+@userCode+'%' ");
            }
            if (model.equipmentIP != null)
            {
                stringBuilder.Append($" and  t1.equipmentIP=@equipmentIP ");
            }
            if (!string.IsNullOrEmpty(model.stationCode))
            {
                stringBuilder.Append($" and  t1.stationCode like '%'+@stationCode+'%' ");
            }

            return stringBuilder.ToString();
        }
        #endregion

        private sys_user GetSysUserByName(string name)
        {
            return Context.Queryable<sys_user>().First(x => x.account == name);
        }


        /// <summary>
        /// ip, 工位查找
        /// </summary>
        /// <returns></returns>
        public Response ActionBefore()
        {
            var result = new Response();
            string ip = ComputerHelp.GetAddressIP(); // CommonHelper.GetAddressIP();
            if (string.IsNullOrEmpty(ip) || ip == "127.0.0.1")
            {
                result.Code = -200;
                result.Status = false;
                result.Message = "刷脸打卡,请检查本地ip,确认是否连接网络,请于【工位】中设置Ip地址!";
                return result;
            }
            if (ip == "127.0.0.1")
            {
                result.Code = -200;
                result.Status = false;
                result.Message = "刷脸打卡,ip【127.0.0.1】请检查本地ip,确认是否连接网络,请于【工位】中设置Ip地址!";
                return result;
            }
            stations = Context.Queryable<base_work_station>().Where(u => u.monitorIP == ip).First();

            if (stations == null || string.IsNullOrEmpty(stations.lineCode))
            {
                result.Code = -200;
                result.Status = false;
                result.Message = $"刷脸打卡,根据ip【{ip}】找到对应工位和线体失败,请检查工位信息ip是否配置成功,请于【工位】中设置Ip地址!";
                return result;
            };
            result.Code = 200;
            return result;
        }

    }
}