using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Edu.AOP;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.User;
using Edu.Module.User;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Edu.Common.Enum.User;

namespace Edu.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class WorkFlowController : BaseController
    {
        /// <summary>
        /// 审核处理
        /// </summary>
        private readonly WorkFlowModule workFlowModule = new WorkFlowModule();


        #region 审核管理

        #region 获取模板
        /// <summary>
        /// 获取审批流程模板
        /// </summary>        
        /// <returns></returns>
        public ApiResult AuditWorkFlowTemplate()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<Rb_Workflow_Template_Extend> wfTemplateList = workFlowModule.GetTemplateByEmpId(empId);
            var groupDic = EnumHelper.EnumToList(typeof(WFTGroupTypeEnum));
            List<Object> dataLsit = new List<Object>();
            foreach (var item in groupDic)
            {
                List<Rb_Workflow_Template_Extend> groupTemplateList = wfTemplateList.Where(t => t.GroupType == (WFTGroupTypeEnum)Convert.ToInt32(item.Id)).ToList();
                if (groupTemplateList != null && groupTemplateList.Count > 0)
                {
                    List<object> templateList = new List<object>();
                    foreach (var template in groupTemplateList)
                    {
                        string[] tempTypeStr = template.TemplateType.ToName().Split('|');
                        if (tempTypeStr.Length > 1)
                        {
                            var tmp = new { id = template.Id, name = template.Name, icon = Config.GetOssFileUrl + tempTypeStr[1], cmd = tempTypeStr[3], submitCmd = tempTypeStr[4], jumpUrl = $"vt://applySubmit/view?type={template.Name}" };
                            templateList.Add(tmp);
                        }
                    }
                    var data = new { groupName = item.Name, groupId = item.Id, templateList };
                    dataLsit.Add(data);
                }
            }
            return ApiResult.Success(message: "获取成功", data: dataLsit);
        }

        /// <summary>
        /// 获取请假模板
        /// </summary>
        /// <returns></returns>
        public ApiResult AskForLeaveTemplate()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<Rb_Workflow_Template_Extend> wfTemplateList = workFlowModule.GetTemplateByEmpId(empId);
            if (wfTemplateList.Where(t => (int)t.TemplateType == (int)WFTTemplateTypeEnum.AskForLeave).ToList().Count == 0)
            {
                return ApiResult.Failed(message: "该模板暂未启用");
            }
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int workFlowId = JsonHelper.GetInt(parm, "workFlowId");
            var askforleave = workFlowModule.GetAskforleave(workFlowId);
            List<FormDataModel> formList = new List<FormDataModel>();
            List<Dictionary<string, int>> categoryList = new List<Dictionary<string, int>>();
            foreach (var item in EnumHelper.EnumToList(typeof(AskforleaveTypeEnum)))
            {
                Dictionary<string, int> dic = new Dictionary<string, int>
                {
                    { item.Name, Convert.ToInt32(item.Id) }
                };
                categoryList.Add(dic);
            }
            FormDataModel askforleaveType = new FormDataModel()
            {
                formType = FromTypeEnum.Selectfield.ToName(),
                value = askforleave == null ? 0 : (int)askforleave.AskforleaveType,
                title = "请假类型",
                placeHolder = "请选择",
                required = true,
                key = "askforleaveType",
                category = categoryList
            };
            formList.Add(askforleaveType);

            FormDataModel startTime = new FormDataModel()
            {
                formType = FromTypeEnum.DateTimeField.ToName(),
                value = askforleave == null ? "" : askforleave.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                title = "开始时间",
                placeHolder = "开始时间",
                required = true,
                key = "startTime"
            };
            formList.Add(startTime);
            FormDataModel endTime = new FormDataModel()
            {
                formType = FromTypeEnum.DateTimeField.ToName(),
                value = askforleave == null ? "" : askforleave.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                title = "结束时间",
                placeHolder = "结束时间",
                required = true,
                key = "endTime"
            };
            formList.Add(endTime);
            FormDataModel duration = new FormDataModel()
            {
                formType = FromTypeEnum.DurationField.ToName(),
                value = askforleave == null ? 0 : askforleave.Duration,
                title = "时长(小时)",
                placeHolder = "时长",
                required = true,
                key = "duration"
            };
            formList.Add(duration);
            FormDataModel description = new FormDataModel()
            {
                formType = FromTypeEnum.TextareaField.ToName(),
                value = askforleave == null ? "" : askforleave.Description,
                title = "请假事由",
                placeHolder = "请输入请假事由",
                required = true,
                key = "description"
            };
            formList.Add(description);
            if (askforleave != null && !string.IsNullOrWhiteSpace(askforleave.Image))
            {
                List<string> imgList = JsonConvert.DeserializeObject<List<string>>(askforleave.Image);
                List<string> resultImgList = new List<string>();
                foreach (var item in imgList)
                {
                    resultImgList.Add(Config.GetOssFileUrl + item);
                }
                FormDataModel image = new FormDataModel()
                {
                    formType = FromTypeEnum.ImageField.ToName(),
                    value = resultImgList,
                    title = "图片",
                    key = "images"
                };
                formList.Add(image);
            }
            else
            {
                FormDataModel image = new FormDataModel()
                {
                    formType = FromTypeEnum.ImageField.ToName(),
                    value = "",
                    title = "图片",
                    key = "images"
                };
                formList.Add(image);
            }

            return ApiResult.Success("获取成功", data: formList);
        }

        /// <summary>
        /// 获取出差模板
        /// </summary>
        /// <returns></returns>
        public ApiResult EvectionTemplate()
        {

            int empId = Convert.ToInt32(RequestParm.Uid);
            List<Rb_Workflow_Template_Extend> wfTemplateList = workFlowModule.GetTemplateByEmpId(empId);
            if (wfTemplateList.Where(t => (int)t.TemplateType == (int)WFTTemplateTypeEnum.Evection).ToList().Count == 0)
            {
                return ApiResult.Failed(message: "该模板暂未启用");
            }
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int workFlowId = JsonHelper.GetInt(parm, "workFlowId");
            var evection = workFlowModule.GetEvection(workFlowId);
            List<FormDataModel> formList = new List<FormDataModel>();
            FormDataModel description = new FormDataModel()
            {
                formType = FromTypeEnum.textField.ToName(),
                value = evection == null ? "" : evection.Description,
                title = "出差事由",
                placeHolder = "请输入出差事由",
                required = true,
                key = "description"
            };
            formList.Add(description);

            #region 行程
            {
                List<List<FormDataModel>> allTravelFormList = new List<List<FormDataModel>>();
                FormDataModel travel = new FormDataModel()
                {
                    formType = FromTypeEnum.ChildField.ToName(),
                    value = allTravelFormList,
                    title = "行程",
                    key = "travel"
                };

                #region 行程表单
                {

                    List<Rb_Workflow_Travel_Extend> travelList = workFlowModule.GetTravelList(workFlowId);
                    if (evection != null && travelList.Count > 0)
                    {
                        foreach (var travelData in travelList)
                        {
                            List<FormDataModel> travelFormList = new List<FormDataModel>();
                            allTravelFormList.Add(travelFormList);
                            List<Dictionary<string, int>> vehicleCategoryList = new List<Dictionary<string, int>>();
                            foreach (var item in EnumHelper.EnumToList(typeof(TravelVehicleEnum)))
                            {
                                Dictionary<string, int> dic = new Dictionary<string, int>
                                {
                                    { item.Name, Convert.ToInt32(item.Id) }
                                };
                                vehicleCategoryList.Add(dic);
                            }
                            FormDataModel vehicle = new FormDataModel()
                            {
                                formType = FromTypeEnum.Selectfield.ToName(),
                                value = (int)travelData.Vehicle,
                                title = "交通工具",
                                required = true,
                                key = "vehicle",
                                category = vehicleCategoryList
                            };
                            travelFormList.Add(vehicle);
                            List<Dictionary<string, int>> typeCategoryList = new List<Dictionary<string, int>>();
                            foreach (var item in EnumHelper.EnumToList(typeof(TravelVehicleTypeEnum)))
                            {
                                Dictionary<string, int> dic = new Dictionary<string, int>
                                {
                                    { item.Name, Convert.ToInt32(item.Id) }
                                };
                                typeCategoryList.Add(dic);
                            }
                            FormDataModel type = new FormDataModel()
                            {
                                formType = FromTypeEnum.Selectfield.ToName(),
                                value = (int)travelData.Type,
                                title = "单程往返",
                                required = true,
                                key = "type",
                                category = typeCategoryList
                            };
                            travelFormList.Add(type);
                            FormDataModel departCity = new FormDataModel()
                            {
                                formType = FromTypeEnum.textField.ToName(),
                                value = travelData.DepartCity,
                                title = "出发城市",
                                placeHolder = "请输入城市",
                                required = true,
                                key = "departCity"
                            };
                            travelFormList.Add(departCity);
                            FormDataModel destinationCity = new FormDataModel()
                            {
                                formType = FromTypeEnum.textField.ToName(),
                                value = travelData.DestinationCity,
                                title = "目的城市",
                                placeHolder = "请输入城市",
                                required = true,
                                key = "destinationCity"
                            };
                            travelFormList.Add(destinationCity);
                            FormDataModel startTime = new FormDataModel()
                            {
                                formType = FromTypeEnum.DateTimeField.ToName(),
                                value = travelData.StartTime.ToString(),
                                title = "开始时间",
                                placeHolder = "开始时间",
                                required = true,
                                key = "startTime"
                            };
                            travelFormList.Add(startTime);
                            FormDataModel endTime = new FormDataModel()
                            {
                                formType = FromTypeEnum.DateTimeField.ToName(),
                                value = travelData.EndTime.ToString(),
                                title = "结束时间",
                                placeHolder = "结束时间",
                                required = true,
                                key = "endTime"
                            };
                            travelFormList.Add(endTime);
                            FormDataModel duration = new FormDataModel()
                            {
                                formType = FromTypeEnum.DurationField.ToName(),
                                value = travelData.Duration,
                                title = "时长(天数)",
                                placeHolder = "时长",
                                required = true,
                                key = "duration"
                            };
                            travelFormList.Add(duration);
                        }
                    }
                    else
                    {
                        List<FormDataModel> travelFormList = new List<FormDataModel>();
                        allTravelFormList.Add(travelFormList);
                        List<Dictionary<string, int>> vehicleCategoryList = new List<Dictionary<string, int>>();
                        foreach (var item in EnumHelper.EnumToList(typeof(TravelVehicleEnum)))
                        {
                            Dictionary<string, int> dic = new Dictionary<string, int>
                            {
                                { item.Name, Convert.ToInt32(item.Id) }
                            };
                            vehicleCategoryList.Add(dic);
                        }
                        FormDataModel vehicle = new FormDataModel()
                        {
                            formType = FromTypeEnum.Selectfield.ToName(),
                            value = "",
                            title = "交通工具",
                            required = true,
                            key = "vehicle",
                            category = vehicleCategoryList
                        };
                        travelFormList.Add(vehicle);
                        List<Dictionary<string, int>> typeCategoryList = new List<Dictionary<string, int>>();
                        foreach (var item in EnumHelper.EnumToList(typeof(TravelVehicleTypeEnum)))
                        {
                            Dictionary<string, int> dic = new Dictionary<string, int>
                            {
                                { item.Name, Convert.ToInt32(item.Id) }
                            };
                            typeCategoryList.Add(dic);
                        }
                        FormDataModel type = new FormDataModel()
                        {
                            formType = FromTypeEnum.Selectfield.ToName(),
                            value = "",
                            title = "单程往返",
                            required = true,
                            key = "type",
                            category = typeCategoryList
                        };
                        travelFormList.Add(type);
                        FormDataModel departCity = new FormDataModel()
                        {
                            formType = FromTypeEnum.textField.ToName(),
                            value = "",
                            title = "出发城市",
                            placeHolder = "请输入城市",
                            required = true,
                            key = "departCity"
                        };
                        travelFormList.Add(departCity);
                        FormDataModel destinationCity = new FormDataModel()
                        {
                            formType = FromTypeEnum.textField.ToName(),
                            value = "",
                            title = "目的城市",
                            placeHolder = "请输入城市",
                            required = true,
                            key = "destinationCity"
                        };
                        travelFormList.Add(destinationCity);
                        FormDataModel startTime = new FormDataModel()
                        {
                            formType = FromTypeEnum.DateTimeField.ToName(),
                            value = "",
                            title = "开始时间",
                            placeHolder = "开始时间",
                            required = true,
                            key = "startTime"
                        };
                        travelFormList.Add(startTime);
                        FormDataModel endTime = new FormDataModel()
                        {
                            formType = FromTypeEnum.DateTimeField.ToName(),
                            value = "",
                            title = "结束时间",
                            placeHolder = "结束时间",
                            required = true,
                            key = "endTime"
                        };
                        travelFormList.Add(endTime);
                        FormDataModel duration = new FormDataModel()
                        {
                            formType = FromTypeEnum.DurationField.ToName(),
                            value = "",
                            title = "时长(天数)",
                            placeHolder = "时长",
                            required = true,
                            key = "duration"
                        };
                        travelFormList.Add(duration);
                    }

                }
                #endregion
                formList.Add(travel);
            }
            #endregion

            FormDataModel traveldays = new FormDataModel()
            {
                formType = FromTypeEnum.TotalDurationField.ToName(),
                value = evection == null ? 0 : evection.Traveldays,
                title = "出差天数",
                placeHolder = "出差天数",
                required = true,
                key = "traveldays"
            };
            formList.Add(traveldays);
            FormDataModel remark = new FormDataModel()
            {
                formType = FromTypeEnum.TextareaField.ToName(),
                value = evection == null ? "" : evection.Remark,
                title = "出差备注",
                placeHolder = "请输入出具体出差备注",
                key = "remark"
            };
            formList.Add(remark);

            return ApiResult.Success("获取成功", data: formList);
        }

        /// <summary>
        /// 获取外出模板
        /// </summary>
        /// <returns></returns>
        public ApiResult GooutTemplate()
        {

            int empId = Convert.ToInt32(RequestParm.Uid);
            List<Rb_Workflow_Template_Extend> wfTemplateList = workFlowModule.GetTemplateByEmpId(empId);
            if (wfTemplateList.Where(t => (int)t.TemplateType == (int)WFTTemplateTypeEnum.Goout).ToList().Count == 0)
            {
                return ApiResult.Failed(message: "该模板暂未启用");
            }
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int workFlowId = JsonHelper.GetInt(parm, "workFlowId");
            var goOut = workFlowModule.GetGoOut(workFlowId);
            List<FormDataModel> formList = new List<FormDataModel>();
            FormDataModel startTime = new FormDataModel()
            {
                formType = FromTypeEnum.DateTimeField.ToName(),
                value = goOut == null ? "" : goOut.StartTime.ToString(),
                title = "开始时间",
                placeHolder = "开始时间",
                required = true,
                key = "startTime"
            };
            formList.Add(startTime);
            FormDataModel endTime = new FormDataModel()
            {
                formType = FromTypeEnum.DateTimeField.ToName(),
                value = goOut == null ? "" : goOut.EndTime.ToString(),
                title = "结束时间",
                placeHolder = "结束时间",
                required = true,
                key = "endTime"
            };
            formList.Add(endTime);
            FormDataModel duration = new FormDataModel()
            {
                formType = FromTypeEnum.DurationField.ToName(),
                value = goOut == null ? 0 : goOut.Duration,
                title = "时长",
                placeHolder = "时长",
                required = true,
                key = "duration"
            };
            formList.Add(duration);
            FormDataModel description = new FormDataModel()
            {
                formType = FromTypeEnum.TextareaField.ToName(),
                value = goOut == null ? "" : goOut.Description,
                title = "外出事由",
                placeHolder = "请输入外出事由",
                required = true,
                key = "description"
            };
            formList.Add(description);
            if (goOut != null && !string.IsNullOrWhiteSpace(goOut.Image))
            {
                List<string> imgList = JsonConvert.DeserializeObject<List<string>>(goOut.Image);
                List<string> resultImgList = new List<string>();
                foreach (var item in imgList)
                {
                    resultImgList.Add(Config.GetOssFileUrl + item);
                }
                FormDataModel image = new FormDataModel()
                {
                    formType = FromTypeEnum.ImageField.ToName(),
                    value = resultImgList,
                    title = "图片",
                    key = "images"
                };
                formList.Add(image);
            }
            else
            {
                FormDataModel image = new FormDataModel()
                {
                    formType = FromTypeEnum.ImageField.ToName(),
                    value = "",
                    title = "图片",
                    key = "images"
                };
                formList.Add(image);
            }
            return ApiResult.Success("获取成功", data: formList);
        }

        /// <summary>
        /// 获取补卡模板
        /// </summary>
        /// <returns></returns>
        public ApiResult ReissueCardTemplate()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<Rb_Workflow_Template_Extend> wfTemplateList = workFlowModule.GetTemplateByEmpId(empId);
            if (wfTemplateList.Where(t => (int)t.TemplateType == (int)WFTTemplateTypeEnum.ReissueCard).ToList().Count == 0)
            {
                return ApiResult.Failed(message: "该模板暂未启用");
            }
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int workFlowId = JsonHelper.GetInt(parm, "workFlowId");
            string cardTime = JsonHelper.GetStringValue(parm, "reissueCardTime");
            var reissuecard = workFlowModule.GetReissuecard(workFlowId);
            List<FormDataModel> formList = new List<FormDataModel>();
            if (string.IsNullOrWhiteSpace(cardTime))
            {
                FormDataModel reissueCardTime = new FormDataModel()
                {
                    formType = FromTypeEnum.DateTimeField.ToName(),
                    value = reissuecard == null ? "" : reissuecard.ReissueCardTime.ToString(),
                    title = "补卡时间",
                    placeHolder = "补卡时间",
                    required = true,
                    key = "reissueCardTime"
                };
                formList.Add(reissueCardTime);
            }
            else
            {
                FormDataModel reissueCardTime = new FormDataModel()
                {
                    formType = FromTypeEnum.DateTimeField.ToName(),
                    value = cardTime,
                    title = "补卡时间",
                    placeHolder = "补卡时间",
                    required = true,
                    key = "reissueCardTime"
                };
                formList.Add(reissueCardTime);
            }
            FormDataModel description = new FormDataModel()
            {
                formType = FromTypeEnum.TextareaField.ToName(),
                value = reissuecard == null ? "" : reissuecard.Description,
                title = "缺卡原因",
                placeHolder = "请输入缺卡原因",
                required = true,
                key = "description"
            };
            formList.Add(description);


            if (reissuecard != null && !string.IsNullOrWhiteSpace(reissuecard.Image))
            {
                List<string> imgList = JsonConvert.DeserializeObject<List<string>>(reissuecard.Image);
                List<string> resultImgList = new List<string>();
                foreach (var item in imgList)
                {
                    resultImgList.Add(Config.GetOssFileUrl + item);
                }
                FormDataModel image = new FormDataModel()
                {
                    formType = FromTypeEnum.ImageField.ToName(),
                    value = resultImgList,
                    title = "图片",
                    key = "images"
                };
                formList.Add(image);
            }
            else
            {
                FormDataModel image = new FormDataModel()
                {
                    formType = FromTypeEnum.ImageField.ToName(),
                    value = "",
                    title = "图片",
                    key = "images"
                };
                formList.Add(image);
            }
            return ApiResult.Success("获取成功", data: formList);
        }
        #endregion

        #region 提交审核申请

        /// <summary>
        /// 计算时长
        /// </summary>
        /// <returns></returns>
        public ApiResult CalculateDuration()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            Rb_Workflow_Askforleave_Extend askforleave = JsonConvert.DeserializeObject<Rb_Workflow_Askforleave_Extend>(RequestParm.Msg.ToString());
            if (askforleave.StartTime != null && string.IsNullOrWhiteSpace(askforleave.StartTime.ToString()))
            {
                return ApiResult.Failed("开始时间不能为空");
            }
            if (askforleave.EndTime != null && string.IsNullOrWhiteSpace(askforleave.EndTime.ToString()))
            {
                return ApiResult.Failed("结束时间不能为空");
            }
            if (askforleave.EndTime < askforleave.StartTime)
            {
                return ApiResult.Failed("结束时间不能小于开始时间");
            }
            //if (string.IsNullOrWhiteSpace(askforleave.LunchTime)) {
            //    return ApiResult.Failed("午休时间未设置！");
            //}
            //获取设置的午休时间
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            string lunchTime = workFlowModule.GetLunchTime(userInfo.Group_Id, "SK_AskForLeaveSet_LunchBreak");
            askforleave.LunchTime = lunchTime;
            var data = new { duration = workFlowModule.CalculateDuration(empId, askforleave.TemplateId.Value, askforleave.StartTime.Value, askforleave.EndTime.Value, askforleave.LunchTime) };

            return ApiResult.Success("获取成功", data: data);
        }
        /// <summary>
        /// 提交请假申请
        /// </summary>
        /// <returns></returns>
        public ApiResult AskForLeaveSubmit()
        {
            //RequestParm.Uid = "1972";
            int empId = Convert.ToInt32(RequestParm.Uid);
            Rb_Workflow_Askforleave_Extend askforleave = JsonConvert.DeserializeObject<Rb_Workflow_Askforleave_Extend>(RequestParm.Msg.ToString());
            if (askforleave.StartTime > askforleave.EndTime)
            {
                return ApiResult.Failed("开始时间不能大于结束时间");
            }
            if (askforleave.Duration <= 0)
            {
                return ApiResult.Failed("请假时长必须大于0");
            }
            //获取设置的午休时间
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            string lunchTime = workFlowModule.GetLunchTime(userInfo.Group_Id, "SK_AskForLeaveSet_LunchBreak");
            if (!string.IsNullOrWhiteSpace(lunchTime))
            {
                string[] lunchArr = lunchTime.Split('-');
                string StartT = askforleave.StartTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[0];//开始午休开始时间
                string StartE = askforleave.StartTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[1];//开始午休结束时间
                string EndT = askforleave.EndTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[0];//结束午休开始时间
                string EndE = askforleave.EndTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[1];//结束午休结束时间
                if (askforleave.StartTime > Convert.ToDateTime(StartT) && askforleave.StartTime < Convert.ToDateTime(StartE))
                {
                    //重新规范赋值
                    askforleave.StartTime = Convert.ToDateTime(StartE);
                }
                if (askforleave.EndTime > Convert.ToDateTime(EndT) && askforleave.EndTime < Convert.ToDateTime(EndE))
                {
                    //重新规范赋值
                    askforleave.EndTime = Convert.ToDateTime(EndT);
                }
            }
            askforleave.CreateBy = empId;
            return workFlowModule.AskForLeaveSubmit(askforleave);
        }

        /// <summary>
        /// 提交出差申请
        /// </summary>
        /// <returns></returns>
        public ApiResult EvectionSubmit()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            Rb_Workflow_Evection_Extend evection = JsonConvert.DeserializeObject<Rb_Workflow_Evection_Extend>(RequestParm.Msg.ToString());
            if (evection.Traveldays <= 0)
            {
                return ApiResult.Failed("出差天数必须大于0");
            }
            if (evection.Travel.Count > 0)
            {
                //获取设置的午休时间
                UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
                string lunchTime = workFlowModule.GetLunchTime(userInfo.Group_Id, "SK_AskForLeaveSet_LunchBreak");
                foreach (var item in evection.Travel)
                {
                    if (!string.IsNullOrWhiteSpace(lunchTime))
                    {
                        string[] lunchArr = lunchTime.Split('-');
                        string StartT = item.StartTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[0];//开始午休开始时间
                        string StartE = item.StartTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[1];//开始午休结束时间
                        string EndT = item.EndTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[0];//结束午休开始时间
                        string EndE = item.EndTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[1];//结束午休结束时间
                        if (item.StartTime > Convert.ToDateTime(StartT) && item.StartTime < Convert.ToDateTime(StartE))
                        {
                            //重新规范赋值
                            item.StartTime = Convert.ToDateTime(StartE);
                        }
                        if (item.EndTime > Convert.ToDateTime(EndT) && item.EndTime < Convert.ToDateTime(EndE))
                        {
                            //重新规范赋值
                            item.EndTime = Convert.ToDateTime(EndT);
                        }
                    }
                }
            }
            else
            {
                return ApiResult.Failed("行程为空");
            }
            evection.CreateBy = empId;
            return workFlowModule.EvectionSubmit(evection);
        }

        /// <summary>
        /// 提交外出申请
        /// </summary>
        /// <returns></returns>
        public ApiResult GooutSubmit()
        {

            int empId = Convert.ToInt32(RequestParm.Uid);
            Rb_Workflow_GoOut_Extend goOut = JsonConvert.DeserializeObject<Rb_Workflow_GoOut_Extend>(RequestParm.Msg.ToString());
            if (goOut.Duration <= 0)
            {
                return ApiResult.Failed("外出时长必须大于0");
            }
            //获取设置的午休时间
            UserInfo userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            string lunchTime = workFlowModule.GetLunchTime(userInfo.Group_Id, "SK_AskForLeaveSet_LunchBreak");
            if (!string.IsNullOrWhiteSpace(lunchTime))
            {
                string[] lunchArr = lunchTime.Split('-');
                string StartT = goOut.StartTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[0];//开始午休开始时间
                string StartE = goOut.StartTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[1];//开始午休结束时间
                string EndT = goOut.EndTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[0];//结束午休开始时间
                string EndE = goOut.EndTime.Value.ToString("yyyy-MM-dd") + " " + lunchArr[1];//结束午休结束时间
                if (goOut.StartTime > Convert.ToDateTime(StartT) && goOut.StartTime < Convert.ToDateTime(StartE))
                {
                    //重新规范赋值
                    goOut.StartTime = Convert.ToDateTime(StartE);
                }
                if (goOut.EndTime > Convert.ToDateTime(EndT) && goOut.EndTime < Convert.ToDateTime(EndE))
                {
                    //重新规范赋值
                    goOut.EndTime = Convert.ToDateTime(EndT);
                }
            }
            goOut.CreateBy = empId;
            return workFlowModule.GooutSubmit(goOut);
        }

        /// <summary>
        /// 提交补卡申请
        /// </summary>
        /// <returns></returns>
        public ApiResult ReissueCardSubmit()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            Rb_Workflow_Reissuecard_Extend reissuecard = JsonConvert.DeserializeObject<Rb_Workflow_Reissuecard_Extend>(RequestParm.Msg.ToString());
            reissuecard.CreateBy = empId;
            if (reissuecard.TemplateId == 0)
            {
                Rb_Workflow_Template_Extend wfTemplate = workFlowModule.GetTemplateByEmpId(empId).Where(t => (int)t.TemplateType == (int)WFTTemplateTypeEnum.ReissueCard).FirstOrDefault();
                if (wfTemplate != null)
                {
                    reissuecard.TemplateId = wfTemplate.Id;
                }
                else
                {
                    return ApiResult.Failed(message: "该模板暂未启用");
                }
            }
            return workFlowModule.ReissueCardSubmit(reissuecard);
        }
        #endregion

        #region 审核详情
        /// <summary>
        /// 获取申请单详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetAuditInfo()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int WorkFlowId = parm.GetInt("WorkFlowId", 0);
            int TemplateType = parm.GetInt("TemplateType", 0);
            int LogId = parm.GetInt("SysLogId", 0);
            if (WorkFlowId <= 0)
            {
                return ApiResult.ParamIsNull("参数WorkFlowId有误，请核实后再试！");
            }
            if (TemplateType <= 0)
            {
                return ApiResult.ParamIsNull("参数TemplateType有误，请核实后再试！");
            }
            if (LogId > 0)
            {
                //syspushModule.UpdateReadStatus(LogId);//更新日志阅读状态
            }
            List<AuditInfoModel> aiList = new List<AuditInfoModel>();
            string Proposer = "", ProposerPhoto = "", StatusStr = "", ProposerTime = "", DepartmentName = "", TempleteTypeName = "", Cmd = "", SubmitCmd = "", AttendanceRecordId = "", ReissuecardType = "";
            int Status = 1, CreateBy = 0, TempleteId = 0;
            AuditInfoModel aimodel = new AuditInfoModel() { };
            switch (TemplateType)
            {
                case (int)WFTTemplateTypeEnum.AskForLeave:
                    Rb_Workflow_Askforleave_Extend askmodel = workFlowModule.GetAskforleaveModel(WorkFlowId);
                    if (askmodel == null)
                    {
                        return ApiResult.Failed("参数有误，请核实后再试！");
                    }
                    TempleteTypeName = "请假申请单";
                    if (askmodel.IsCancel == WFAuditCancelStatus.Cancel)
                    {
                        TempleteTypeName += "(撤回)";
                    }
                    string EnumStr = Common.Plugin.EnumHelper.ToName(WFTTemplateTypeEnum.AskForLeave);
                    if (EnumStr.Split('|').Length > 4)
                    {
                        Cmd = EnumStr.Split('|')[3];
                        SubmitCmd = EnumStr.Split('|')[4];
                    }
                    TempleteId = askmodel.TemplateId ?? 0;
                    Proposer = askmodel.EmName;
                    ProposerPhoto = Config.GetFileUrl(askmodel.EmPhoto);
                    StatusStr = askmodel.Status.ToName();
                    Status = (int)askmodel.Status;
                    CreateBy = askmodel.CreateBy ?? 0;
                    ProposerTime = askmodel.CreateTime.HasValue ? askmodel.CreateTime.Value.ToString("yyyy-MM-dd HH:mm") : "";
                    //获取申请人所在部门
                    DepartmentName = workFlowModule.GetDepartmentForEmplyoeeId(CreateBy);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "审批编号",
                        value = WorkFlowId
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "所在部门",
                        value = DepartmentName
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "请假类型",
                        value = askmodel.AskforleaveType.ToName()
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "开始时间",
                        value = askmodel.StartTime.HasValue ? askmodel.StartTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "结束时间",
                        value = askmodel.EndTime.HasValue ? askmodel.EndTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "时长(小时)",
                        value = askmodel.Duration
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "请假事由",
                        value = askmodel.Description
                    };
                    aiList.Add(aimodel);
                    if (!string.IsNullOrWhiteSpace(askmodel.Image))
                    {
                        List<string> ImageList = JsonConvert.DeserializeObject<List<string>>(askmodel.Image);
                        for (var i = 0; i < ImageList.Count; i++)
                        {
                            ImageList[i] = Config.GetFileUrl(ImageList[i]);
                        }
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.Image.ToName(),
                            title = "图片",
                            value = ImageList
                        };
                        aiList.Add(aimodel);
                    }
                    break;
                case (int)WFTTemplateTypeEnum.Evection:
                    Rb_Workflow_Evection_Extend evemodel = workFlowModule.GetEvectionModel(WorkFlowId);
                    if (evemodel == null)
                    {
                        return ApiResult.Failed("参数有误，请核实后再试！");
                    }
                    TempleteTypeName = "出差申请单";
                    if (evemodel.IsCancel == WFAuditCancelStatus.Cancel)
                    {
                        TempleteTypeName += "(撤回)";
                    }
                    EnumStr = Common.Plugin.EnumHelper.ToName(WFTTemplateTypeEnum.Evection);
                    if (EnumStr.Split('|').Length > 4)
                    {
                        Cmd = EnumStr.Split('|')[3];
                        SubmitCmd = EnumStr.Split('|')[4];
                    }
                    TempleteId = evemodel.TemplateId ?? 0;
                    Proposer = evemodel.EmName;
                    ProposerPhoto = Config.GetFileUrl(evemodel.EmPhoto);
                    StatusStr = evemodel.Status.ToName();
                    Status = (int)evemodel.Status;
                    CreateBy = evemodel.CreateBy ?? 0;
                    ProposerTime = evemodel.CreateTime.HasValue ? evemodel.CreateTime.Value.ToString("yyyy-MM-dd HH:mm") : "";
                    //获取申请人所在部门
                    DepartmentName = workFlowModule.GetDepartmentForEmplyoeeId(CreateBy);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "审批编号",
                        value = WorkFlowId
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "所在部门",
                        value = DepartmentName
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "出差事由",
                        value = evemodel.Description
                    };
                    aiList.Add(aimodel);
                    List<Rb_Workflow_Travel_Extend> TravelList = workFlowModule.GetTravelListForEvection(WorkFlowId);
                    List<object> Rtrave = new List<object>();
                    List<AuditInfoModel> trList = new List<AuditInfoModel>();
                    foreach (var item in TravelList)
                    {
                        trList = new List<AuditInfoModel>();
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.String.ToName(),
                            title = "交通工具",
                            value = item.Vehicle.ToName()
                        };
                        trList.Add(aimodel);
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.String.ToName(),
                            title = "单程往返",
                            value = item.Type.ToName()
                        };
                        trList.Add(aimodel);
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.String.ToName(),
                            title = "出发城市",
                            value = item.DepartCity
                        };
                        trList.Add(aimodel);
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.String.ToName(),
                            title = "目的城市",
                            value = item.DestinationCity
                        };
                        trList.Add(aimodel);
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.String.ToName(),
                            title = "开始时间",
                            value = item.StartTime.HasValue ? item.StartTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                        };
                        trList.Add(aimodel);
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.String.ToName(),
                            title = "结束时间",
                            value = item.EndTime.HasValue ? item.EndTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                        };
                        trList.Add(aimodel);
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.String.ToName(),
                            title = "时长（天）",
                            value = item.Duration
                        };
                        trList.Add(aimodel);
                        Rtrave.Add(trList);
                    }
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.Json.ToName(),
                        title = "行程",
                        value = Rtrave
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "出差天数",
                        value = evemodel.Traveldays
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "出差备注",
                        value = evemodel.Remark
                    };
                    aiList.Add(aimodel);
                    break;
                case (int)WFTTemplateTypeEnum.Goout:
                    Rb_Workflow_GoOut_Extend gooutmodel = workFlowModule.GetGooutModel(WorkFlowId);
                    if (gooutmodel == null)
                    {
                        return ApiResult.Failed("参数有误，请核实后再试！");
                    }
                    TempleteTypeName = "外出申请单";
                    if (gooutmodel.IsCancel == WFAuditCancelStatus.Cancel)
                    {
                        TempleteTypeName += "(撤回)";
                    }
                    EnumStr = Common.Plugin.EnumHelper.ToName(WFTTemplateTypeEnum.Goout);
                    if (EnumStr.Split('|').Length > 4)
                    {
                        Cmd = EnumStr.Split('|')[3];
                        SubmitCmd = EnumStr.Split('|')[4];
                    }
                    TempleteId = gooutmodel.TemplateId ?? 0;
                    Proposer = gooutmodel.EmName;
                    ProposerPhoto = Config.GetFileUrl(gooutmodel.EmPhoto);
                    StatusStr = gooutmodel.Status.ToName();
                    Status = (int)gooutmodel.Status;
                    CreateBy = gooutmodel.CreateBy ?? 0;
                    ProposerTime = gooutmodel.CreateTime.HasValue ? gooutmodel.CreateTime.Value.ToString("yyyy-MM-dd HH:mm") : "";
                    //获取申请人所在部门
                    DepartmentName = workFlowModule.GetDepartmentForEmplyoeeId(CreateBy);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "审批编号",
                        value = WorkFlowId
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "所在部门",
                        value = DepartmentName
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "开始时间",
                        value = gooutmodel.StartTime.HasValue ? gooutmodel.StartTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "结束时间",
                        value = gooutmodel.EndTime.HasValue ? gooutmodel.EndTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "时长(小时)",
                        value = gooutmodel.Duration
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "外出事由",
                        value = gooutmodel.Description
                    };
                    aiList.Add(aimodel);

                    if (!string.IsNullOrWhiteSpace(gooutmodel.Image))
                    {
                        List<string> ImageList = JsonConvert.DeserializeObject<List<string>>(gooutmodel.Image);
                        for (var i = 0; i < ImageList.Count; i++)
                        {
                            ImageList[i] = Config.GetFileUrl(ImageList[i]);
                        }
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.Image.ToName(),
                            title = "图片",
                            value = ImageList
                        };
                        aiList.Add(aimodel);
                    }
                    break;
                case (int)WFTTemplateTypeEnum.ReissueCard:
                    Rb_Workflow_Reissuecard_Extend ReissueCardmodel = workFlowModule.GetReissuecarModel(WorkFlowId);
                    if (ReissueCardmodel == null)
                    {
                        return ApiResult.Failed("参数有误，请核实后再试！");
                    }
                    TempleteTypeName = "补卡申请单";
                    if (ReissueCardmodel.IsCancel == WFAuditCancelStatus.Cancel)
                    {
                        TempleteTypeName += "(撤回)";
                    }
                    EnumStr = Common.Plugin.EnumHelper.ToName(WFTTemplateTypeEnum.ReissueCard);
                    if (EnumStr.Split('|').Length > 4)
                    {
                        Cmd = EnumStr.Split('|')[3];
                        SubmitCmd = EnumStr.Split('|')[4];
                    }
                    AttendanceRecordId = ReissueCardmodel.AttendanceRecordId.HasValue ? ReissueCardmodel.AttendanceRecordId.Value.ToString() : "";
                    ReissuecardType = ReissueCardmodel.ReissuecardType.HasValue ? ReissueCardmodel.ReissuecardType.Value.ToString() : "";
                    TempleteId = ReissueCardmodel.TemplateId ?? 0;
                    Proposer = ReissueCardmodel.EmName;
                    ProposerPhoto = Config.GetFileUrl(ReissueCardmodel.EmPhoto);
                    StatusStr = ReissueCardmodel.Status.ToName();
                    Status = (int)ReissueCardmodel.Status;
                    CreateBy = ReissueCardmodel.CreateBy ?? 0;
                    ProposerTime = ReissueCardmodel.CreateTime.HasValue ? ReissueCardmodel.CreateTime.Value.ToString("yyyy-MM-dd HH:mm") : "";
                    //获取申请人所在部门
                    DepartmentName = workFlowModule.GetDepartmentForEmplyoeeId(CreateBy);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "审批编号",
                        value = WorkFlowId
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "所在部门",
                        value = DepartmentName
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "补卡时间",
                        value = ReissueCardmodel.ReissueCardTime.HasValue ? ReissueCardmodel.ReissueCardTime.Value.ToString("yyyy-MM-dd HH:mm") : ""
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "补卡类型",
                        value = ReissueCardmodel.ReissuecardType == 1 ? "上班补卡" : "下班补卡"
                    };
                    aiList.Add(aimodel);
                    aimodel = new AuditInfoModel()
                    {
                        formType = AuditInfoTypeEnum.String.ToName(),
                        title = "缺卡原因",
                        value = ReissueCardmodel.Description
                    };
                    aiList.Add(aimodel);
                    if (!string.IsNullOrWhiteSpace(ReissueCardmodel.Image))
                    {
                        List<string> ImageList = JsonConvert.DeserializeObject<List<string>>(ReissueCardmodel.Image);
                        for (var i = 0; i < ImageList.Count; i++)
                        {
                            ImageList[i] = Config.GetFileUrl(ImageList[i]);
                        }
                        aimodel = new AuditInfoModel()
                        {
                            formType = AuditInfoTypeEnum.Image.ToName(),
                            title = "图片",
                            value = ImageList
                        };
                        aiList.Add(aimodel);
                    }
                    break;
            }

            //获取所有的审核流程
            int IsCancel = 2;
            int IsAudit = 2;
            int IsUpdate = 2;
            List<Rb_Workflow_AuditRelevance_Extend> arList = workFlowModule.GetAuditRecordList(WorkFlowId, TemplateType);
            if (empId == CreateBy && !TempleteTypeName.Contains("撤回") && Status != (int)WFAuditStatus.ToWithdraw && Status != (int)WFAuditStatus.NotThrough)
            {//第一个审核  并且审核人是自己  可以有撤回  /如果是撤回状态就不行了
                IsCancel = 1;
            }
            if (Status == (int)WFAuditStatus.InReview)
            {
                if (empId == CreateBy && !TempleteTypeName.Contains("撤回"))
                {
                    IsUpdate = 1;
                }
                if (arList.Count > 0)
                {
                    var arModel = arList.Where(x => x.Stauts == WFRrocessStatus.NotAudit).FirstOrDefault();
                    if (arModel != null)
                    {
                        int count = arModel.AuditRecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == empId).Count();
                        if (count > 0)
                            IsAudit = 1;
                    }
                }
            }
            //获取抄送人列表
            List<Rb_Workflow_CopyToPeople_Extend> CopyToPeopleList = new List<Rb_Workflow_CopyToPeople_Extend>();
            if (Status == (int)WFAuditStatus.Through)
            {
                CopyToPeopleList = workFlowModule.GetCopyToPeopleList(WorkFlowId, TemplateType);
            }
            return ApiResult.Success("", new
            {
                TempleteTypeName,
                Cmd,
                SubmitCmd,
                WorkFlowId,
                TemplateType,
                Proposer,
                ProposerId = CreateBy,
                ProposerPhoto,
                Status = StatusStr,
                AuditStatus = Status,
                ProposerTime,
                Details = aiList,
                arList = arList.Select(x => new
                {
                    AuditDescription = x.AuditDescription + "审核",
                    x.Sort,
                    AuditWay = x.AuditWay.HasValue ? x.AuditWay.Value > 0 ? Common.Plugin.EnumHelper.ToName((WFTAuditWayEnum)x.AuditWay.Value) : "" : "",
                    AuditWayStatus = x.AuditWay.HasValue ? x.AuditWay.Value > 0 ? (int)x.AuditWay.Value : 1 : 1,
                    AuditRecordList = x.AuditRecordList.Select(y => new
                    {
                        y.AuditEmName,
                        Stauts = y.AuditStatus == WFRrocessStatus.Rejected ? "" : y.AuditStatus.ToName(),
                        AuditStauts = (int)y.AuditStatus,
                        StatusColor = GetStatusColor(y.AuditStatus),
                        y.Description,
                        Image = GetImagePath(y.Image),
                        AuditEmPhoto = y.AuditEmPhoto == "" ? "" : Config.GetFileUrl(y.AuditEmPhoto),
                        AuditTime = y.AuditStatus == WFRrocessStatus.NotAudit ? "" : y.AuditStatus == WFRrocessStatus.Rejected ? "" : y.UpdateTime.HasValue ? y.UpdateTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                        CareOfList = JsonConvert.DeserializeObject<List<SetCareOfModel>>(y.CareOfRemarks ?? "")
                    })
                }),
                IsAudit,
                IsCancel,
                IsUpdate,
                TempleteId,
                AttendanceRecordId,
                ReissuecardType,
                CopyToPeopleList = CopyToPeopleList.Select(x => new
                {
                    x.EmName,
                    EmPhoto = x.EmPhoto == "" ? "" : Config.GetFileUrl(x.EmPhoto),
                    x.EmployeeId
                })
            });
        }
        /// <summary>
        /// 获取列表图片全地址
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string GetImagePath(string path)
        {
            path = path ?? "[]";
            path = path == "" ? "[]" : path;
            string[] pathstr = JsonConvert.DeserializeObject<string[]>(path);
            List<string> pathList = new List<string>();
            foreach (string item in pathstr)
            {
                string Newpath = Config.GetFileUrl(item);
                pathList.Add(Newpath);
            }
            return JsonConvert.SerializeObject(pathList);
        }
        /// <summary>
        /// 获取审核状态的颜色
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public string GetStatusColor(WFRrocessStatus? status)
        {
            string color = "";
            switch (status)
            {
                case WFRrocessStatus.NotAudit: color = "#257BF1"; break;
                case WFRrocessStatus.AuditNotThrough: color = "#F73939"; break;
                case WFRrocessStatus.AuditThrough: color = "#00B06C"; break;
                default: color = "#257BF1"; break;
            }
            return color;
        }

        /// <summary>
        /// 审核  同意
        /// </summary>
        /// <returns></returns>
        public ApiResult SetConsent()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int WorkFlowId = parm.GetInt("WorkFlowId", 0);
            int TemplateType = parm.GetInt("TemplateType", 0);
            string Description = parm.GetStringValue("Description");
            string ImageStr = parm.GetStringValue("Image");
            if (WorkFlowId <= 0)
            {
                return ApiResult.ParamIsNull("参数WorkFlowId有误，请核实后再试！");
            }
            if (TemplateType <= 0)
            {
                return ApiResult.ParamIsNull("参数TemplateType有误，请核实后再试！");
            }
            return workFlowModule.SetConsent(WorkFlowId, TemplateType, empId, Description, ImageStr);
        }
        /// <summary>
        /// 审核  拒绝
        /// </summary>
        /// <returns></returns>
        public ApiResult SetNotConsent()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int WorkFlowId = parm.GetInt("WorkFlowId", 0);
            int TemplateType = parm.GetInt("TemplateType", 0);
            string Description = parm.GetStringValue("Description");
            string ImageStr = parm.GetStringValue("Image");
            if (WorkFlowId <= 0)
            {
                return ApiResult.ParamIsNull("参数WorkFlowId有误，请核实后再试！");
            }
            if (TemplateType <= 0)
            {
                return ApiResult.ParamIsNull("参数TemplateType有误，请核实后再试！");
            }
            return workFlowModule.SetNotConsent(WorkFlowId, TemplateType, empId, Description, ImageStr);
        }
        /// <summary>
        /// 审核  转交
        /// </summary>
        /// <returns></returns>
        public ApiResult SetCareOf()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int WorkFlowId = parm.GetInt("WorkFlowId", 0);
            int TemplateType = parm.GetInt("TemplateType", 0);
            string Description = parm.GetStringValue("Description");
            int CareOfEmId = parm.GetInt("CareOfEmId", 0);
            if (WorkFlowId <= 0)
            {
                return ApiResult.ParamIsNull("参数WorkFlowId有误，请核实后再试！");
            }
            if (TemplateType <= 0)
            {
                return ApiResult.ParamIsNull("参数TemplateType有误，请核实后再试！");
            }
            if (CareOfEmId <= 0)
            {
                return ApiResult.ParamIsNull("参数CareOfEmId值有误，请核实后再试！");
            }
            return workFlowModule.SetCareOf(WorkFlowId, TemplateType, empId, Description, CareOfEmId);
        }
        #endregion


        /// <summary>
        /// 获取审批类型
        /// </summary>
        /// <returns></returns>
        public ApiResult GetWfTmplateType()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<Rb_Workflow_Template_Extend> wfTemplateList = workFlowModule.GetTemplateByEmpId(empId);
            var dicTemplate = EnumHelper.EnumToList(typeof(WFTTemplateTypeEnum));
            List<Dictionary<string, int>> TemplateList = new List<Dictionary<string, int>>();
            Dictionary<string, int> dicTemplateData = new Dictionary<string, int>();
            TemplateList.Add(new Dictionary<string, int> { { "全部", 0 } });
            foreach (var item in dicTemplate)
            {
                string[] tempTypeStr = item.Name.Split('|');
                if (tempTypeStr.Length > 1)
                {
                    TemplateList.Add(new Dictionary<string, int> { { item.Name.Split('|')[0], Convert.ToInt32(item.Id) } });
                }
            }
            return ApiResult.Success(message: "获取成功", data: TemplateList);
        }
        /// <summary>
        /// 获取我发起的审核状态
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMyInitiateAuditStatus()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            List<Rb_Workflow_Template_Extend> wfTemplateList = workFlowModule.GetTemplateByEmpId(empId);
            var dicAuditStatus = EnumHelper.EnumToList(typeof(AppAuditStatusEnum));
            List<Dictionary<string, int>> auditStatusList = new List<Dictionary<string, int>>();
            foreach (var item in dicAuditStatus)
            {
                auditStatusList.Add(new Dictionary<string, int> { { item.Name, Convert.ToInt32(item.Id) } });
            }
            return ApiResult.Success(message: "获取成功", data: auditStatusList);
        }

        /// <summary>
        /// 我的审批
        /// </summary>
        /// <returns></returns>
        public ApiResult MyAudit()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            // 搜索关键字
            string searchKey = JsonHelper.GetStringValue(parm, "searchKey");
            // 1待我审批，2我已审批的
            int auditType = JsonHelper.GetInt(parm, "auditType");
            // app审批状态
            int appAuditStatus = JsonHelper.GetInt(parm, "appAuditStatus");
            //申请筛选模板类型
            int applyType = JsonHelper.GetInt(parm, "applyType");
            int pageIndex = JsonHelper.GetInt(parm, "pageIndex");
            int pageSize = JsonHelper.GetInt(parm, "pageSize");
            var data = workFlowModule.MyAudit(searchKey, empId, (AppAuditStatusEnum)appAuditStatus, auditType, applyType, pageIndex, pageSize, out long rowCount);
            ResultPageModel pageModel = new ResultPageModel
            {
                PageSize = pageSize,
                PageIndex = pageIndex,
                PageData = data.Select(t => new { workFlowId = t.WorkFlowId, templateType = t.TemplateType, title = t.Title, userPhoto = t.UserPhoto, createTime = t.CreateTime.Value.ToString("yyyy.MM.dd"), detial = t.Detial, auditStatusStrt = t.AuditStatusStr, auditStatusColor = t.AuditStatusColor }),
                Count = (int)rowCount
            };
            return ApiResult.Success("获取成功", data: pageModel);
        }

        /// <summary>
        /// 获取待我审批的数量
        /// </summary>
        /// <returns></returns>
        public ApiResult MyAuditCount()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            int Count = workFlowModule.MyAuditCount(empId, AppAuditStatusEnum.InComplete, 1);
            return ApiResult.Success("", Count);
        }

        /// <summary>
        /// 我发起的审批
        /// </summary>
        /// <returns></returns>
        public ApiResult MyInitiateAudit()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            // 搜索关键字
            string searchKey = JsonHelper.GetStringValue(parm, "searchKey");
            // app审批状态
            int appAuditStatus = JsonHelper.GetInt(parm, "appAuditStatus");
            //申请模板类型
            int applyType = JsonHelper.GetInt(parm, "applyType");
            int pageIndex = JsonHelper.GetInt(parm, "pageIndex");
            int pageSize = JsonHelper.GetInt(parm, "pageSize");
            var data = workFlowModule.MyInitiateAudit(searchKey, empId, (AppAuditStatusEnum)appAuditStatus, applyType, pageIndex, pageSize, out long rowCount);
            ResultPageModel pageModel = new ResultPageModel
            {
                PageSize = pageSize,
                PageIndex = pageIndex,
                PageData = data.Select(t => new { workFlowId = t.WorkFlowId, templateType = t.TemplateType, title = t.Title, userPhoto = t.UserPhoto, createTime = t.CreateTime.Value.ToString("yyyy.MM.dd"), detial = t.Detial, auditStatusStrt = t.AuditStatusStr, auditStatusColor = t.AuditStatusColor }),
                Count = (int)rowCount
            };
            return ApiResult.Success("获取成功", data: pageModel);
        }

        /// <summary>
        /// 获取申请人历史记录
        /// </summary>
        /// <returns></returns>
        public ApiResult ProposerHostoryAudit()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int empId = parm.GetInt("EmployeeId", 0);
            if (empId == 0)
            {
                return ApiResult.ParamIsNull("参数有误，请核实后再试！");
            }
            // 搜索关键字
            string searchKey = JsonHelper.GetStringValue(parm, "searchKey");
            // app审批状态
            int appAuditStatus = JsonHelper.GetInt(parm, "appAuditStatus");
            //申请模板类型
            int applyType = JsonHelper.GetInt(parm, "applyType");
            int pageIndex = JsonHelper.GetInt(parm, "pageIndex");
            int pageSize = JsonHelper.GetInt(parm, "pageSize");
            var data = workFlowModule.ProposerHostoryAudit(searchKey, empId, (AppAuditStatusEnum)appAuditStatus, applyType, pageIndex, pageSize, out long rowCount);
            ResultPageModel pageModel = new ResultPageModel
            {
                PageSize = pageSize,
                PageIndex = pageIndex,
                PageData = data.Select(t => new { workFlowId = t.WorkFlowId, templateType = t.TemplateType, monthNum = t.MonthNum, title = t.Title, userPhoto = t.UserPhoto, createTime = t.CreateTime.Value.ToString("yyyy.MM.dd"), detial = t.Detial, auditStatusStrt = t.AuditStatusStr, auditStatusColor = t.AuditStatusColor }),
                Count = (int)rowCount
            };
            return ApiResult.Success("获取成功", data: pageModel);
        }

        /// <summary>
        /// 抄送我的审批
        /// </summary>
        /// <returns></returns>
        public ApiResult CopyToMyAudit()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            // 搜索关键字
            string searchKey = JsonHelper.GetStringValue(parm, "searchKey");
            // app审批状态
            int appAuditStatus = JsonHelper.GetInt(parm, "appAuditStatus");
            // 抄送我的阅读状态 0全部，1未读
            int readeType = JsonHelper.GetInt(parm, "readeType");
            //申请模板类型
            int applyType = JsonHelper.GetInt(parm, "applyType");
            int pageIndex = JsonHelper.GetInt(parm, "pageIndex");
            int pageSize = JsonHelper.GetInt(parm, "pageSize");
            var data = workFlowModule.CopyToMyAudit(searchKey, empId, (AppAuditStatusEnum)appAuditStatus, readeType, applyType, pageIndex, pageSize, out long rowCount);
            ResultPageModel pageModel = new ResultPageModel
            {
                PageSize = pageSize,
                PageIndex = pageIndex,
                PageData = data.Select(t => new { workFlowId = t.WorkFlowId, templateType = t.TemplateType, title = t.Title, userPhoto = t.UserPhoto, createTime = t.CreateTime.Value.ToString("yyyy.MM.dd"), detial = t.Detial, auditStatusStrt = t.AuditStatusStr, auditStatusColor = t.AuditStatusColor, readStaut = t.ReadStauts }),
                Count = (int)rowCount
            };
            return ApiResult.Success("获取成功", data: pageModel);
        }

        /// <summary>
        /// 修改阅读状态
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateCopyToPeopleReadStaut()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int templateType = JsonHelper.GetInt(parm, "templateType");
            int workFlowId = JsonHelper.GetInt(parm, "workFlowId");
            workFlowModule.UpdateCopyToPeopleReadStaut(templateType, workFlowId);
            return ApiResult.Success("修改成功", data: null);
        }
        /// <summary>
        /// 修改所有阅读状态
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateCopyToPeopleAllReadStaut()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            workFlowModule.UpdateCopyToPeopleAllReadStaut(empId);
            return ApiResult.Success("修改成功", data: null);
        }
        /// <summary>
        /// 撤销申请
        /// </summary>
        /// <returns></returns>
        public ApiResult UndoAudit()
        {
            int empId = Convert.ToInt32(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int templateType = JsonHelper.GetInt(parm, "templateType");
            int workFlowId = JsonHelper.GetInt(parm, "workFlowId");
            bool isSuccess = workFlowModule.UndoAudit(empId, (WFTTemplateTypeEnum)templateType, workFlowId);
            if (isSuccess)
            {
                return ApiResult.Success("撤销成功", data: null);
            }
            else
            {
                return ApiResult.Failed("撤销失败", data: null);
            }
        }
        /// <summary>
        /// 获取签到列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetSignInPageList()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            Rb_Workflow_SignIn_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_SignIn_Extend>(RequestParm.Msg.ToString());
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            demodel.RB_GroupId = userInfo.Group_Id;
            List<Rb_Workflow_SignIn_Extend> data = workFlowModule.GetSignInPageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.Address,
                x.EmName,
                x.BName,
                x.MapCoordinate,
                x.EmployeeId,
                x.Id,
                Image = GetImagePath(x.Image),
                x.RB_BranchId,
                x.RB_GroupId,
                x.Remarks,
                SignInTime = x.SignInTime.Value.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pmodel);
        }
        /// <summary>
        /// 签到管理
        /// </summary>
        /// <returns></returns>
        public ApiResult GetSignInManagementPageList()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            Rb_Workflow_SignIn_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_SignIn_Extend>(RequestParm.Msg.ToString());
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            demodel.RB_GroupId = userInfo.Group_Id;
            List<Rb_Workflow_SignIn_Extend> data = workFlowModule.GetSignInManagementPageList(pmodel.PageIndex, pmodel.PageSize, demodel, out long count);
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = data.Select(x => new
            {
                x.EmName,
                x.BName,
                x.SignTime,
                x.EmployeeId,
                x.StartTime,
                x.StartAddress,
                EndTime = x.StartTime == x.EndTime ? "" : x.EndTime,
                EndAddress = x.StartTime == x.EndTime ? "" : x.EndAddress
            });
            return ApiResult.Success("", pmodel);
        }
        /// <summary>
        /// 新增  获取修改签到
        /// </summary>
        /// <returns></returns>
        public ApiResult SetSignIn()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            Rb_Workflow_SignIn_Extend demodel = JsonConvert.DeserializeObject<Rb_Workflow_SignIn_Extend>(RequestParm.Msg.ToString());
            if (!demodel.SignInTime.HasValue)
            {
                return ApiResult.ParamIsNull("签到时间不能为空！");
            }
            demodel.RB_GroupId = userInfo.Group_Id;
            demodel.RB_BranchId = userInfo.School_Id;
            bool flag = workFlowModule.SetSignIn(demodel);
            if (flag)
                return ApiResult.Success("");
            else
                return ApiResult.Failed("保存失败！");
        }
        /// <summary>
        /// 根据id获取签到详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetSignIn()
        {
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            int Id = parm.GetInt("SignInId", 0);
            if (Id <= 0)
            {
                return ApiResult.ParamIsNull("参数有误，请核实后再试！");
            }
            var data = workFlowModule.GetSignIn(Id);
            return ApiResult.Success("", new { data.Id, data.Address, data.MapCoordinate, data.EmName, data.EmployeeId, Image = GetImagePath(data.Image), data.Remarks, SignInTime = data.SignInTime.Value.ToString("yyyy-MM-dd HH:mm") });
        }
        /// <summary>
        /// 获取用户当前月的所有签到
        /// </summary>
        /// <returns></returns>
        public ApiResult GetSignInInfo()
        {
            var userInfo = UserReidsCache.GetUserLoginInfo(RequestParm.Uid);
            JObject parm = JObject.Parse(RequestParm.Msg.ToString());
            string Month = parm.GetStringValue("MonthStr");
            int EmployeeId = parm.GetInt("EmployeeId", 0);
            if (string.IsNullOrWhiteSpace(Month))
            {
                return ApiResult.ParamIsNull("月份不能为空");
            }
            try
            {
                Convert.ToDateTime(Month);
            }
            catch (Exception)
            {
                return ApiResult.ParamIsNull("月份有误，请核实后再试！");
            }
            if (EmployeeId > 0)
            {
                userInfo.Id = EmployeeId;
            }
            //根据uid获取  当天是否可以签到    同时获取一个月签到状态
            var data = workFlowModule.GetSignInInfo(userInfo.Id, userInfo.Group_Id, Month);
            //今天是否可以签到
            var Daymode = data.Where(x => x.DateStr == DateTime.Now.ToString("yyyy-MM-dd")).Count();
            return ApiResult.Success("", new { IsNowSign = Daymode > 0 ? 1 : 0, data });

        }

        #endregion
    }
}