using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Enum;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using CallCenterAPI.WechatSDK;
using qcloudsms_csharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace CallCenterApi.Interface.Controllers.workorder
{
    public class WorkOrderNewController : BaseController
    {
        BLL.T_Wo_WorkOrder workOrder = new BLL.T_Wo_WorkOrder();
        BLL.T_Cus_CustomerBaseNew cusbll = new BLL.T_Cus_CustomerBaseNew();
        BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();
        BLL.T_Wo_MaterialManage mmBLL = new BLL.T_Wo_MaterialManage();
        BLL.T_Wo_QuestionManage quesBLL = new BLL.T_Wo_QuestionManage();
        BLL.T_Wo_WorkOrderItem_New itembll = new BLL.T_Wo_WorkOrderItem_New();
        BLL.T_Wo_WorkOrder_Logs blllogs = new BLL.T_Wo_WorkOrder_Logs();
        BLL.T_Sys_UserAccount sysUserAccountBll = new BLL.T_Sys_UserAccount();
        BLL.T_Sys_RoleInfo rolebll = new BLL.T_Sys_RoleInfo();
        BLL.T_Sys_DictionaryValue dicvalueBll = new BLL.T_Sys_DictionaryValue();

        // GET: WorkOrderNew
        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(string description, string code, string visitResult, string cusname, string cusphone, string createby, string starttime, string endtime, string keywords, string companyname, string province, string city, string callresults,
            string country, string telephone, string township, string touser, string strvisit, string endvisit, int source = 0, int type = 0, int status = 0, int state = -1, int pageindex = 1, int pagesize = 10)
        {

           int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string sql = $"and  F_IsDelete=0";
                DataTable dt = new DataTable();
                #region 筛选条件
                if (type > 0 && type < 6)//工单类型
                    sql += $" and F_Type=" + type;
                if (source > 0)//工单来源
                {
                    if (source == 1)
                        sql += $" and (F_Source in (1,'') or F_Source is null)";
                    else
                        sql += $" and F_Source='" + source + "'";
                }
                if (!string.IsNullOrWhiteSpace(description))//问题描述
                    sql += $" and F_Description like '%" + description.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(touser))//参与人
                    sql += $" and F_DealBy like '%" + touser.Trim() + "%'";
                if (!string.IsNullOrEmpty(starttime))
                    sql += " and datediff(day,F_CreateOn,'" + starttime + "')<=0 ";
                if (!string.IsNullOrEmpty(endtime))
                    sql += " and datediff(day,F_CreateOn,'" + endtime + "')>=0   ";
                if (!string.IsNullOrEmpty(strvisit))
                    sql += " and datediff(day,F_VisitOn,'" + strvisit + "')<=0 ";
                if (!string.IsNullOrEmpty(endvisit))
                    sql += " and datediff(day,F_VisitOn,'" + endvisit + "')>=0   ";
                if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                    sql += $"  and ( F_CusName like '%" + keywords.Trim() + "%'or F_CusPhone like '%" + keywords.Trim() + "%' ) ";
                if (!string.IsNullOrWhiteSpace(code))//工单编号
                    sql += $" and F_WorkOrderCode like '%" + code.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(visitResult))//
                    sql += $" and F_VisitResult = '" + visitResult.Trim() + "'";
                if (!string.IsNullOrWhiteSpace(callresults))//
                    sql += $" and F_Callresults = '" + callresults.Trim() + "'";

                if (!string.IsNullOrWhiteSpace(createby))//创建人
                {
                    string F_WorkNumber = "";
                    string UserCode = "";
                    Model.T_Sys_UserAccount user = sysUserAccountBll.GetworkModel(createby);

                    if (user != null)
                    {
                        F_WorkNumber = user.F_WorkNumber;
                        UserCode = user.F_UserCode;
                    }
                    else
                    {
                        Model.T_Sys_UserAccount userer = sysUserAccountBll.GetName(createby);
                        if (userer != null)
                        {
                            F_WorkNumber = userer.F_WorkNumber;
                            UserCode = userer.F_UserCode;
                        }

                    }
                    if (!string.IsNullOrEmpty(F_WorkNumber) && !string.IsNullOrEmpty(UserCode))
                    {
                        sql += $" and F_CreateBy  in('" + UserCode + "','" + F_WorkNumber + "') ";
                    }
                    else if (!string.IsNullOrEmpty(F_WorkNumber))
                    {
                        sql += $" and F_CreateBy  in('" + F_WorkNumber + "') ";
                    }
                    else if (!string.IsNullOrEmpty(UserCode))
                    {
                        sql += $" and F_CreateBy  in('" + UserCode + "') ";
                    }

                }
                if (!string.IsNullOrWhiteSpace(cusname))//客户姓名
                    sql += $" and F_CusName like '%" + cusname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusphone))//客户电话
                    sql += $" and F_CusPhone like '%" + cusphone.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(companyname))//公司名称
                    sql += $" and F_CompanyName like '%" + companyname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//省
                    sql += $" and F_IncidentProvince like '%" + province.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//市
                    sql += $" and F_IncidentCity like '%" + city.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//县
                    sql += $" and F_IncidentCountry like '%" + country.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//乡
                    sql += $" and F_IncidentTownship like '%" + township.Trim() + "%'";
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                string uwhere = " ";
                switch (state)
                {
                    case 0://待指派的
                        if (ro.F_RoleCode == "GC")
                        {
                            sql += " and (F_CreateBy= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.F_ID in ( " + GetCYWorkOrderID(ua.F_UserCode) + ")) ";
                        }
                        else if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            uwhere =  $" or (F_State = " + (int)EnumWorkOrderState.reassign + "  and F_State2 = " + (int)EnumWorkOrderState.reassign + ")";
                            uwhere += $" or (F_State = " + (int)EnumWorkOrderState.revoke + "  and F_State2 = " + (int)EnumWorkOrderState.revoke + ")";
                        }
                        #region 获取部门工单列表
                        else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                        {
                            string detpid = "" + ua.F_DeptId;
                            var deparmentlist = new List<Model.T_Sys_Department>();
                            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                            if (dModel != null)
                            {
                                if (dModel.F_Layer == 1)
                                {
                                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                    if (deparmentlist.Count > 0)
                                    {
                                        foreach (var it in deparmentlist)
                                        {
                                            if (detpid != "")
                                            {
                                                detpid += "," + it.F_DeptId;
                                            }
                                            else
                                            {
                                                detpid = "" + it.F_DeptId; ;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    detpid = ua.F_DeptId.ToString();
                                }
                                if (GetDeptWorkOrderID(detpid) != "")
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                                }
                                else
                                {

                                    return Success("暂无工单"); ;
                                }

                            }
                            else
                            {
                                return Error("加载失败");
                            }
                        }
                        #endregion
                        else
                        {
                            sql += $" and F_CreateBy like '%" + ua.F_UserCode + "%'"; ;
                        }
                        //sql += $" and (F_State in(" + (int)EnumWorkOrderState.neworder + "," + (int)EnumWorkOrderState.reassign + "," + (int)EnumWorkOrderState.revoke + ")" + " " + uwhere;
                        sql += $" and (F_State in(" + (int)EnumWorkOrderState.neworder + ")" + " " + uwhere;
                        //    sql +=  "and T_Wo_WorkOrder.F_ID in (" + GetBackWorkOrderID(ua.F_UserCode) + ") ";
                        if (!string.IsNullOrEmpty(GetRevokeWo(ua.F_UserCode, 1)))
                        {
                            sql += $" or (F_State={(int)EnumWorkOrderState.assign} and F_State2={(int)EnumWorkOrderState.assign} and  T_Wo_WorkOrder.F_ID in ({GetRevokeWo(ua.F_UserCode, 1)}))";
                            sql += $" or (F_State={(int)EnumWorkOrderState.assign} and F_Flag=1  and  T_Wo_WorkOrder.F_ID in ({GetRevokeWo(ua.F_UserCode)}))";
                            sql += $" or (F_State2={(int)EnumWorkOrderState.assign} and F_Flag=2  and  T_Wo_WorkOrder.F_ID in ({GetRevokeWo(ua.F_UserCode)})))";
                        }
                        else
                        {
                            sql += $")";
                        }
                        break;
                    case 1://待接单的
                        string strsql = GetDeptWorkOrderID(ua.F_DeptId, ua.F_UserCode, ua.F_Flag);
                        if (strsql != "")
                        {
                            if (ua.F_Flag == 1)
                            {
                                sql += $" and F_State in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ")  ";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                sql += $" and F_State2 in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ") ";
                            }
                            sql += " and T_Wo_WorkOrder.F_ID in ( " + strsql + ")";
                        }
                        else
                        {

                            return Success("暂无工单"); ;
                        }

                        break;
                    case 2://待完成的(待处理)
                        string dealstr = GetDWCWorkOrderID(ua.F_UserCode, ua.F_DeptId, ua.F_Flag);
                        if (!string.IsNullOrEmpty(dealstr))
                        {
                            if (ua.F_Flag == 1)
                            {
                                sql += " and (F_State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + ","+(int)EnumWorkOrderState.revoke + ")";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                sql += " and (F_State2 in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback+","+(int)EnumWorkOrderState.revoke + ")";
                            }
                            sql += "  and T_Wo_WorkOrder.F_ID in ( " + dealstr + ") ";
                            if (!string.IsNullOrEmpty(GetRevokeWo(ua.F_UserCode)))
                            {
                                if (ua.F_Flag == 1)
                                {
                                    sql += " or (F_State=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                }
                                else if (ua.F_Flag == 2)
                                {
                                    sql += " or (F_State2=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                }
                            }
                            else
                            {
                                sql += $")";
                            }
                        }
                        else
                        {
                            return Success("暂无工单"); ;
                        }
                        break;
                    case 10://已完成的
                        if (GetDeptUserCode(ua.F_DeptId) != "")
                        {
                            if (ua.F_Flag == 1)
                            {
                                sql += " and F_State in(10,11)";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                sql += " and F_State2 in(10,11)";
                            }
                            sql += "  and F_DealBy in(" + GetDeptUserCode(ua.F_DeptId) + ") ";
                        }

                        break;
                    case 3://我参与的
                        if (status > 0)
                        {
                            sql += $" and F_State =" + status;
                        }
                        else
                        {
                            sql += $" and F_State in(1,2,3,4)";
                        }
                        if (ro.F_RoleCode == "XTGLY")
                        {
                            if (GetParticipateID() != "")
                            {
                                sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetParticipateID() + ") ";
                            }
                        }
                        else
                        {
                            if (GetParticipateID(ua.F_UserCode) != "")
                            {

                                sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetParticipateID(ua.F_UserCode) + ") ";
                            }
                            else
                            {
                                return Error("暂无工单");
                            }
                        }

                        break;
                    case 4://待回访
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            uwhere = $" and F_Type <> 3";
                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        //sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" +"1" +"' "+ uwhere; ;
                        sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_State2=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" + "1" + "' " + uwhere; ;
                        break;
                    case 6://已回访
                        sql += $" and F_State=" + (int)EnumWorkOrderState.evaluate; ;
                        sql += $" and F_IsVisit=" + 1; ;
                        sql += $" and F_VisitBy !=''";
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX")
                        {
                            sql += " and (F_CreateBy= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.F_ID in ( " + GetCYWorkOrderID(ua.F_UserCode) + ") or F_State =13)";
                        }
                        else if (ro.F_RoleCode == "XTGLY")
                        {
                            uwhere = ""; ;
                        }
                        else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                        {
                            string detpid = "" + ua.F_DeptId;
                            var deparmentlist = new List<Model.T_Sys_Department>();
                            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                            if (dModel != null)
                            {
                                if (dModel.F_Layer == 1)
                                {
                                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                    if (deparmentlist.Count > 0)
                                    {
                                        foreach (var it in deparmentlist)
                                        {
                                            if (detpid != "")
                                            {
                                                detpid += "," + it.F_DeptId;
                                            }
                                            else
                                            {
                                                detpid = "" + it.F_DeptId; ;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    detpid = ua.F_DeptId.ToString();
                                }
                                if (GetDeptWorkOrderID(detpid) != "")
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                                }
                                else
                                {

                                    return Success("暂无工单"); ;
                                }

                            }
                            else
                            {
                                return Error("加载失败");
                            }
                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        sql += $" and F_State=" + (int)EnumWorkOrderState.evaluate;
                        break;
                    case 7://待完结
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            uwhere = ""; ;
                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_State2=" + (int)EnumWorkOrderState.finish + " and ( F_IsVisit = '" + "0" + "' or  F_Type = 3)"; ;
                        //sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and ( F_IsVisit = '" + "0" + "' or  F_Type = 3)"; ;
                        break;
                    case 8://待审批
                        if (ro.F_RoleCode == "GC")
                        {
                            if (GetHApproval(ua.F_UserCode) != "")
                            {
                                sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetHApproval(ua.F_UserCode) + ") "; ;
                            }
                        }
                        else
                        {

                            return Success("暂无工单"); ;
                        }
                        break;
                    case 9://客户工单
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            uwhere = "";
                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        sql += $" and F_State=" + (int)EnumWorkOrderState.customers;
                        break;
                    case 11://延期工单
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            sql += $" and F_ID in(" + GetDelay() + ")";
                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        sql += "and ((F_State !=11 and F_State !=10) or (F_State2 !=11 and F_State2 !=10) )";
                        //sql += "and F_State !=11 and F_State !=10";
                        break;
                    case 12://微信未通过工单
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {

                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        sql += $" and F_State=" + (int)EnumWorkOrderState.recustomers;
                        break;
                    case 13://高层已审批
                        if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "GC")
                        {
                            if (GetApprovedOrderID(ua.F_UserCode) != "")
                            {
                                sql += $"  and F_ID in ( " + GetApprovedOrderID(ua.F_UserCode) + ") "; ;
                            }
                            else
                            {
                                return Error("暂无工单");
                            }
                        }
                        else
                        {
                            return Success("暂无工单");
                        }
                        break;
                    case 14://业务员工单
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            sql += $" and F_Source='" + 2 + "'";
                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        break;
                    case 15://待审批

                        if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL")
                        {
                            if (GetApprovalOrderID(ua, ro.F_RoleCode) != "")
                            {
                                sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetApprovalOrderID(ua, ro.F_RoleCode) + ") ";
                            }
                            else
                            {
                                return Success("暂无工单");
                            }
                        }
                        else
                        {
                            return Success("无操作权限");
                        }
                        break;
                    case 16://已创单
                        sql += $" and F_CreateBy  ='" + ua.F_UserCode + "'";
                        break;
                    case 17://退单
                        if (GetBackid(ua) != "")
                        {
                            sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetBackid(ua) + ") ";
                        }
                        else
                        {
                            return Success("暂无工单");
                        }
                        break;
                    case 18://已审核
                        if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "GC")
                        {
                            if (GetApprovedOrderID(ua.F_UserCode) != "")
                            {
                                sql += $"  and F_ID in ( " + GetApprovedOrderID(ua.F_UserCode) + ") "; ;
                            }
                            else
                            {
                                return Error("暂无工单");
                            }
                        }
                        else
                        {
                            return Success("暂无工单");
                        }
                        break;
                    case 19://综合回访
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX")
                        {
                            sql += " and (F_CreateBy= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.F_ID in ( " + GetCYWorkOrderID(ua.F_UserCode) + ") or F_State =13)";

                        }
                        else if (ro.F_RoleCode == "XTGLY")
                        {
                            uwhere = ""; ;
                        }
                        else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                        {
                            string detpid = "" + ua.F_DeptId;
                            var deparmentlist = new List<Model.T_Sys_Department>();
                            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                            if (dModel != null)
                            {
                                if (dModel.F_Layer == 1)
                                {
                                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                    if (deparmentlist.Count > 0)
                                    {
                                        foreach (var it in deparmentlist)
                                        {
                                            if (detpid != "")
                                            {
                                                detpid += "," + it.F_DeptId;
                                            }
                                            else
                                            {
                                                detpid = "" + it.F_DeptId; ;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    detpid = ua.F_DeptId.ToString();
                                }
                                if (GetDeptWorkOrderID(detpid) != "")
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                                }
                                else
                                {

                                    return Success("暂无工单"); ;
                                }

                            }
                            else
                            {
                                return Error("加载失败");
                            }
                        }
                        else
                        {
                            return Success("无操作权限"); ;
                        }
                        sql += $" and F_State in(10," + (int)EnumWorkOrderState.evaluate + ")"; ;
                        break;
                    case 20: //抄送工单列表
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            uwhere = " ";
                        }
                        else
                        {
                            uwhere = $"where  F_SendCopyUser like '%{ua.F_UserCode}%' or (F_Flag=1 and F_SendCopyDepts={ua.F_DeptId})";
                        }
                        sql += $" and T_Wo_WorkOrder.F_ID in (select F_WorkOrderID from T_Wo_WorkCopy " + uwhere + ") ";
                        //sql += $" and T_Wo_WorkOrder.F_ID in (select F_WorkOrderID from T_Wo_WorkCopy where F_SendCopyUser='" + ua.F_DeptId + "') "; ;
                        break;

                }
                #endregion

                int recordCount = 0;
                if (!string.IsNullOrWhiteSpace(sql))
                {

                    dt = BLL.PagerBLL.GetListPager(
                        "T_Wo_WorkOrder",
                        "F_ID",
                        "*",
                        sql,
                        "ORDER BY T_Wo_WorkOrder.F_ID desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);
                }
                List<Model.T_Wo_WorkOrder> modlelist = new BLL.T_Wo_WorkOrder().DataTableToList(dt);
                if (modlelist.Count > 0)
                {
                    List<WorkOrderNewInput> Input = modeltooip(modlelist);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = Input,
                        total = recordCount
                    };

                    return Content(obj.ToJson()); ;
                }
                else
                {

                    return Success("暂无工单"); ;
                }
            }
            else
            {
                return Error("无操作权限！");
            }
            #region 
            #endregion

        }
        /// <summary>
        /// 获取工单数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkCount()
        {

            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {

                DataTable dt = new DataTable();
                #region 筛选条件
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                string uwhere = " ";
                string sql = "";
                if (!Refresh() || !Refresh2())
                {
                    return Error("查询失败");
                }
                int DZP = 0, YCD = 0, DJD = 0, DCL = 0, YQGD = 0, YZP = 0, DSP = 0, YCL = 0, GCDBL = 0, YBL = 0, WSP =
                    0, YGGD = 0, KHFK = 0, CQGD = 0, CBGD = 0, TD = 0, ZHCX = 0, RV_awaitVist = 0, RV_haveVisit = 0, RV_resultVisit = 0, DWJ = 0, ZHHF = 0,CSGD=0; ;
                for (int i = 0; i <= 21; i++)
                {
                    switch (i)
                    {
                        case 0://待指派的
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "GC")
                            {
                                sql += " and (F_CreateBy= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.F_ID in ( " + GetCYWorkOrderID(ua.F_UserCode) + ")) ";
                            }
                            else if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                uwhere = $" or (F_IsDelete=0 and  F_State = " + (int)EnumWorkOrderState.reassign + "  and F_State2 = " + (int)EnumWorkOrderState.reassign + ")";
                                uwhere += $" or (F_IsDelete=0 and F_State = " + (int)EnumWorkOrderState.revoke + "  and F_State2 = " + (int)EnumWorkOrderState.revoke + ")";                              
                            }
                            #region 获取部门工单列表
                            else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                            {
                                string detpid = "" + ua.F_DeptId;
                                var deparmentlist = new List<Model.T_Sys_Department>();
                                Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                                if (dModel != null)
                                {
                                    if (dModel.F_Layer == 1)
                                    {
                                        deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                        if (deparmentlist.Count > 0)
                                        {
                                            foreach (var it in deparmentlist)
                                            {
                                                if (detpid != "")
                                                {
                                                    detpid += "," + it.F_DeptId;
                                                }
                                                else
                                                {
                                                    detpid = "" + it.F_DeptId; ;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        detpid = ua.F_DeptId.ToString();
                                    }
                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {
                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                                    }
                                    else
                                    {
                                        DZP = 0;
                                        break;
                                    }

                                }
                                else
                                {
                                    DZP = 0;
                                    break;
                                }

                            }
                            #endregion
                            else
                            {
                                sql += $" and F_CreateBy like '%" + ua.F_UserCode + "%'"; ;
                            }
                            sql += $" and F_State in(" + (int)EnumWorkOrderState.neworder + ")" + " " + uwhere;
                            if (!string.IsNullOrEmpty(GetRevokeWo(ua.F_UserCode, 1)))
                            {
                                sql += $" or (F_IsDelete=0 and  F_State={(int)EnumWorkOrderState.assign} and F_State2={(int)EnumWorkOrderState.assign} and  T_Wo_WorkOrder.F_ID in ({GetRevokeWo(ua.F_UserCode, 1)}))";
                                sql += $" or (F_IsDelete=0 and F_State={(int)EnumWorkOrderState.assign} and F_Flag=1  and  T_Wo_WorkOrder.F_ID in ({GetRevokeWo(ua.F_UserCode)}))";
                                sql += $" or (F_IsDelete=0 and F_State2={(int)EnumWorkOrderState.assign} and F_Flag=2  and  T_Wo_WorkOrder.F_ID in ({GetRevokeWo(ua.F_UserCode)}))";
                            }
                            DZP = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//指派
                            break;
                        case 1://待接单的
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            string strsql = GetDeptWorkOrderID(ua.F_DeptId, ua.F_UserCode, ua.F_Flag);
                            if (strsql != "")
                            {
                                if (ua.F_Flag == 1)
                                {
                                    sql += $" and F_State in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ")  ";
                                }
                                else if (ua.F_Flag == 2)
                                {
                                    sql += $" and F_State2 in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ") ";
                                }
                                sql += " and T_Wo_WorkOrder.F_ID in ( " + strsql + ")";

                            }
                            else
                            {

                                DJD = 0;
                                break;
                            }
                            DJD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//接单
                            break;
                        case 2://待完成的(待处理)
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            string dealstr = GetDWCWorkOrderID(ua.F_UserCode, ua.F_DeptId, ua.F_Flag);
                            if (!string.IsNullOrEmpty(dealstr))
                            {
                                if (ua.F_Flag == 1)
                                {
                                    sql += " and (F_State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ")";
                                }
                                else if (ua.F_Flag == 2)
                                {
                                    sql += " and (F_State2 in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ")";
                                }
                                sql += "  and T_Wo_WorkOrder.F_ID in ( " + dealstr + ") ";
                                if (!string.IsNullOrEmpty(GetRevokeWo(ua.F_UserCode)))
                                {

                                    if (ua.F_Flag == 1)
                                    {
                                        sql += " or (F_State=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                    }
                                    else if (ua.F_Flag == 2)
                                    {
                                        sql += " or (F_State2=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                    }
                                }
                                else
                                {
                                    sql += $")";
                                }
                            }
                            else
                            {
                                DCL = 0;
                                break;
                            }
                            DCL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//已接单

                            break;
                        case 10://已完成的
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ua.F_Flag == 1)
                            {
                                sql += " and F_State in(10,11)";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                sql += " and F_State2 in(10,11)";
                            }
                            if (GetDeptUserCode(ua.F_DeptId) != "")
                            {
                                sql += "  and F_DealBy in(" + GetDeptUserCode(ua.F_DeptId) + ") ";
                            }
                            //   sql += " and F_State in(10,11) and F_DealBy = '" + ua.F_UserCode + "' ";
                            YCL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//已完成的

                            break;
                        case 3://客服已分配
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            sql += $" and F_State in(1,2,3,4)";
                            if (ro.F_RoleCode == "XTGLY")
                            {
                                if (GetParticipateID() != "")
                                {
                                    sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetParticipateID() + ") ";

                                }
                                else
                                {
                                    YZP = 0;
                                    break;
                                }
                            }
                            else
                            {
                                if (GetParticipateID(ua.F_UserCode) != "")
                                {
                                    sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetParticipateID(ua.F_UserCode) + ") ";
                                }
                                else
                                {
                                    YZP = 0;
                                    break;
                                }
                            }

                            YZP = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//客服已分配

                            break;
                        case 4://待回访
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                uwhere = $" and F_Type <> 3";
                            }
                            else
                            {
                                RV_awaitVist = 0;
                                break;
                            }
                            sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_State2=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" + "1" + "' " + uwhere; ;
                            //sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" + "1" + "' " + uwhere; ;
                            RV_awaitVist = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//待回访

                            break;
                        case 6://已回访
                            sql = "";
                            sql += $"  F_IsDelete=0";

                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX")
                            {
                                sql += " and (F_CreateBy= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.F_ID in ( " + GetCYWorkOrderID(ua.F_UserCode) + ") or F_State =13)";
                                sql += $" and F_State=" + (int)EnumWorkOrderState.evaluate; ;
                            }
                            else if (ro.F_RoleCode == "XTGLY")
                            {
                                uwhere = ""; ;
                            }
                            else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                            {
                                string detpid = "" + ua.F_DeptId;
                                var deparmentlist = new List<Model.T_Sys_Department>();
                                Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                                if (dModel != null)
                                {
                                    if (dModel.F_Layer == 1)
                                    {
                                        deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                        if (deparmentlist.Count > 0)
                                        {
                                            foreach (var it in deparmentlist)
                                            {
                                                if (detpid != "")
                                                {
                                                    detpid += "," + it.F_DeptId;
                                                }
                                                else
                                                {
                                                    detpid = "" + it.F_DeptId; ;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        detpid = ua.F_DeptId.ToString();
                                    }
                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {
                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                                    }
                                    else
                                    {

                                        RV_haveVisit = 0;
                                        break;
                                    }

                                }
                                else
                                {
                                    RV_haveVisit = 0;
                                    break;
                                }
                            }
                            else
                            {
                                RV_haveVisit = 0;
                                break;
                            }
                            string where = $" and F_State in(10," + (int)EnumWorkOrderState.evaluate + ")"; ;
                            RV_resultVisit = new BLL.T_Wo_WorkOrder().GetModelList(sql + where).Count;//
                            sql += $" and F_State=" + (int)EnumWorkOrderState.evaluate;
                            sql += $" and F_IsVisit=" + 1; ;
                            sql += $" and F_VisitBy !=''";
                            RV_haveVisit = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//已回访
                            break;
                        case 7://待完结
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                uwhere = ""; ;
                            }
                            else
                            {
                                DWJ = 0;
                                break; ;
                            }
                            sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_State2=" + (int)EnumWorkOrderState.finish + " and ( F_IsVisit = '" + "0" + "' or  F_Type = 3)"; ;
                            //sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and ( F_IsVisit = '" + "0" + "' or  F_Type = 3) "; ;
                            DWJ = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//待完结
                            break;
                        case 8://待审批
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "GC")
                            {
                                if (GetHApproval(ua.F_UserCode) != "")
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetHApproval(ua.F_UserCode) + ") "; ;
                                }
                            }
                            else
                            {

                                GCDBL = 0;
                                break; ;
                            }
                            GCDBL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//高层待审批
                            break;
                        case 9://客户工单
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                uwhere = "";
                            }
                            else
                            {
                                KHFK = 0;
                                break; ;
                            }
                            sql += $" and F_State=" + (int)EnumWorkOrderState.customers;
                            KHFK = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//客户工单

                            break;
                        case 11://延期工单
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                sql += $" and F_ID in(" + GetDelay() + ")";
                                sql += "and ((F_State !=11 and F_State !=10) or (F_State2 !=11 and F_State2 !=10) )";
                                //sql += "and F_State !=11 and F_State !=10";
                            }
                            else
                            {
                                YQGD = 0;
                                break; ;
                            }
                            YQGD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//客户工单

                            break;
                        case 12://微信未通过工单
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {

                            }
                            else
                            {
                                WSP = 0;
                                break; ;
                            }
                            sql += $" and F_State=" + (int)EnumWorkOrderState.recustomers;
                            WSP = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//微信未通过工单

                            break;
                        case 13://已审批
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "GC")
                            {
                                if (GetApprovedOrderID(ua.F_UserCode) != "")
                                {
                                    sql += $"  and F_ID in ( " + GetApprovedOrderID(ua.F_UserCode) + ") "; ;
                                }
                                else
                                {
                                    YBL = 0;
                                    break; ;
                                }
                            }
                            else
                            {
                                YBL = 0;
                                break; ;
                            }
                            YBL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//已审批

                            break;
                        case 14://业务员工单
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                sql += $" and F_Source='" + 2 + "'";
                            }
                            else
                            {
                                YGGD = 0;
                                break; ;
                            }
                            YGGD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//微信业务员工单

                            break;
                        case 15://待审批
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL")
                            {
                                if (GetApprovalOrderID(ua, ro.F_RoleCode) != "")
                                {
                                    sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetApprovalOrderID(ua, ro.F_RoleCode) + ") ";
                                }
                                else
                                {
                                    DSP = 0;
                                    break; ;
                                }
                            }
                            else
                            {
                                DSP = 0;
                                break; ;
                            }

                            DSP = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//待审批
                            break;
                        case 16:
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            sql += $" and F_CreateBy  ='" + ua.F_UserCode + "'";
                            YCD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//业务员已创单
                            break;

                        case 17://超期
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            //sql += $" and (F_IsOver=1 or F_IsOver=2)";
                            //sql += $" and F_State !=" + 11;
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                sql += $" and((F_IsOver in(1,3) and F_State !=11) or ( F_IsOver in (2,3) and  F_State2!=11))";
                            }
                            else if (ua.F_Flag == 1)
                            {
                                sql += $" and F_IsOver in (1,3)";
                                sql += $" and F_State !=" + 11;
                            }
                            else if (ua.F_Flag == 2)
                            {
                                sql += $" and  F_IsOver in (2,3)";
                                sql += $" and F_State2 !=" + 11;
                            }
                            #region 退换货的工单按未超期处理 20220302
                            sql += $" and  F_ID not in (select F_ID from T_Wo_WorkOrder where F_SC_PreliminaryOpinion='退换货')";
                            #endregion
                            if (ro.F_RoleCode == "YWY" || ro.F_RoleCode == "BLRY")
                            {
                                sql += $" and F_DealBy like '%" + ua.F_UserCode.Trim() + "%'";
                            }
                            else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                            {
                                string detpid = "" + ua.F_DeptId;
                                var deparmentlist = new List<Model.T_Sys_Department>();
                                Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                                if (dModel != null)
                                {
                                    if (dModel.F_Layer == 1)
                                    {
                                        deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                        if (deparmentlist.Count > 0)
                                        {
                                            foreach (var it in deparmentlist)
                                            {
                                                if (detpid != "")
                                                {
                                                    detpid += "," + it.F_DeptId;
                                                }
                                                else
                                                {
                                                    detpid = "" + it.F_DeptId; ;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        detpid = ua.F_DeptId.ToString();
                                    }
                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {
                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                                    }
                                    else
                                    {

                                        CQGD = 0;
                                        break; ;
                                    }

                                }
                                else
                                {
                                    CQGD = 0;
                                    break; ;
                                }
                            }

                            else if (ro.F_RoleCode == "QTJS")
                            {
                                CQGD = 0;
                                break; ;
                            }
                            CQGD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//超期
                            break;
                        case 18://催办
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            //sql += $" and F_State !=" + 10;
                            //sql += $" and F_State !=" + 11;
                            sql += $" and (F_State not in(10,11) or F_State2 not in (10,11)) ";
                            var list = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.urge);
                            string str = "";
                            foreach (var it in list)
                            {
                                if (str != "")
                                    str += "," + it.F_WoID;
                                else
                                    str = "" + it.F_WoID;
                            }
                            if (str != "")
                            {
                                sql += $"  and T_Wo_WorkOrder.F_ID in(" + str + ")";
                            }
                            else
                            {
                                CBGD = 0;
                                break;
                            }
                            CBGD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//催办
                            break;
                        case 19://综合查询
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "QTJS" || ro.F_RoleCode == "YWY")
                                sql += $" and F_CreateBy like '%" + ua.F_UserCode.Trim() + "%'";
                            else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "BLRY" || ro.F_RoleCode == "ZG" || ro.F_RoleCode == "GC")
                            {

                                string markdepts = "37,57,74,88,268,422,339";
                                string qualdepts = "12,36,295";
                                string detpid = "" + ua.F_DeptId;
                                var deparmentlist = new List<Model.T_Sys_Department>();
                                Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                                if (dModel != null)
                                {

                                    #region  工单查询- 综合查询模块，权限增加，市场部和质管部可以看到事业部所有的工单，包含未经办的  20220519
                                    if (markdepts.Contains(ua.F_DeptId.ToString()) || qualdepts.Contains(ua.F_DeptId.ToString()))
                                    {
                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptAllWorkOrderID(ua.F_DeptId) + ") ";
                                    }
                                    #endregion
                                    else if (ro.F_RoleCode== "GC")
                                    {
                                        string strsq = judgmentDept(ua.F_DeptId);
                                        if (!string.IsNullOrEmpty(strsq))
                                        {
                                            sql += $"  and T_Wo_WorkOrder.F_ID in ( " + strsq + ") ";
                                        }
                                    }
                                    else
                                    {
                                        if (dModel.F_Layer == 1)
                                        {
                                            deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                            if (deparmentlist.Count > 0)
                                            {
                                                foreach (var it in deparmentlist)
                                                {
                                                    if (detpid != "")
                                                    {
                                                        detpid += "," + it.F_DeptId;
                                                    }
                                                    else
                                                    {
                                                        detpid = "" + it.F_DeptId;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            detpid = ua.F_DeptId.ToString();
                                        }
                                        #region 人员更换部门后，仍然需要查看、处理自己原部门的历史工单 20220307
                                        //if (!string.IsNullOrEmpty(ua.F_Origdepts))
                                        //{
                                        //    detpid += "," + ua.F_Origdepts;
                                        //}
                                        #endregion

                                        if (GetDeptWorkOrderID(detpid) != "")
                                        {

                                            sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                        }
                                        else
                                        {

                                            ZHCX = 0;
                                            break;
                                        }
                                    }


                                }
                                else
                                {
                                    ZHCX = 0;
                                    break;
                                }
                            }
                            ZHCX = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//综合查询
                            break;
                        case 20://退单
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (GetBackid(ua) != "")
                            {
                                sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetBackid(ua) + ") ";
                            }
                            else
                            {
                                TD = 0;
                                break;
                            }
                            TD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//综合查询
                            break;

                        case 21: //抄送工单列表
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                uwhere = " ";
                            }
                            else
                            {
                                uwhere = $"where  F_SendCopyUser like '%{ua.F_UserCode}%' or (F_Flag=1 and F_SendCopyDepts={ua.F_DeptId})";
                            }
                            sql += $" and T_Wo_WorkOrder.F_ID in (select F_WorkOrderID from T_Wo_WorkCopy "+ uwhere + ") "; 
                            CSGD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;
                            break;


                    }
                }

                #endregion

                var obj = new
                {
                    state = "success",
                    message = "成功",
                    DZP = DZP,//指派
                    DJD = DJD,//待接单
                    DCL = DCL,//已接单（待处理）
                    YCL = YCL,//已完成的
                    YZP = YZP,//客服已分配
                    RV_await = RV_awaitVist,//待回访
                    RV_have = RV_haveVisit,//已回访
                    RV_result = RV_resultVisit,//综合回访
                    DWJ = DWJ,//待完结
                    GCDBL = GCDBL,//高层待审批
                    KHFK = KHFK,//客户工单
                    YQGD = YQGD,//延期工单
                    WSP = WSP,//微信未通过工单
                    YBL = YBL,//已审批
                    YGGD = YGGD,//微信业务员工单
                    DSP = DSP,//待审批
                    YCD = YCD,//业务员已创单
                    TD = TD,//退单
                    CQGD = CQGD,//超期
                    CBGD = CBGD,//催办
                    ZHCX = ZHCX,//综合查询
                    CSGD= CSGD//抄送工单
                };
                return Content(obj.ToJson()); ;
            }
            else
            {
                return Error("无操作权限！");
            }

        }
        /// <summary>
        ///退回工单列表
        /// </summary>
        public string GetBackid(Model.T_Sys_UserAccount ua)
        {
            string str = string.Empty;

            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType in(" + (int)EnumItemType.deal + "," + (int)EnumItemType.audit + ")"
                + " and "
                    + "F_OptType in(" + (int)EnumItemOpt.abreback + "," + (int)EnumItemOpt.reback + ") and F_NextUser='" + ua.F_UserCode + "'"
                + ""
                + " and isnull(F_IsUsed,'0')='0' ";

            return str;
        }
        public string GetID(string str, long id)
        {
            if (str != "")
            {
                str += "," + id;
            }
            else
            {
                str += id;
            }
            return str;
        }

        /// <summary>
        /// 指派工单时撤回
        /// </summary>
        /// <param name="usercode"></param>
        /// <returns></returns>
        public string GetRevokeWo(string usercode,int flag=0)
        {
            string str = string.Empty;

            str = $"Select F_WoID from T_Wo_WorkOrderItem_New where F_IsUsed=0 and  F_OptType=" + (int)EnumItemOpt.assign+ 
                  $" and F_CreateUser='{usercode}'  group by F_WoID HAVING COUNT(*) >{flag}";
            //var modetab = DbHelperSQL.Query(str).Tables[0];
            //var modelarray = modetab.AsEnumerable().Select(c => c.Field<long>("F_WoID")).ToArray(); ;
            //str = string.Join(",", modelarray);
            return str;
        }

        /// <summary>
        /// 审核工单
        /// </summary>
        public ActionResult GetApproval(long orderid, string AuditCont, int IsAudit = 0, int AuditState = 0, float overtime = 0, int sms = 0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    if (model != null)
                    {
                        var res = Approval(orderid, AuditCont, ua, model, overtime, sms, IsAudit, AuditState);
                        if (res)
                            return Success("审核成功");
                        else
                            return Error("审核失败");
                    }
                    else
                        return Error("工单不存在");
                }
            }
            return Error("OpenId不能为空");
        }
        /// <summary>
        /// 审核工单
        /// </summary>
        public bool Approval(long orderid, string AuditCont, Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, float overtime = 0, int sms = -1, int IsAudit = 0, int AuditState = 0)
        {
            bool res = true;
            string touser = ""; string tousername = "";
            string opt = "审核";
            string deptname = "";
            string deptmodelsname = "";
            int wostate = 0;
            var toussers = "";
            //  var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.audit + " and  F_OptType=" + (int)EnumItemOpt.audit + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_CreateTime desc").FirstOrDefault();
            //    if (itemlast != null)
            // toussers = itemlast.F_CreateUser;
            #region 上报
            if (IsAudit != 0)
            {
                if (GetUser(nowUser) != null)
                {
                    var user = GetUser(nowUser);
                    var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                    var deptmodels = departmentBLL.GetModel(nowUser.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    if (deptmodels != null)
                    {
                        deptmodelsname = deptmodels.F_DeptName + "-";
                    }
                    var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.audit + " and  F_CreateUser!=" + user.F_UserCode + " and  F_OptType=" + (int)EnumItemOpt.audit + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();

                    if (itemlast != null)
                    {
                        toussers = itemlast.F_CreateUser;
                        if (sms == -1)
                        {
                            sms = (int)itemlast.F_IsSMS;
                        }
                    }
                    else
                    {
                        if (sms == -1)
                        {
                            sms = 0;
                        }
                    }

                    if (itemlast != null)
                        toussers = itemlast.F_CreateUser;
                    wostate = 16;
                    if (AuditState == 0)
                    {
                        opt = "同意上报";
                        var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：同意上报" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reaudit, user.F_UserCode, user.F_DeptId, nowUser, overtime, sms);
                        var uaid = AddLog(model.F_ID, model.F_State.Value, deptname + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, nowUser, overtime, sms);
                        if (userid <= 0 || uaid <= 0)
                            res = false;
                        else
                        {
                            if (sms == 1 && !string.IsNullOrEmpty(user.F_Mobile))
                            {
                                SendSms(model.F_Type, user.F_Mobile, nowUser.F_UserId);
                            }
                        }
                    }
                    else if (AuditState == 1)
                    {
                        opt = "驳回修订";
                        var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：驳回修订" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reback, toussers, 0, nowUser, overtime, sms);
                        if (userid <= 0)
                            res = false;
                    }
                    else
                    {
                        opt = "强制结案";
                        wostate = 11;
                        var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：强制结案" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.visit, "", 0, nowUser, overtime, sms);
                        if (userid <= 0)
                            res = false;
                    }
                }
                else
                {
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(nowUser.F_RoleId);
                    if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL")
                    {
                        var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.audit + " and  F_OptType=" + (int)EnumItemOpt.audit + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
                        if (itemlast != null)
                        {
                            toussers = itemlast.F_CreateUser;
                            if (sms == -1)
                            {
                                sms = (int)itemlast.F_IsSMS;
                            }
                        }
                        else
                        {
                            if (sms == -1)
                            {
                                sms = 0;
                            }
                        }
                        if (AuditState == 0)
                        {
                            opt = "同意上报";
                            var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：同意上报" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reaudit, "", 0, nowUser, overtime, sms);
                            res = GetDaQucirCulation(AuditCont, nowUser, DateTime.Now.ToString(), model.F_ID, true);
                            if (userid <= 0 || !res)
                                res = false;
                            wostate = 1;
                        }
                        else if (AuditState == 1)
                        {
                            opt = "驳回修订";
                            var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：驳回修订" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reback, toussers, 0, nowUser, overtime, sms);
                            if (userid <= 0)
                                res = false;
                            wostate = 16;
                        }
                        else
                        {
                            opt = "强制结案";
                            var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：强制结案" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.visit, "", 0, nowUser, overtime, sms);
                            if (userid <= 0)
                                res = false;
                            wostate = 11;
                        }

                    }
                    else
                    {
                        res = false;
                    }
                }
            }
            #endregion
            if (res)
            {
                model.F_State = wostate;
                model.F_State2 = wostate;
                //处理内容
                if (!string.IsNullOrEmpty(AuditCont))
                    model.F_AuditCont += AuditCont + "；";
                model.F_IsAudit = IsAudit;
                model.F_AuditState = AuditState;
                model.F_AuditBy = nowUser.F_UserCode;
                model.F_AuditOn = DateTime.Now;
                workOrder.Update(model);
                if (nowUser.F_UserCode != model.F_CreateBy)
                {
                    sendsysmsg(model, nowUser, model.F_CreateBy, (int)model.F_ID, opt);//
                    //var createmodel = sysUserAccountBll .GetModel(model.F_CreateBy);  //
                    //if (createmodel != null)
                    //{
                    //    if (!string.IsNullOrEmpty(createmodel.F_WxOpenId))
                    //    {
                    //        sendwxmsg(model, createmodel.F_WxOpenId, nowUser, opt);

                    //    }
                    //}
                }

                #region 向下一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser))
                {
                    sendsysmsg(model, nowUser, touser, (int)model.F_ID, opt);//
                    //var modelUser2 = sysUserAccountBll .GetModel(touser);  //
                    //if (modelUser2 != null)
                    //{
                    //    if (!string.IsNullOrEmpty(modelUser2.F_WxOpenId))
                    //    {
                    //        sendwxmsg(model, modelUser2.F_WxOpenId, nowUser, opt);
                    //    }
                    //}
                }
                #endregion 向下一级操作人员推送消息
            }
            else
                return false;
            return true;
        }
        public string GetDeptment(Model.T_Sys_UserAccount ua)
        {
            string detpid = string.Empty;
            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
            var deparmentlist = new List<Model.T_Sys_Department>();
            if (dModel != null)
            {
                if (dModel.F_Layer == 1)
                {
                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                    if (deparmentlist.Count > 0)
                    {
                        foreach (var it in deparmentlist)
                        {
                            if (detpid != "")
                            {
                                detpid += "," + it.F_DeptId;
                            }
                            else
                            {
                                detpid = "" + it.F_DeptId;
                            }
                        }
                    }
                }
                else
                {
                    detpid = ua.F_DeptId.ToString();
                }
            }
            return detpid;
        }
        /// <summary>
        /// 大区经理未审批流转市场管理科
        /// </summary>
        /// <param name="ua"></param>
        /// <param name="time"></param>
        /// <param name="id"></param>
        public bool GetDaQucirCulation(string AuditCont, Model.T_Sys_UserAccount ua, string time, long id, bool istrue)
        {
            DateTime times = DateTime.Parse(time).AddHours(24);
            Model.T_Wo_WorkOrder model = workOrder.GetModel(id);
            List<Model.T_Wo_WorkOrder> modeLlist = new List<Model.T_Wo_WorkOrder>();
            modeLlist.Add(model);
            List<WorkOrderNewInput> Input = modeltooip(modeLlist);
            string cont = "";
            int dapt = 0, nextda = 0; string opt = ""; int nextda2 = 0;string opt2 = "";string cont2 = "";
            var itemlast = itembll.GetModelList("   F_WoID='" + model.F_ID + "' order by F_ID desc").FirstOrDefault();
            int sms = (int)itemlast.F_IsSMS;
            var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
            string deptname = "";
            if (deptmodel1 != null)
            {
                dapt = deptmodel1.F_ParentId;
                deptname = deptmodel1.F_DeptName;
            }
            int isbl = 0;
            Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
            //if (dapt != 0)
            //{
            if (CirculMarket(ua.F_DeptId, 11))
            {
                isbl = 1;
                nextda = 37;
                opt = "流转市场管理科";
                nextda2 = 36;
                opt2 = "流转质量管理科";
            }
            else if (CirculMarket(ua.F_DeptId, 14))
            {
                isbl = 1;
                nextda = 57;
                opt = "流转营销管理处";
            }
            else if (CirculMarket(ua.F_DeptId, 15))
            {
                isbl = 1;
                nextda = 74;
                opt = "流转策划推广";
            }
            else if (CirculMarket(ua.F_DeptId, 16))
            {
                isbl = 1;
                nextda = 88;
                opt = "流转销售部";
            }
            else if (CirculMarket(ua.F_DeptId, 18))
            {
                nextda = 268;
                opt = "流转车用尿素";

            }
            else if (CirculMarket(ua.F_DeptId, 20))
            {
                nextda = 295;
                opt = "流转新乡黑科质检";
            }
            else if (CirculMarket(ua.F_DeptId, 332))
            {
                nextda = 339;
                opt = "流转营销管理处";

            }
            else if (ua.F_DeptId == 17 || ua.F_DeptId == 19 || ua.F_DeptId == 20 || ua.F_DeptId == 21)
            {
                isbl = 1;
                nextda = ua.F_DeptId;
                opt = "流转" + deptname;
                //}
                //else
                //{
                //    nextda = ua.F_DeptId;
                //    opt = "流转"+ deptname;
                //}

            }
            if (istrue)
            {
                if (ro.F_RoleCode == "DQJL")
                {
                    cont = "大区经理已审批:" + AuditCont + "," + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "大区经理已审批: " + AuditCont + "," + opt2;
                    }
                }
                else
                {
                    cont = "分公司经理已审批:" + AuditCont + "," + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "分公司经理已审批: " + AuditCont + "," + opt2;
                    }
                }
            }
            else
            {
                if (ro.F_RoleCode == "DQJL")
                {
                    cont = "大区经理未审批" + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "大区经理未审批" + opt2;
                    }
                }
                else
                {
                    cont = "分公司经理未审批" + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "分公司经理未审批" + opt2;
                    }
                }
            }
            if (nextda != 0 || nextda2 != 0)
            {
                var res = AssignWO(ua, model, Input[0], cont, "", nextda, 0, model.F_limit, sms, 0, 0, 0, time.ToString(), isbl);
                if (nextda2 != 0)
                {
                    var res2 = AssignWO(ua, model, Input[0], cont2, "", nextda2, 0, model.F_limit, sms, 0, 0, 0, time.ToString(), isbl, 2);
                }
                //else
                //{

                //}
                return true;
            }
            else return false;

        }
        /// <summary>
        /// 获取待审批的工单
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetApprovalOrderID(Model.T_Sys_UserAccount ua, string F_RoleCode)
        {

            string str = string.Empty;
            #region 查询自己名下未审批的工单列表
            var itemlast = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_OptType in(" + (int)EnumItemOpt.audit + ")" + " and "
                    + "F_WoState in(" + (int)EnumWorkOrderState.audit + ") and F_NextUser='" + ua.F_UserCode + "' "
                + "" + " ");

            foreach (var it in itemlast)
            {
                float hours = (DateTime.Now - DateTime.Parse(it.F_CreateTime.ToString())).Hours;
                int overtime = 0;
                if (!string.IsNullOrEmpty(it.F_LimitTime))
                {
                    overtime = int.Parse(it.F_LimitTime);
                }
                int sms = int.Parse(it.F_IsSMS.ToString());
                if (F_RoleCode == "DQJL" || F_RoleCode == "FGSJL")
                {
                    if (hours >= 24)
                    {
                        GetDaQucirCulation("", ua, it.F_CreateTime.ToString(), it.F_WoID, false);
                    }
                    else
                    {
                        str = GetID(str, it.F_WoID);
                    }

                }
                else
                {
                    if (hours >= 24)
                    {
                        var user = GetUser(ua);
                        string deptname = "";
                        string deptmodelsname = "";
                        string namestr = "";
                        Model.T_Sys_RoleInfo ro = rolebll.GetModel(user.F_RoleId);
                        if (ro.F_RoleCode == "DQJL")
                        {
                            namestr = "大区经理";
                        }
                        else
                        {
                            namestr = "分公司经理";
                        }
                        var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                        var deptmodels = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            deptname = deptmodel.F_DeptName + "-";
                        }
                        if (deptmodels != null)
                        {
                            deptmodelsname = deptmodels.F_DeptName + "-";
                        }
                        DateTime time = DateTime.Parse(it.F_CreateTime.ToString()).AddHours(24);
                        Model.T_Wo_WorkOrder model = workOrder.GetModel(it.F_WoID);
                        AddLog(model.F_ID, model.F_State.Value, deptmodelsname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "未审批流转" + namestr + "", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, ua, overtime, sms);
                        AddLog(model.F_ID, model.F_State.Value, deptname + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, user, overtime, sms);
                    }
                    else if (hours >= 48)
                    {
                        var user = GetUser(ua);
                        GetDaQucirCulation("", user, it.F_CreateTime.ToString(), it.F_WoID, false);
                    }
                    else
                    {
                        str = GetID(str, it.F_WoID);
                    }
                }
            }
            #endregion
            if (F_RoleCode == "DQJL")
            {
                if (!string.IsNullOrEmpty(GetDeptment(ua)))
                {
                    var itemlasts = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_OptType in(" + (int)EnumItemOpt.audit + ")" + " and "
                                      + "F_WoState in(" + (int)EnumWorkOrderState.audit + ") and F_NextUser in ( " + GetDeptment(ua) + ") ");
                    foreach (var it in itemlasts)
                    {
                        float hours = (DateTime.Now - DateTime.Parse(it.F_CreateTime.ToString())).Hours;
                        int overtime = 0;
                        if (!string.IsNullOrEmpty(it.F_LimitTime))
                        {
                            overtime = int.Parse(it.F_LimitTime);
                        }
                        int sms = int.Parse(it.F_IsSMS.ToString());
                        if (F_RoleCode == "DQJL")
                        {
                            if (hours >= 24)
                            {

                                Model.T_Sys_UserAccount user = sysUserAccountBll.GetModel(it.F_CreateUser);
                                DateTime time = DateTime.Parse(it.F_CreateTime.ToString()).AddHours(24);
                                Model.T_Wo_WorkOrder model = workOrder.GetModel(it.F_WoID);
                                string deptname = "";
                                string deptmodelsname = "";
                                var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                                var deptmodels = departmentBLL.GetModel(ua.F_DeptId);
                                if (deptmodel != null)
                                {
                                    deptname = deptmodel.F_DeptName + "-";
                                }
                                if (deptmodels != null)
                                {
                                    deptmodelsname = deptmodels.F_DeptName + "-";
                                }
                                AddLog(model.F_ID, model.F_State.Value, deptmodelsname + user.F_UserName + "(" + user.F_WorkNumber + ")" + "未审批流转大区经理", (int)EnumItemType.audit, (int)EnumItemOpt.audit, ua.F_UserCode, ua.F_DeptId, user, overtime, sms);
                                AddLog(model.F_ID, model.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, ua.F_UserCode, ua.F_DeptId, ua, overtime, sms);
                                if (hours < 48)
                                {
                                    str = GetID(str, it.F_WoID);
                                }
                                else
                                {
                                    GetDaQucirCulation("", ua, time.ToString(), it.F_WoID, false);
                                }
                            }
                        }
                    }
                }




            }
            return str;
        }
        /// <summary>
        /// 获取已审批的工单列表
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetApprovedOrderID(string user)
        {
            string str = string.Empty;

            str = "select F_WoID from T_Wo_WorkOrderItem_New where  F_OptType=" + (int)EnumItemOpt.reaudit
               + " and F_CreateUser=" + user + "  "//
                 ;
            return str;
        }
        private string GetDelay()
        {
            string str = "";
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_OptType=" + (int)EnumItemOpt.Delay + "and F_ItemType = " + (int)EnumItemType.Delay;
            return str;
        }
        /// <summary>
        /// 延时审批
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="isadopt"></param>
        /// <param name="cont"></param>
        /// <returns></returns>
        public ActionResult Delayapproval(int orderid, int isadopt = 0, string cont = "")
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        var res = Delay(ua, model, cont, isadopt);
                        if (res)
                            return Success("延期成功");
                        else
                            return Error("延期失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 微信审批
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="isadopt"></param>
        /// <param name="cont"></param>
        /// <returns></returns>
        public ActionResult Customersapproval(int orderid, int isadopt = 0, string cont = "")
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        var res = Customers(ua, model, cont, isadopt);
                        if (res)
                            return Success("审批成功");
                        else
                            return Error("审批失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 微信审批
        /// </summary>
        public bool Customers(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont, int isadopt)
        {
            #region 工单处理
            int sms = 0; int wostate = 0; int limit = 0, F_State = 0;
            string opt = "";
            int optbut = 0;
            if (isadopt == 0)
            {
                opt = "未通过";
                optbut = (int)EnumItemOpt.create;
                limit = model.F_limit;
                F_State = (int)EnumWorkOrderState.recustomers;
            }
            else
            {
                opt = "通过";
                optbut = (int)EnumItemOpt.create;
                F_State = (int)EnumWorkOrderState.neworder;
            }

            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "微信审批：" + opt + cont;
            //获取上一级处理人员
            var touser = "";
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, touser, 0, nowUser, limit, sms);
            if (itemid > 0)
            {
                model.F_State = F_State;
                workOrder.Update(model);
            }
            #endregion
            return true;
        }
        /// <summary>
        ///延期处理
        /// </summary>
        public bool Delay(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont, int isadopt)
        {
            #region 工单处理
            int sms = 0; int wostate = 0; int limit = 0;
            var itemlasts = itembll.GetModelList("  F_OptType=" + (int)EnumItemOpt.Delay + "and F_ItemType = " + (int)EnumItemType.Delay + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    sms = int.Parse(it.F_IsSMS.ToString());
                    limit = int.Parse(it.F_LimitTime);
                    it.F_ItemType = (int)EnumItemType.deal;
                    it.F_OptType = (int)EnumItemOpt.deal;
                    itembll.Update(it);
                }
            }
            string opt = "";
            int optbut = 0;
            if (isadopt == 0)
            {
                opt = "未通过";
                optbut = (int)EnumItemOpt.deal;
                limit = model.F_limit;
            }
            else
            {
                opt = "通过";
                optbut = (int)EnumItemOpt.deal;
            }

            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "延期审批：" + opt + cont;
            //获取上一级处理人员
            var touser = "";
            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
            if (itemlast != null)
                touser = itemlast.F_CreateUser;
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, touser, 0, nowUser, limit, sms, "", 1);
            if (itemid > 0)
            {

                model.F_limit = limit;
                workOrder.Update(model);

            }
            #endregion
            return true;
        }

        /// <summary>
        /// 获取异常
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetBackWorkOrderID(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_NextUser='" + user + "' " + " and  F_WoState=" + (int)EnumWorkOrderState.reback + " " + " and isnull(F_IsUsed,'0')='0' "; ;

            return str;
        }
        /// <summary>
        /// 获取我参与的工单编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetCYWorkOrderID(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_CreateUser in(" + user + ") and F_OptType in( 1,3,13 )";
            return str;
        }
        public string GetParticipateID()
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where  F_OptType in(1)";

            ;
            return str;
        }
        /// <summary>
        /// 获取我参与的工单编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetParticipateID(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_CreateUser in(" + user + ") and F_OptType in( 1)";

            ;
            return str;
        }
        public string GetDeptUserCode(int deptid)
        {
            string deptuser = string.Empty;
            var dept = sysUserAccountBll.GetModelList("F_DeptId=" + deptid);
            if (dept != null)
            {
                foreach (var it in dept)
                {
                    if (deptuser != "")
                        deptuser += "," + it.F_UserCode;
                    else
                        deptuser += it.F_UserCode;
                }
            }
            return deptuser;
        }
        /// <summary>
        /// 获取部门待接单的工单编号
        /// </summary>
        /// <returns></returns>
        public string GetDeptWorkOrderID(int deptid, string user, int flag = 1)
        {
            string str = string.Empty;
            string deptuser = string.Empty;
            var dept = sysUserAccountBll.GetModelList("F_DeptId=" + deptid);
            if (dept != null)
            {
                foreach (var it in dept)
                {
                    //if (it.F_UserCode != user)
                    //{
                    if (deptuser != "")
                        deptuser += "','" + it.F_UserCode;
                    else
                        deptuser += it.F_UserCode;
                    //}
                }
            }
            if (!string.IsNullOrEmpty(deptuser))
            {
                if (flag == 1)
                {
                    // string deptuser = "select F_WoID from T_Sys_UserAccount where F_DeptId=" + deptid;
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                        + " and isnull(F_IsUsed,'0')='0'  and F_Type in(1,3)" + " and "
                       + " F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and (F_NextUser in('" + deptuser + "') or  F_NextDept =" + deptid + ") ";//办理中和接单状态的操作人
                            //+ " or (F_WoState =" + (int)EnumWorkOrderState.abreback + " and F_NextUser in('" + deptuser + "'))";//
                }
                else if (flag == 2) //内线
                {
                    // string deptuser = "select F_WoID from T_Sys_UserAccount where F_DeptId=" + deptid;
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                        + " and isnull(F_IsUsed,'0')='0'  and F_Type in(2,3)" + " and "
                        + " F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and (F_NextUser in('" + deptuser + "') or F_NextDept =" + deptid + ") ";//办理中和接单状态的操作人
                            //+ " or (F_WoState =" + (int)EnumWorkOrderState.abreback + " and F_NextUser in('" + deptuser + "'))";//
                }


            }
            else
            {
                if (flag == 1)
                {
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                       + " and "
                           + "F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and F_NextDept =" + deptid + " "//办理中和接单状态的操作人
                            + " and isnull(F_IsUsed,'0')='0' and F_Type in(1,3)";
                }
                else if (flag == 2)
                {
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                      + " and "
                          + "F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and F_NextDept =" + deptid + " "//办理中和接单状态的操作人
                           + " and isnull(F_IsUsed,'0')='0' and F_Type in(2,3)";
                }
            }

            return str;
        }
        /// <summary>
        /// 获取待完成的工单编号
        /// </summary>
        /// <returns></returns>
        //public string GetDWCWorkOrderID(string user, int deptid)
        //{
        //    string str = string.Empty;

        //    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
        //        + " and ("
        //            + "(F_WoState in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + ") and F_NextDept='" + deptid + "') "//办理中和接单状态的操作人
        //            + " or (F_WoState in(" + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.receive + ") and F_NextDept='" + deptid + "')"//退回下一步操作人
        //            + " or (F_WoState in(" + (int)EnumWorkOrderState.revoke + "," + (int)EnumWorkOrderState.receive + ") and F_NextDept='" + deptid + "')"//撤回下一步操作人
        //        + ")"
        //        + " and isnull(F_IsUsed,'0')='0' ";

        //    return str;
        //}

        public string GetDWCWorkOrderID(string user, int deptid, int flag = 1)
        {
            string str = string.Empty;
            string strsql = "";

            if (flag == 1)
            {
                strsql = "and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = "and F_Type in(2,3)";
            }
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                  + " and "
                  + "(F_WoState in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ") and (F_CreateUser='"+user+"' or F_NextDept='" + deptid + "')) "//办理中和接单状态的操作人，退回下一步操作人，撤回下一步操作人
                  + " and isnull(F_IsUsed,'0')='0' " + strsql + "";
            return str;
        }

        /// <summary>
        /// 根据部门获取工单号
        /// </summary>
        /// <returns></returns>
        public string GetDeptWorkOrderID(string user)
        {
            string sql = " ";
            string ua = "";
            DataTable dt = new DataTable();
            if (user != "")
            {
                sql += $" F_DeptId in ( " + user + ") ";
            }
            var userarray = new BLL.T_Sys_UserAccount().GetModelList(sql).Select(T=>T.F_UserCode).ToArray();
            if (userarray.Count()>0)
            {
                ua= string.Join(",", userarray);
            }
            string str = string.Empty;
            int length = ua.Length;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where (F_CreateUser in(" + ua + ")  or F_NextDept in(" + user + "))";
            return str;
        }

        /// <summary>
        ///  市场管理科 和质量管理科可以看到整个事业部的工单
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public string GetDeptAllWorkOrderID(int deptid)
        {
            string sql = " ";
            string dptcode = departmentBLL.GetModel(deptid).F_ParentCode;
            string arrsql = $"select F_DeptId from T_Sys_Department where F_DeptCode LIKE '" + dptcode + "%' ";
            string ua = $"select F_UserCode from T_Sys_UserAccount where F_DeptId in ( " + arrsql + ") " ;
            sql = "select F_WoID from T_Wo_WorkOrderItem_New where (F_CreateUser in(" + ua + ") or F_NextDept in(" + arrsql + "))";
            return sql;
        }
        /// <summary>
        /// 高层可以看到本事业部的所有工单
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public string judgmentDept(int deptid)
        {
            string deptcode = "";
            string sql = " ";

            if (CirculMarket(deptid, 11))
            {
                deptcode = "|0|1|11|";
            }
            else if (CirculMarket(deptid, 14))
            {
                deptcode = "|0|1|14|";
            }
            else if (CirculMarket(deptid, 15))
            {
                deptcode = "|0|1|15|";
            }
            else if (CirculMarket(deptid, 16))
            {
                deptcode = "|0|1|16|";
            }
            else if (CirculMarket(deptid, 18))
            {
                deptcode = "|0|1|18|";

            }
            else if (CirculMarket(deptid, 20))
            {
                deptcode = "|0|1|20|";
            }
            if (!string.IsNullOrEmpty(deptcode))
            {
                string arrsql = $"select F_DeptId from T_Sys_Department where F_DeptCode LIKE '" + deptcode + "%' ";
                string ua = $"select F_UserCode from T_Sys_UserAccount where F_DeptId in ( " + arrsql + ") ";
                sql = "select F_WoID from T_Wo_WorkOrderItem_New where (F_CreateUser in(" + ua + ") or F_NextDept in(" + arrsql + "))";
            }
            return sql;
        }
        /// <summary>
        /// 获取待接单的工单编号
        /// </summary>
        /// <returns></returns>
        public string GetDJDWorkOrderID(string user)
        {
            string str = string.Empty;
            var itemlast = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_ItemType=" + (int)EnumItemType.deal + " and  F_WoState=" + (int)EnumWorkOrderState.assign + " ");
            //   str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
            //    + " and F_WoState=" + (int)EnumWorkOrderState.assign
            //    + " and isnull(F_IsUsed,'0')='0' and F_NextUser='" + user + "' ";
            foreach (var it in itemlast)
            {

                string[] code = it.F_NextUser.Split(',');
                for (int i = 0; i < code.Length; i++)
                {
                    if (code[i] == user)
                    {
                        if (str != string.Empty)
                        {
                            str = str + "," + it.F_WoID;
                        }
                        else
                        {
                            str = it.F_WoID + "";
                        }
                    }
                }
            }
            return str;
        }
        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(ids))
            {
                dt = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + ids + ")").Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                }
            }
            return dt;
        }
        /// <summary>
        /// 查询工单详情
        /// </summary>
        public ActionResult GetDetails(int id)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                DataTable FileUrl = new DataTable();
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);

                if (id <= 0)
                {
                    return Error("请输入正确的id");
                }
                var list = new List<Model.T_Wo_WorkOrder>();
                var model = workOrder.GetModel(id);
                if (model != null)
                {
                    if (model.F_SC_PreliminaryOpinion == "退换货")
                    {
                        List<T_Wo_MaterialItems> materlist = new BLL.T_Wo_MaterialItems().GetModelList($" F_WoID={model.F_ID}");
                        if (materlist != null)
                        {
                            model.MaterialItems = materlist;
                        }
                    }
                    list.Add(model);
                }
                var itemlasts = itembll.GetModelList("  F_WoID=" + id + " and  F_Type=" + ua.F_Flag + " ");
                ; var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                FileUrl = GetFileData(model.F_Files, configfj.F_ParamValue);
                if (list.Count > 0)
                {
                    List<WorkOrderNewInput> Input = modeltooip(list);
                    if (Input != null)
                    {
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            rows = Input,
                            FileUrl,
                            total = ItemList(itemlasts),
                        };

                        return Content(obj.ToJson());
                    }
                    else
                    {
                        return Error("没有查询到此工单");
                    }
                }
                else
                    return Error("没有查询到此工单");

            }
            else
            {
                return Error("无操作权限！");
            }
        }
        private List<ItemListLog> ItemList(List<Model.T_Wo_WorkOrderItem_New> list)
        {
            List<ItemListLog> Modellist = new List<ItemListLog>();

            foreach (var it in list)
            {
                ItemListLog log = new ItemListLog();

                log.F_ID = it.F_ID;
                if (it.F_WoID > 0)
                {
                    if (workOrder.GetModel(it.F_WoID) != null)
                    {
                        log.F_WoID = workOrder.GetModel(it.F_WoID).F_WorkOrderCode;
                    }
                }

                log.F_WoState = it.F_WoState;
                log.F_ItemType = it.F_ItemType;
                log.F_OptType = it.F_OptType;
                log.F_OptContent = it.F_OptContent;
                log.F_IsUsed = it.F_IsUsed;
                log.F_LimitTime = it.F_LimitTime;
                log.F_IsSMS = it.F_IsSMS;
                log.F_SMSToUser = it.F_SMSToUser;
                log.F_SMSToPhone = it.F_SMSToPhone;
                log.F_SMSContent = it.F_SMSContent;
                log.F_CreateTime = it.F_CreateTime;
                log.F_LastTime = it.F_LastTime;
                string username = "";
                if (!string.IsNullOrEmpty(it.F_CreateUser))
                {
                    if (sysUserAccountBll.GetModel(it.F_CreateUser) != null)
                    {
                        username = sysUserAccountBll.GetModel(it.F_CreateUser).F_UserName;
                        log.F_CreateUser = it.F_CreateUser + "(" + username + ")";
                    }
                }
                if (!string.IsNullOrEmpty(it.F_NextUser))
                {
                    if (sysUserAccountBll.GetModel(it.F_NextUser) != null)
                    {
                        log.F_NextUser = it.F_NextUser + "(" + sysUserAccountBll.GetModel(it.F_NextUser).F_UserName + ")";
                    }
                }
                if (it.F_NextDept > 0)
                {
                    if (departmentBLL.GetModel(int.Parse(it.F_NextDept.ToString())) != null)
                    {
                        log.F_NextDept = departmentBLL.GetModel(int.Parse(it.F_NextDept.ToString())).F_DeptName;
                    }

                }

                var configlist = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='NodeLimit' ");
                if (configlist != null && configlist.Count() > 0)
                {
                    var config = configlist.FirstOrDefault();
                    try
                    {
                        if (log.F_LastTime != null)
                        {
                            DateTime t = log.F_LastTime.Value.AddHours(int.Parse(config.F_ParamValue));
                            TimeSpan ts = log.F_CreateTime.Value.Subtract(t);
                            double tss = double.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                            if (tss < 0) { tss = -tss; }
                            string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                            if (t > log.F_CreateTime)
                            {
                                log.Timeout = "剩余" + gshsj;
                            }
                            else
                            {
                                log.Timeout = "超时" + gshsj;
                            }
                            TimeSpan tsx = log.F_CreateTime.Value.Subtract(log.F_LastTime.Value);
                            double tssx = double.Parse(Math.Round(tsx.TotalSeconds, 0).ToString());
                            string gshsjx = DateTimeConvert.parseTimeSeconds(tssx, 1);
                            log.Timeuse = gshsjx;
                        }
                    }
                    catch
                    {

                    }

                }


                Modellist.Add(log);
            }
            return Modellist;
        }
        /// <summary>
        /// 查询工单记录列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult GetItemList(int id, int type = 1, int pageindex = 1, int pagesize = 10,int flag=1)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                string msg = "";
                string strsql = "";
                if (id <= 0)
                    return Error("请输入正确的id");
                if (type == 1)
                {
                    msg = "0,1,7,8";
                }
                else
                {
                    msg = "" + type;
                }              
                strsql = " and F_Type in(3, " + flag + ")";
                string sql = "and  F_ItemType in(" + msg + ") and  F_WoID=" + id + strsql+" ";
                DataTable dt = new DataTable();
                int recordCount;
                dt = BLL.PagerBLL.GetListPager(
                                         "T_Wo_WorkOrderItem_New",
                                         "F_ID",
                                         "*",
                                         sql,
                                         "ORDER BY F_ID desc",
                                          pagesize,
                                          pageindex,
                                         true,
                                         out recordCount);
                List<Model.T_Wo_WorkOrderItem_New> itemlasts = new BLL.T_Wo_WorkOrderItem_New().DataTableToList(dt);
                if (itemlasts != null)
                {
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = ItemList(itemlasts),
                        total = recordCount,
                    };
                    return Content(obj.ToJson());
                }
                else
                {
                    return Error("暂无工单记录");
                }
            }
            {
                return Error("无操作权限！");
            }

        }

        /// <summary>
        /// 节点用时报表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult GetNodeLimitReport(string starttime, string endtime, int page = 1, int limit = 20, int flag = 1, string wocode = "", int isdc = 0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                string msg = "";
                string strsql = "";
                string sql = "";
                if (!string.IsNullOrEmpty(starttime))
                    sql += " and datediff(day,F_CreateTime,'" + starttime + "')<=0 ";
                if (!string.IsNullOrEmpty(endtime))
                    sql += " and datediff(day,F_CreateTime,'" + endtime + "')>=0   ";
                if (!string.IsNullOrWhiteSpace(wocode))//工单编号
                    sql += $" and F_WoID in(select F_ID from T_Wo_WorkOrder where F_WorkOrderCode like '%" + wocode.Trim() + "%')";
                sql += $"and  F_ItemType in(0,1,7,8) ";
                if (flag > 0)
                {
                    sql += $" and  F_Type in(3, {flag}) ";
                }
                DataTable dt = new DataTable();
                DataTable dt2 = new DataTable();
                int recordCount;
                dt = BLL.PagerBLL.GetListPager(
                                         "T_Wo_WorkOrderItem_New",
                                         "F_ID",
                                         "*",
                                         sql,
                                         "ORDER BY F_WoID desc",
                                          limit,
                                          page,
                                         true,
                                         out recordCount);
                List<Model.T_Wo_WorkOrderItem_New> itemlasts = new BLL.T_Wo_WorkOrderItem_New().DataTableToList(dt);
                var rows = ItemList(itemlasts);
                rows.Sort(delegate (ItemListLog x, ItemListLog y) { return Convert.ToInt32(y.F_ID) - Convert.ToInt32(x.F_ID); });
                if (isdc > 0)
                {
                    dt2.Columns.Add("工单编号");
                    dt2.Columns.Add("节点处理人");
                    dt2.Columns.Add("处理内容");
                    dt2.Columns.Add("创建时间");
                    dt2.Columns.Add("节点用时");
                    dt2.Columns.Add("节点超时");

                    foreach (var it in rows)
                    {
                        DataRow drNew = dt2.NewRow();
                        drNew["工单编号"] = it.F_WoID;//工单编号
                        drNew["节点处理人"] = it.F_CreateUser;//节点处理人
                        drNew["处理内容"] = it.F_OptContent;//处理内容
                        drNew["创建时间"] = it.F_CreateTime;//创建时间
                        drNew["节点用时"] = it.Timeuse;//节点用时
                        drNew["节点超时"] = it.Timeout;//节点超时

                        dt2.Rows.Add(drNew);
                    }
                    DataTable dtnew = new DataTable();
                    dtnew = dt2.Copy();
                    dtnew.Rows.Clear();
                    IEnumerable<IGrouping<string, DataRow>> result = dt2.Rows.Cast<DataRow>().GroupBy<DataRow, string>(dr => dr["工单编号"].ToString());//按工单编号分组
                    foreach (IGrouping<string, DataRow> ig in result)
                    {
                        foreach (DataRow dr in ig)
                        {
                            dtnew.ImportRow(dr);
                        }
                    }

                    NPOIHelper npoi = new NPOIHelper();
                    if (npoi.ExportToExcel("节点用时报表", dtnew) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");

                    }
                }
                else
                {
                    List<ItemListLog> loglist = new List<ItemListLog>();
                    var grouplist = rows.GroupBy(x => x.F_WoID).ToList();
                    foreach (var ig in grouplist)
                    {
                        foreach (ItemListLog dr in ig)
                        {
                            ItemListLog log = new ItemListLog();
                            log = dr;
                            loglist.Add(log);
                        }
                    }

                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = loglist,
                        total = recordCount,
                    };
                    return Content(obj.ToJson());

                }
            }
            return Error("无操作权限！");

        }

        /// <summary>
        /// 获取问题类别
        /// </summary>
        /// <returns></returns>
        public string GetComplaint(string msg, int type = 0)
        {
            string str = "";
            string str1 = "";
            string str3 = "";
            if (type == 0)
            {
                str1 = " select F_Id from T_Wo_QuestionManage where F_QuestionName in(" + msg + ")";
                str3 = " select F_Id from T_Wo_QuestionManage where F_ParentId in(" + str1 + ")";
            }
            else if (type == 1)
            {
                str3 = " select F_Id from T_Wo_QuestionManage where F_QuestionName in(" + msg + ")";
            }
            var dept = quesBLL.GetModelList("F_ParentId in(" + str3 + ")");
            if (dept != null)
            {
                foreach (var it in dept)
                {

                    if (str != "")
                        str += "','" + it.F_Id;
                    else
                        str += it.F_Id;

                }
            }
            //  string str4 = " select F_Id from T_Wo_QuestionManage where F_ParentId in(" + str3 + ")";
            return str;
        }


        /// <summary>
        /// 市场管理科 和质量管理科可以看到整个事业部的工单
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="pdeptid"></param>
        /// <returns></returns>
        public string GetAllDepts(int deptid)
        {
            string sql = " F_State=1 ";
            string dptcode = departmentBLL.GetModel(deptid).F_ParentCode;
            string arrsql = " select F_DeptId from T_Sys_Department where F_DeptCode LIKE '" + dptcode + "%' ";
            var deptlist = departmentBLL.GetModelList(sql).Select(p=>p.F_DeptId).ToArray();
            if (deptlist.Count() > 0)
                return string.Join(",", deptlist);
            else return "";
        }

        /// <summary>
        ///综合查询列表
        /// </summary>
        public ActionResult GetComprehensive(string description, string code, string cusname, string createby, string starttime, string endtime, string keywords, string cusphone, string companyname, string province, string city,
            string country, string township, string category, string salebase, string touser, string visitby, string visitresult, string question, int isdc = 0, int source = 0, int state = -1, int type = 0, int pageindex = 1, int pagesize = 10, string question1 = "", string question2 = "")
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string sql = $" and F_IsDelete=0";
                DataTable dt = new DataTable();
                if (type > 0 && type < 6)//工单类型
                    sql += $" and F_Type=" + type;
                if (state >= 0)//
                {
                    if (state == 5)
                    {
                        sql += $" and F_State in (2,3,4,5)";
                    }
                    else if (state == 6)
                    {
                        sql += $" and F_State in (11)";
                        sql += $" and F_IsVisit=" + 1; ;
                        sql += $"and F_DealType != '当即办理'  and F_VisitBy != ''";
                    }
                    else if (state == 10)
                    {
                        sql += $" and F_State in (10,11)";
                    }
                    else if (state == 12)
                    {
                        sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" + "1" + "' ";
                    }
                    else
                    {
                        sql += $" and F_State=" + state;
                    }

                }
                if (!string.IsNullOrEmpty(question))
                {
                    var QuestionManage = quesBLL.GetModelList("F_QuestionName='" + question + "'").FirstOrDefault();
                    if (QuestionManage != null)
                    {
                        if (QuestionManage.F_Type == EnumWOType.Complaint.ToString())
                        {
                            sql += $"  and T_Wo_WorkOrder.F_QuestionType in ('" + GetComplaint("'" + question + "'", 0) + "')"; ;
                        }
                        else
                            sql += $"  and T_Wo_WorkOrder.F_QuestionType  ='" + QuestionManage.F_Id + "'"; ;
                    }
                }
                if (!string.IsNullOrEmpty(question1))
                {
                    var QuestionManage = quesBLL.GetModelList("F_QuestionName='" + question1 + "'").FirstOrDefault();
                    if (QuestionManage != null)
                    {
                        if (QuestionManage.F_Type == EnumWOType.Complaint.ToString())
                        {
                            sql += $"  and T_Wo_WorkOrder.F_QuestionType in ('" + GetComplaint("'" + question + "'", 1) + "')"; ;
                        }
                    }
                }
                if (!string.IsNullOrEmpty(question2))
                {
                    var QuestionManage = quesBLL.GetModelList("F_QuestionName='" + question2 + "'").FirstOrDefault();
                    if (QuestionManage != null)
                    {
                        if (QuestionManage.F_Type == EnumWOType.Complaint.ToString())
                        {
                            sql += $"  and T_Wo_WorkOrder.F_QuestionType  ='" + QuestionManage.F_Id + "'"; ;
                        }
                    }
                    //  
                }
                if (source > 0)//工单来源
                {
                    if (source == 1)
                        sql += $" and (F_Source in (1,'')or F_Source is null )";
                    else
                        sql += $" and F_Source='" + source + "'";
                }
                if (!string.IsNullOrWhiteSpace(createby))//创建人
                {
                    string F_WorkNumber = "";
                    string UserCode = "";
                    Model.T_Sys_UserAccount user = sysUserAccountBll.GetworkModel(createby);
                    if (user != null)
                    {
                        F_WorkNumber = user.F_WorkNumber;
                        UserCode = user.F_UserCode;
                    }
                    else
                    {
                        Model.T_Sys_UserAccount username = sysUserAccountBll.GetName(createby);
                        if (username != null)
                        {
                            F_WorkNumber = username.F_WorkNumber;
                            UserCode = username.F_UserCode;
                        }
                    }
                    if (!string.IsNullOrEmpty(F_WorkNumber) && !string.IsNullOrEmpty(UserCode))
                    {
                        sql += $"and F_CreateBy  in(" + UserCode + "," + F_WorkNumber + ") ";
                    }
                    else if (!string.IsNullOrEmpty(F_WorkNumber))
                    {
                        sql += $"and F_CreateBy  in(" + F_WorkNumber + ") ";
                    }
                    else if (!string.IsNullOrEmpty(UserCode))
                    {
                        sql += $"and F_CreateBy  in(" + UserCode + ") ";
                    }

                }
                if (!string.IsNullOrWhiteSpace(description))//问题描述
                    sql += $" and F_Description like '%" + description.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(touser))//参与人
                    sql += $" and F_DealBy like '%" + touser.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(code))//工单编号
                    sql += $" and F_WorkOrderCode like '%" + code.Trim() + "%'";
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += " and datediff(day,F_CreateOn,'" + starttime + "')<=0 ";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += " and datediff(day,F_CreateOn,'" + endtime + "')>=0   ";
                if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                    sql += $"  and  (F_QuestionType like '%" + keywords.Trim()
                         + "%' or F_ZX_Area like '%" + keywords.Trim() + "%' or F_ZX_Branch like '%" + keywords.Trim()
                         + "%' or F_CusName like '%" + keywords.Trim() + "%'or F_CusPhone like '%" + keywords.Trim() + "%')  ";
                if (!string.IsNullOrWhiteSpace(cusname))//客户姓名
                    sql += $" and F_CusName like '%" + cusname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusphone))//客户电话
                    sql += $" and F_CusPhone like '%" + cusphone.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(companyname))//公司名称
                    sql += $" and F_CompanyName like '%" + companyname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(category))//产品名称
                    sql += $" and F_TS_Category like '%" + category.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(salebase))//销售基地
                    sql += $" and F_SalesBase like '%" + salebase.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//省
                    sql += $" and F_IncidentProvince like '%" + province.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//市
                    sql += $" and F_IncidentCity like '%" + city.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//县
                    sql += $" and F_IncidentCountry like '%" + country.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//乡
                    sql += $" and F_IncidentTownship like '%" + township.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(visitby))//回访人
                    sql += $" and F_VisitBy like '%" + visitby.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(visitresult))//回访结果
                    sql += $" and F_VisitResult like '%" + visitresult.Trim() + "%'";
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                if (ro.F_RoleCode == "QTJS" || ro.F_RoleCode == "YWY")
                    sql += $" and F_CreateBy like '%" + ua.F_UserCode.Trim() + "%'";
                else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "BLRY" || ro.F_RoleCode == "ZG" || ro.F_RoleCode == "GC")
                {
                    string markdepts = "37,57,74,88,268,422,339";
                    string qualdepts = "12,36,295";
                    string detpid = "" + ua.F_DeptId;
                    var deparmentlist = new List<Model.T_Sys_Department>();
                    Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                    if (dModel != null)
                    {
                        #region  工单查询- 综合查询模块，权限增加，市场部和质管部可以看到事业部所有的工单，包含未经办的  20220519
                        if (markdepts.Contains(ua.F_DeptId.ToString()) || qualdepts.Contains(ua.F_DeptId.ToString()))
                        {
                            //detpid += "," + GetAllDepts(ua.F_DeptId);
                            sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptAllWorkOrderID(ua.F_DeptId) + ") ";
                        }
                        #endregion
                        #region 高层可以看到本事业部的所有工单
                        else if (ro.F_RoleCode == "GC")
                        {
                            string strsq = judgmentDept(ua.F_DeptId);
                            if (!string.IsNullOrEmpty(strsq))
                            {
                                sql += $"  and T_Wo_WorkOrder.F_ID in ( " + strsq + ") ";
                            }
                        }
                        #endregion
                        else
                        {
                            if (dModel.F_Layer == 1)
                            {
                                deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                if (deparmentlist.Count > 0)
                                {
                                    foreach (var it in deparmentlist)
                                    {
                                        if (detpid != "")
                                        {
                                            detpid += "," + it.F_DeptId;
                                        }
                                        else
                                        {
                                            detpid = "" + it.F_DeptId;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                detpid = ua.F_DeptId.ToString();
                            }
                            #region 人员更换部门后，仍然需要查看、处理自己原部门的历史工单 20220307
                            //if (!string.IsNullOrEmpty(ua.F_Origdepts))
                            //{
                            //    detpid += "," + ua.F_Origdepts;
                            //}
                            #endregion

                            if (state >= 0)
                            {
                                if (GetDeptWorkOrderID(detpid) != "")
                                {

                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                }
                                else
                                {

                                    return Success("暂无工单"); ;
                                }
                            }
                            else
                            {
                                if (GetDeptWorkOrderID(detpid) != "")
                                {

                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                }
                                else
                                {

                                    return Success("暂无工单"); ;
                                }
                            }

                        }
                    }
                    else
                    {
                        return Error("加载失败");
                    }
                }
                if (isdc > 0)
                {

                    if (type <= 0 || type >= 6)//工单类型
                    {
                        return Error("请选择工单类型");
                    }
                    if (userId != 0)
                    {
                        var depts = new BLL.T_Wo_WorkOrder().GetModelList("F_IsDelete=0" + sql);
                        #region 
                        dt.Columns.Add("工单编号");
                        dt.Columns.Add("工单来源");
                        dt.Columns.Add("工单类型");
                        dt.Columns.Add("外线工单状态");
                        dt.Columns.Add("内线工单状态");
                        dt.Columns.Add("生产单位");

                        if (type == 1 || type == 4)
                        {
                            dt.Columns.Add("问题类别");
                            dt.Columns.Add("产品名称");
                            dt.Columns.Add("问题数量");
                            dt.Columns.Add("销售基地");
                        }
                        else if (type == 2 || type==5)
                        {

                            dt.Columns.Add("产品名称");
                            dt.Columns.Add("问题数量");
                            dt.Columns.Add("销售基地");
                            dt.Columns.Add("生产批次号");
                            dt.Columns.Add("问题类别1");
                            dt.Columns.Add("问题类别2");
                            dt.Columns.Add("问题类别3");
                            dt.Columns.Add("重要级别");
                            dt.Columns.Add("品牌");
                            dt.Columns.Add("客户编号");
                            dt.Columns.Add("业务员");
                            dt.Columns.Add("电话");
                            dt.Columns.Add("经营品牌");
                            dt.Columns.Add("大区名称");
                            dt.Columns.Add("分公司名称");
                            dt.Columns.Add("公司名称");
                            dt.Columns.Add("渠道类型");
                            dt.Columns.Add("物料编码");
                            dt.Columns.Add("物料名称");
                            dt.Columns.Add("型号");
                            dt.Columns.Add("规格");
                            dt.Columns.Add("一级分类");
                            dt.Columns.Add("二级分类");
                            dt.Columns.Add("三级分类");
                            dt.Columns.Add("物料品牌");
                            dt.Columns.Add("复合肥肥效");
                            dt.Columns.Add("产品线");
                            dt.Columns.Add("工艺");
                            dt.Columns.Add("原料及厂家");
                            dt.Columns.Add("该批次生产数量");
                            dt.Columns.Add("车牌号");
                            dt.Columns.Add("返账金额");
                            dt.Columns.Add("责任单位");
                            dt.Columns.Add("下步整改");
                            dt.Columns.Add("问题原因(外)");
                            dt.Columns.Add("问题原因(内)");
                            dt.Columns.Add("处理结果(外)");
                            dt.Columns.Add("处理结果(内)");
                        }
                        else
                        {
                            dt.Columns.Add("问题类别");
                            dt.Columns.Add("抽检级别");
                            dt.Columns.Add("抽检单位");
                            dt.Columns.Add("抽检吨数");
                            dt.Columns.Add("抽检袋数");
                            dt.Columns.Add("抽检时间");
                            dt.Columns.Add("化验单位");
                            dt.Columns.Add("生产批次号");
                            dt.Columns.Add("公关费用金额");
                            dt.Columns.Add("客户编号");
                            dt.Columns.Add("业务员");
                            dt.Columns.Add("电话");
                            dt.Columns.Add("经营品牌");
                            dt.Columns.Add("大区名称");
                            dt.Columns.Add("分公司名称");
                            dt.Columns.Add("公司名称");
                            dt.Columns.Add("渠道类型");
                            dt.Columns.Add("物料编码");
                            dt.Columns.Add("物料名称");
                            dt.Columns.Add("型号");
                            dt.Columns.Add("规格");
                            dt.Columns.Add("一级分类");
                            dt.Columns.Add("二级分类");
                            dt.Columns.Add("三级分类");
                            dt.Columns.Add("物料品牌");
                            dt.Columns.Add("复合肥肥效");
                            dt.Columns.Add("产品线");
                            dt.Columns.Add("工艺");
                            dt.Columns.Add("原料及厂家");
                            dt.Columns.Add("该批次生产数量");
                            dt.Columns.Add("问题原因(外)");
                            dt.Columns.Add("问题原因(内)");
                            dt.Columns.Add("处理结果(外)");
                            dt.Columns.Add("处理结果(内)");
                        }
                        dt.Columns.Add("客户姓名");
                        dt.Columns.Add("客户电话");
                        dt.Columns.Add("问题描述");
                        dt.Columns.Add("事发地-省");
                        dt.Columns.Add("事发地-市");
                        dt.Columns.Add("事发地-县");
                        dt.Columns.Add("事发地-乡");
                        dt.Columns.Add("事发地-详细");
                        dt.Columns.Add("上级处理意见");
                        dt.Columns.Add("处理详情-外线");
                        dt.Columns.Add("处理详情-内线");
                        dt.Columns.Add("备注");
                        dt.Columns.Add("注解");
                        dt.Columns.Add("超时时限");
                        dt.Columns.Add("剩余时间-外线");
                        dt.Columns.Add("剩余时间-内线");
                        dt.Columns.Add("超时原因");
                        dt.Columns.Add("工单记录");
                        #endregion
                        foreach (var it in depts)
                        {
                            DataRow drNew = dt.NewRow();

                            drNew["生产单位"] = it.F_Production;//生产单位
                            drNew["工单编号"] = it.F_WorkOrderCode;//工单编号
                            #region
                            if (it.F_Source == "1")
                            {
                                drNew["工单来源"] = "电话";
                            }
                            else if (it.F_Source == "2")
                            {
                                drNew["工单来源"] = "微信业务员";
                            }
                            else if (it.F_Source == "3")
                            {
                                drNew["工单来源"] = "微信客户";
                            }
                            else if (it.F_Source == "4")
                            {
                                drNew["工单来源"] = "官网";
                            }
                            else
                            {
                                drNew["工单来源"] = "电话";
                            }
                            if (it.F_Type == "1")
                            {
                                drNew["工单类型"] = "咨询";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else if (it.F_Type == "2")
                            {
                                drNew["工单类型"] = "投诉";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else if (it.F_Type == "3")
                            {
                                drNew["工单类型"] = "抽检";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else if (it.F_Type == "5")
                            {
                                drNew["工单类型"] = "业务协办";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else
                            {
                                drNew["工单类型"] = "建议及其他";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            #region 外线工单状态
                            if (it.F_State == 0)//工单状态
                            {
                                drNew["外线工单状态"] = "待指派";
                            }
                            else if (it.F_State == 1)
                            {
                                drNew["外线工单状态"] = "待接单";
                            }
                            else if (it.F_State == 2)
                            {
                                drNew["外线工单状态"] = "待处理";
                            }
                            else if (it.F_State == 3)
                            {
                                drNew["外线工单状态"] = "已退回";
                            }
                            else if (it.F_State == 4)
                            {
                                drNew["外线工单状态"] = "异常退回";
                            }
                            else if (it.F_State == 5)
                            {
                                drNew["外线工单状态"] = "处理中";
                            }
                            else if (it.F_State == 6)
                            {
                                drNew["外线工单状态"] = "待回访";
                            }
                            else if (it.F_State == 7)
                            {
                                drNew["外线工单状态"] = "待完结";
                            }
                            else if (it.F_State == 10)
                            {
                                drNew["外线工单状态"] = "已处理";
                            }
                            else if (it.F_State == 11)
                            {
                                drNew["外线工单状态"] = "已回访";
                            }
                            else if (it.F_State == 12)
                            {
                                drNew["外线工单状态"] = "已退回";
                            }
                            else if (it.F_State == 13)
                            {
                                drNew["外线工单状态"] = "导入工单";
                            }
                            else if (it.F_State == 14)
                            {
                                drNew["外线工单状态"] = "待办理";
                            }
                            else if (it.F_State == 15)
                            {
                                drNew["外线工单状态"] = "微信未通过";
                            }
                            else if (it.F_State == 16)
                            {
                                drNew["外线工单状态"] = "待办理";
                            }
                            else if (it.F_State == 17)
                            {
                                drNew["外线工单状态"] = "已撤回待指派";
                            }
                            #endregion
                            #region 内线工单状态
                            if (it.F_State2 == 0)//工单状态
                            {
                                drNew["内线工单状态"] = "待指派";
                            }
                            else if (it.F_State2 == 1)
                            {
                                drNew["内线工单状态"] = "待接单";
                            }
                            else if (it.F_State2 == 2)
                            {
                                drNew["内线工单状态"] = "待处理";
                            }
                            else if (it.F_State2 == 3)
                            {
                                drNew["内线工单状态"] = "已退回";
                            }
                            else if (it.F_State2 == 4)
                            {
                                drNew["内线工单状态"] = "异常退回";
                            }
                            else if (it.F_State2 == 5)
                            {
                                drNew["内线工单状态"] = "处理中";
                            }
                            else if (it.F_State2 == 6)
                            {
                                drNew["内线工单状态"] = "待回访";
                            }
                            else if (it.F_State2 == 7)
                            {
                                drNew["内线工单状态"] = "待完结";
                            }
                            else if (it.F_State2 == 10)
                            {
                                drNew["内线工单状态"] = "已处理";
                            }
                            else if (it.F_State2 == 11)
                            {
                                drNew["内线工单状态"] = "已回访";
                            }
                            else if (it.F_State2 == 12)
                            {
                                drNew["内线工单状态"] = "已退回";
                            }
                            else if (it.F_State2 == 13)
                            {
                                drNew["内线工单状态"] = "导入工单";
                            }
                            else if (it.F_State2 == 14)
                            {
                                drNew["内线工单状态"] = "待办理";
                            }
                            else if (it.F_State2 == 15)
                            {
                                drNew["内线工单状态"] = "微信未通过";
                            }
                            else if (it.F_State2 == 16)
                            {
                                drNew["内线工单状态"] = "待办理";
                            }
                            else if (it.F_State2 == 17)
                            {
                                drNew["内线工单状态"] = "已撤回待指派";
                            }
                            #endregion
                            if (type == 1 || type == 4)
                            {
                                if (!string.IsNullOrEmpty(it.F_QuestionType))
                                {
                                    try
                                    {
                                        int b = int.Parse(it.F_QuestionType.Trim());
                                        Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                                        if (manage != null)
                                        {
                                            drNew["问题类别"] = manage.F_QuestionName;
                                        }
                                    }
                                    catch
                                    {
                                        drNew["问题类别"] = it.F_QuestionType;
                                    }
                                }
                                drNew["产品名称"] = it.F_TS_Category;
                                drNew["问题数量"] = it.F_ZX_Quantity;//投诉-（吨）
                                drNew["销售基地"] = it.F_SalesBase;
                            }
                            else if (type == 2 || type==5)
                            {
                                drNew["产品名称"] = it.F_TS_Category;
                                if (!string.IsNullOrEmpty(it.F_TS_Quantity))
                                {
                                    drNew["问题数量"] = it.F_TS_Quantity + "吨";//投诉-问题数量（吨）
                                }
                                else
                                    drNew["问题数量"] = "";
                                drNew["销售基地"] = it.F_SalesBase;
                                drNew["生产批次号"] = it.F_BatchNumber;
                                if (!string.IsNullOrEmpty(it.F_QuestionType))
                                {
                                    try
                                    {
                                        int b = int.Parse(it.F_QuestionType.Trim());
                                        Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                                        if (manage != null)
                                        {
                                            drNew["问题类别3"] = manage.F_QuestionName;
                                            if (manage.F_Label == "3")
                                            {
                                                Model.T_Wo_QuestionManage Manage1 = quesBLL.GetModel(int.Parse(manage.F_ParentId.ToString()));//获取问题类别
                                                Model.T_Wo_QuestionManage Manage2 = quesBLL.GetModel(int.Parse(Manage1.F_ParentId.ToString()));//获取问题类别
                                                drNew["问题类别1"] = Manage2.F_QuestionName;//问题类别1
                                                drNew["问题类别2"] = Manage1.F_QuestionName;//问题类别2
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        drNew["问题类别3"] = it.F_QuestionType; //问题类别（投诉抽捡和咨询类别不一样）
                                    }
                                }
                                drNew["重要级别"] = it.F_TS_Level;
                                drNew["品牌"] = it.F_Brand;
                                drNew["车牌号"] = it.F_CarNumber;
                                drNew["返账金额"] = it.F_SC_CJ_ReturnAccount;
                                drNew["责任单位"] = it.F_ZL_ResponsibleUnit;
                                drNew["下步整改"] = it.F_ZL_ImprovementRequirements;
                                //dt.Columns.Add("原料及厂家");
                                //dt.Columns.Add("车牌号");
                                //dt.Columns.Add("返账金额");
                                //dt.Columns.Add("责任单位");
                                //dt.Columns.Add("下步整改");
                                //dt.Columns.Add("物料编码");
                                //dt.Columns.Add("实收数量");
                                //F_ZL_ImprovementRequirements
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(it.F_QuestionType))
                                {
                                    try
                                    {
                                        int b = int.Parse(it.F_QuestionType.Trim());
                                        Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                                        if (manage != null)
                                        {
                                            drNew["问题类别"] = manage.F_QuestionName;
                                        }
                                    }
                                    catch
                                    {
                                        drNew["问题类别"] = it.F_QuestionType;
                                    }
                                }
                                drNew["抽检级别"] = it.F_CJ_Level;
                                drNew["抽检单位"] = it.F_CJ_Unit;
                                drNew["抽检吨数"] = it.F_CJ_Tonnage;
                                drNew["抽检袋数"] = it.F_CJ_BagNo;
                                drNew["抽检时间"] = it.F_CJ_Time;
                                drNew["化验单位"] = it.F_CJ_TestUnit;
                                drNew["生产批次号"] = it.F_BatchNumber;
                                drNew["公关费用金额"] = it.F_CJ_Outlay;
                            }
                            if (type == 2 || type == 3 || type==5)
                            {
                                #region 客户
                                Model.T_Cus_CustomerBaseNew cuModel = new Model.T_Cus_CustomerBaseNew();
                                if (!string.IsNullOrEmpty(it.F_CustomerID))
                                {
                                    cuModel = cusbll.GetModel(it.F_CustomerID.ToString());//通过客户编号获取客户资料
                                }
                                else
                                {
                                    var sqlt = $" and  F_LegalPhone ='" + it.F_CusPhone.Trim() + "'";
                                    cuModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sqlt).FirstOrDefault();
                                }
                                if (cuModel != null)
                                {
                                    drNew["客户编号"] = cuModel.F_CustomerCode;//客户编码

                                    if (!string.IsNullOrEmpty(cuModel.F_AreaID))
                                    {
                                        Model.T_Sys_Department pdModel = new T_Sys_Department();
                                        try
                                        {
                                            pdModel = departmentBLL.GetModel(int.Parse(cuModel.F_AreaID));//通过公司id获取部门
                                        }
                                        catch
                                        {
                                            pdModel = departmentBLL.GetModel(cuModel.F_AreaID);//通过公司id获取部门
                                        }

                                        if (pdModel != null)
                                        {
                                            drNew["大区名称"] = pdModel.F_DeptName;
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(cuModel.F_BranchID))
                                    {
                                        Model.T_Sys_Department pdModel1 = new T_Sys_Department();
                                        try
                                        {
                                            pdModel1 = departmentBLL.GetModel(int.Parse(cuModel.F_BranchID));//通过公司id获取部门
                                        }
                                        catch
                                        {
                                            pdModel1 = departmentBLL.GetModel(cuModel.F_BranchID);//通过公司id获取部门
                                        }
                                        if (pdModel1 != null)
                                        {
                                            drNew["分公司名称"] = pdModel1.F_DeptName;
                                        }
                                    }
                                    drNew["业务员"] = cuModel.F_Salesman;
                                    drNew["电话"] = cuModel.F_SalesPhone;
                                    drNew["公司名称"] = cuModel.F_CompanyName;//公司名称
                                    drNew["经营品牌"] = cuModel.F_Brands;
                                    drNew["渠道类型"] = cuModel.F_Channel;



                                }
                                #endregion
                                #region 物料
                                if (!string.IsNullOrEmpty(it.F_MaterialID))
                                {
                                    if (valcode(it.F_MaterialID.ToString(), 11))
                                    {
                                        drNew["物料编码"] = it.F_MaterialID;//验证物料编码为11位纯数字
                                        Model.T_Wo_MaterialManage maModel = mmBLL.GetModel(it.F_MaterialID);//通过物料编码获取物料信息
                                        if (maModel != null)
                                        {
                                            drNew["物料名称"] = maModel.F_MaterialName;
                                            drNew["型号"] = maModel.F_Model;
                                            drNew["规格"] = maModel.F_Specs;
                                            drNew["一级分类"] = maModel.F_Level1;
                                            drNew["二级分类"] = maModel.F_Level2;
                                            drNew["三级分类"] = maModel.F_Level3;
                                            drNew["物料品牌"] = maModel.F_Brand;
                                            drNew["复合肥肥效"] = maModel.F_MaterialEffect;
                                            drNew["产品线"] = maModel.F_Pipeline;
                                            drNew["工艺"] = maModel.F_Craft;
                                        }
                                    }
                                }

                                //dt.Columns.Add("原料及厂家");
                                //dt.Columns.Add("该批次生产数量");
                                drNew["原料及厂家"] = it.F_Manufacturers;//原料及厂家
                                drNew["该批次生产数量"] = it.F_ProductionNum;//该批次生产数量
                                drNew["问题原因(外)"] = it.F_EventReason;//问题原因(外
                                drNew["问题原因(内)"] = it.F_EventReason2;//问题原因(内)
                                drNew["处理结果(内)"] = it.F_SuperiorOpinion;//处理结果(外)
                                drNew["处理结果(内)"] = it.F_SuperiorOpinion2;//处理结果(内)

                            }

                            #endregion
                            #region 基本字段

                            drNew["客户姓名"] = it.F_CusName;//
                            drNew["客户电话"] = it.F_CusPhone;//
                            drNew["问题描述"] = it.F_Description;//
                            drNew["事发地-省"] = it.F_IncidentProvince;//
                            drNew["事发地-市"] = it.F_IncidentCity;//
                            drNew["事发地-县"] = it.F_IncidentCountry;//
                            drNew["事发地-乡"] = it.F_IncidentTownship;//
                            drNew["事发地-详细"] = it.F_IncidentDetailed;//
                            drNew["上级处理意见"] = AssCont(it.F_ID);//上级处理意见
                            drNew["处理详情-外线"] = it.F_DealContent;//处理内容
                            drNew["处理详情-内线"] = it.F_DealContent2;//处理内容
                            drNew["备注"] = it.F_VisitRemarks;//处理内容
                            drNew["注解"] = it.F_Annotation;//处理内容
                            drNew["超时时限"] = it.F_limit;//处理内容
                            #region
                            float RemainingTime = float.Parse(string.Format("{0:f2}", TimeToOver(it.F_ID, it.F_limit)));
                            if (RemainingTime >= 0)
                            {
                                drNew["剩余时间-外线"] = RemainingTime;//处理内容
                            }
                            else
                            {
                                drNew["剩余时间-外线"] = "超时" + Math.Abs(RemainingTime);//处理内容
                            }
                            #endregion
                            #region 内线
                            float RemainingTime2 = float.Parse(string.Format("{0:f2}", TimeToOver(it.F_ID, it.F_limit, 2)));
                            if (RemainingTime2 >= 0)
                            {
                                drNew["剩余时间-内线"] = RemainingTime2;//处理内容
                            }
                            else
                            {
                                drNew["剩余时间-内线"] = "超时" + Math.Abs(RemainingTime2);//处理内容
                            }
                            #endregion
                            drNew["超时原因"] = it.F_Reasontimeout;//处理内容

                            var itemlasts = itembll.GetModelList(" F_WoID=" + it.F_ID + " ");
                            if (itemlasts != null)
                            {
                                foreach (var iv in itemlasts)
                                {
                                    if (drNew["工单记录"] != null)
                                    {
                                        drNew["工单记录"] += "--" + iv.F_OptContent;
                                    }
                                    else
                                    {
                                        drNew["工单记录"] = iv.F_OptContent;
                                    }

                                }
                            }
                            dt.Rows.Add(drNew);
                            #endregion
                        }
                        NPOIHelper npoi = new NPOIHelper();
                        if (npoi.ExportToExcel("工单列表", dt) == "")
                        {
                            return Success("导出成功");
                        }
                        else
                        {
                            return Error("导出失败");

                        }
                    }
                    return Error("无操作权限");
                }
                else
                {
                    #endregion
                    int recordCount = 0;
                    if (!string.IsNullOrWhiteSpace(sql))
                    {

                        dt = BLL.PagerBLL.GetListPager(
                            "T_Wo_WorkOrder",
                            "F_ID",
                            "*",
                            sql,
                            "ORDER BY T_Wo_WorkOrder.F_CreateOn desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount);
                    }
                    List<Model.T_Wo_WorkOrder> modlelist = new BLL.T_Wo_WorkOrder().DataTableToList(dt);
                    if (modlelist.Count > 0)
                    {
                        List<WorkOrderNewInput> Input = modeltooip(modlelist);
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            rows = Input,
                            total = recordCount
                        };

                        return Content(obj.ToJson()); ;
                    }
                    else
                    {
                        return Success("暂无工单"); ;
                    }
                }

            }
            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 获取高层审批
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetHApproval(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where   F_ItemType=" + (int)EnumItemType.audit + " and  F_OptType=" + (int)EnumItemOpt.audit + "and F_NextUser= '" + user + "'" + "and F_IsUsed=2";
            return str;
        }
        /// <summary>
        /// 查询超时工单列表
        /// </summary>
        public ActionResult GetOvertime(string code, string keywords, string cusname, string cusphone, string companyname, string province, string city,
         string starttime, string salesBase, string endtime, string country, string township, string touser, string product, int source = 0, int state = 0, int type = 0, int pageindex = 1, int pagesize = 10, int isdc = 0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                if (!Refresh() || !Refresh2())
                {
                    return Error("查询失败");
                }
                string sql = $" and F_IsDelete=0";
                //   sql += "and F_Type !=3";
                DataTable dt = new DataTable();
                #region 筛选条件
                if (type > 0 && type < 6)//工单类型
                    sql += $" and F_Type=" + type;
                if (source > 0)//工单来源
                {
                    if (source == 1)
                        sql += $" and F_Source in (1,'')";
                    else
                        sql += $" and F_Source='" + source + "'";
                }
                if (!string.IsNullOrWhiteSpace(touser))//参与人
                    sql += $" and F_DealBy like '%" + touser.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(code))//工单编号
                    sql += $" and F_WorkOrderCode like '%" + code.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                    sql += $"  and ( F_CusName like '%" + keywords.Trim() + "%'or F_CusPhone like '%" + keywords.Trim() + "%' ) ";
                if (!string.IsNullOrEmpty(starttime))
                    sql += " and datediff(day,F_CreateOn,'" + starttime + "')<=0 ";
                if (!string.IsNullOrEmpty(endtime))
                    sql += " and datediff(day,F_CreateOn,'" + endtime + "')>=0   ";
                if (!string.IsNullOrWhiteSpace(salesBase))//销售基地
                    sql += $" and F_SalesBase like '%" + salesBase.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusname))//客户姓名
                    sql += $" and F_CusName like '%" + cusname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusphone))//客户电话
                    sql += $" and F_CusPhone like '%" + cusphone.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(companyname))//公司名称
                    sql += $" and F_CompanyName like '%" + companyname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//省
                    sql += $" and F_IncidentProvince like '%" + province.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//市
                    sql += $" and F_IncidentCity like '%" + city.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//县
                    sql += $" and F_IncidentCountry like '%" + country.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//乡
                    sql += $" and F_IncidentTownship like '%" + township.Trim() + "%'";
                if (!string.IsNullOrEmpty(product))
                {
                    sql += $" and F_TS_Category='" + product.Trim() + "'";
                }
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);

                if (state > 0)
                {
                    sql += $" and F_State =" + state;
                }
                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                {
                    sql += $" and((F_IsOver in(1,3) and F_State !=11) or ( F_IsOver in (2,3) and  F_State2!=11))";
                }
                else if (ua.F_Flag == 1)
                {
                    sql += $" and F_IsOver in (1,3)";
                    sql += $" and F_State !=" + 11;
                }
                else if (ua.F_Flag == 2)
                {
                    sql += $" and  F_IsOver in (2,3)";
                    sql += $" and F_State2 !=" + 11;
                }
                if (ro.F_RoleCode == "YWY" || ro.F_RoleCode == "BLRY")
                {
                    sql += $" and F_DealBy like '%" + ua.F_UserCode.Trim() + "%'";
                }
                else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                {
                    string detpid = "" + ua.F_DeptId;
                    var deparmentlist = new List<Model.T_Sys_Department>();
                    Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                    if (dModel != null)
                    {
                        if (dModel.F_Layer == 1)
                        {
                            deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                            if (deparmentlist.Count > 0)
                            {
                                foreach (var it in deparmentlist)
                                {
                                    if (detpid != "")
                                    {
                                        detpid += "," + it.F_DeptId;
                                    }
                                    else
                                    {
                                        detpid = "" + it.F_DeptId; ;
                                    }
                                }
                            }
                        }
                        else
                        {
                            detpid = ua.F_DeptId.ToString();
                        }
                        if (GetDeptWorkOrderID(detpid) != "")
                        {
                            sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                        }
                        else
                        {

                            return Success("暂无工单"); ;
                        }

                    }
                    else
                    {
                        return Error("加载失败");
                    }
                }
                else if (ro.F_RoleCode == "QTJS")
                {
                    return Error("无操作权限！");
                }
                #endregion
                #region 退换货的工单按未超期处理 20220302
                sql += $" and  F_ID not in (select F_ID from T_Wo_WorkOrder where F_SC_PreliminaryOpinion='退换货')";
                #endregion
                if (isdc > 0)
                {

                    if (type <= 0 || type >= 6)//工单类型
                    {
                        return Error("请选择工单类型");
                    }
                    if (userId != 0)
                    {
                        var depts = new BLL.T_Wo_WorkOrder().GetModelList("F_IsDelete=0" + sql);
                        #region 
                        dt.Columns.Add("工单编号");
                        dt.Columns.Add("工单来源");
                        dt.Columns.Add("工单类型");
                        dt.Columns.Add("外线工单状态");
                        dt.Columns.Add("内线工单状态");

                        if (type == 1 || type == 4)
                        {
                            dt.Columns.Add("问题类别");
                            dt.Columns.Add("产品名称");
                            dt.Columns.Add("问题数量");
                            dt.Columns.Add("销售基地");
                        }
                        else if (type == 2 || type==5)
                        {

                            dt.Columns.Add("产品名称");
                            dt.Columns.Add("问题数量");
                            dt.Columns.Add("销售基地");
                            dt.Columns.Add("生产批次号");
                            dt.Columns.Add("问题类别1");
                            dt.Columns.Add("问题类别2");
                            dt.Columns.Add("问题类别3");
                            dt.Columns.Add("重要级别");
                            dt.Columns.Add("品牌");
                            dt.Columns.Add("客户编号");
                            dt.Columns.Add("业务员");
                            dt.Columns.Add("电话");
                            dt.Columns.Add("经营品牌");
                            dt.Columns.Add("大区名称");
                            dt.Columns.Add("分公司名称");
                            dt.Columns.Add("公司名称");
                            dt.Columns.Add("渠道类型");
                            dt.Columns.Add("物料编码");
                            dt.Columns.Add("物料名称");
                            dt.Columns.Add("型号");
                            dt.Columns.Add("规格");
                            dt.Columns.Add("一级分类");
                            dt.Columns.Add("二级分类");
                            dt.Columns.Add("三级分类");
                            dt.Columns.Add("物料品牌");
                            dt.Columns.Add("复合肥肥效");
                            dt.Columns.Add("产品线");
                            dt.Columns.Add("工艺");
                        }
                        else
                        {
                            dt.Columns.Add("问题类别");
                            dt.Columns.Add("抽检级别");
                            dt.Columns.Add("抽检单位");
                            dt.Columns.Add("抽检吨数");
                            dt.Columns.Add("抽检袋数");
                            dt.Columns.Add("抽检时间");
                            dt.Columns.Add("化验单位");
                            dt.Columns.Add("生产批次号");
                            dt.Columns.Add("公关费用金额");
                            dt.Columns.Add("客户编号");
                            dt.Columns.Add("业务员");
                            dt.Columns.Add("电话");
                            dt.Columns.Add("经营品牌");
                            dt.Columns.Add("大区名称");
                            dt.Columns.Add("分公司名称");
                            dt.Columns.Add("公司名称");
                            dt.Columns.Add("渠道类型");
                            dt.Columns.Add("物料编码");
                            dt.Columns.Add("物料名称");
                            dt.Columns.Add("型号");
                            dt.Columns.Add("规格");
                            dt.Columns.Add("一级分类");
                            dt.Columns.Add("二级分类");
                            dt.Columns.Add("三级分类");
                            dt.Columns.Add("物料品牌");
                            dt.Columns.Add("复合肥肥效");
                            dt.Columns.Add("产品线");
                            dt.Columns.Add("工艺");
                        }
                        dt.Columns.Add("客户姓名");
                        dt.Columns.Add("客户电话");
                        dt.Columns.Add("问题描述");
                        dt.Columns.Add("事发地-省");
                        dt.Columns.Add("事发地-市");
                        dt.Columns.Add("事发地-县");
                        dt.Columns.Add("事发地-乡");
                        dt.Columns.Add("事发地-详细");
                        dt.Columns.Add("上级处理意见");
                        dt.Columns.Add("处理详情-外线");
                        dt.Columns.Add("处理详情-内线");
                        dt.Columns.Add("备注");
                        dt.Columns.Add("注解");
                        dt.Columns.Add("超时时限");
                        dt.Columns.Add("剩余时间-外线");
                        dt.Columns.Add("剩余时间-内线");
                        dt.Columns.Add("超时原因");
                        dt.Columns.Add("工单记录");
                        #endregion
                        foreach (var it in depts)
                        {
                            DataRow drNew = dt.NewRow();

                            drNew["工单编号"] = it.F_WorkOrderCode;//工单编号

                            if (it.F_Source == "1")
                            {
                                drNew["工单来源"] = "电话";
                            }
                            else if (it.F_Source == "2")
                            {
                                drNew["工单来源"] = "微信业务员";
                            }
                            else if (it.F_Source == "3")
                            {
                                drNew["工单来源"] = "微信客户";
                            }
                            else if (it.F_Source == "4")
                            {
                                drNew["工单来源"] = "官网";
                            }
                            else
                            {
                                drNew["工单来源"] = "电话";
                            }
                            if (it.F_Type == "1")
                            {
                                drNew["工单类型"] = "咨询";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else if (it.F_Type == "2")
                            {
                                drNew["工单类型"] = "投诉";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else if (it.F_Type == "3")
                            {
                                drNew["工单类型"] = "抽检";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else if (it.F_Type == "5")
                            {
                                drNew["工单类型"] = "业务协办";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            else
                            {
                                drNew["工单类型"] = "建议及其他";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                            }
                            #region 外线工单状态
                            if (it.F_State == 0)//工单状态
                            {
                                drNew["外线工单状态"] = "待指派";
                            }
                            else if (it.F_State == 1)
                            {
                                drNew["外线工单状态"] = "待接单";
                            }
                            else if (it.F_State == 2)
                            {
                                drNew["外线工单状态"] = "待处理";
                            }
                            else if (it.F_State == 3)
                            {
                                drNew["外线工单状态"] = "已退回";
                            }
                            else if (it.F_State == 4)
                            {
                                drNew["外线工单状态"] = "异常退回";
                            }
                            else if (it.F_State == 5)
                            {
                                drNew["外线工单状态"] = "处理中";
                            }
                            else if (it.F_State == 6)
                            {
                                drNew["外线工单状态"] = "待回访";
                            }
                            else if (it.F_State == 7)
                            {
                                drNew["外线工单状态"] = "待完结";
                            }
                            else if (it.F_State == 10)
                            {
                                drNew["外线工单状态"] = "已处理";
                            }
                            else if (it.F_State == 11)
                            {
                                drNew["外线工单状态"] = "已回访";
                            }
                            else if (it.F_State == 12)
                            {
                                drNew["外线工单状态"] = "已退回";
                            }
                            else if (it.F_State == 13)
                            {
                                drNew["外线工单状态"] = "导入工单";
                            }
                            else if (it.F_State == 14)
                            {
                                drNew["外线工单状态"] = "待办理";
                            }
                            else if (it.F_State == 15)
                            {
                                drNew["外线工单状态"] = "微信未通过";
                            }
                            else if (it.F_State == 16)
                            {
                                drNew["外线工单状态"] = "待办理";
                            }
                            else if (it.F_State == 17)
                            {
                                drNew["外线工单状态"] = "已撤回待指派";
                            }
                            #endregion
                            #region 内线工单状态
                            if (it.F_State2 == 0)//工单状态
                            {
                                drNew["内线工单状态"] = "待指派";
                            }
                            else if (it.F_State2 == 1)
                            {
                                drNew["内线工单状态"] = "待接单";
                            }
                            else if (it.F_State2 == 2)
                            {
                                drNew["内线工单状态"] = "待处理";
                            }
                            else if (it.F_State2 == 3)
                            {
                                drNew["内线工单状态"] = "已退回";
                            }
                            else if (it.F_State2 == 4)
                            {
                                drNew["内线工单状态"] = "异常退回";
                            }
                            else if (it.F_State2 == 5)
                            {
                                drNew["内线工单状态"] = "处理中";
                            }
                            else if (it.F_State2 == 6)
                            {
                                drNew["内线工单状态"] = "待回访";
                            }
                            else if (it.F_State2 == 7)
                            {
                                drNew["内线工单状态"] = "待完结";
                            }
                            else if (it.F_State2 == 10)
                            {
                                drNew["内线工单状态"] = "已处理";
                            }
                            else if (it.F_State2 == 11)
                            {
                                drNew["内线工单状态"] = "已回访";
                            }
                            else if (it.F_State2 == 12)
                            {
                                drNew["内线工单状态"] = "已退回";
                            }
                            else if (it.F_State2 == 13)
                            {
                                drNew["内线工单状态"] = "导入工单";
                            }
                            else if (it.F_State2 == 14)
                            {
                                drNew["内线工单状态"] = "待办理";
                            }
                            else if (it.F_State2 == 15)
                            {
                                drNew["内线工单状态"] = "微信未通过";
                            }
                            else if (it.F_State2 == 16)
                            {
                                drNew["内线工单状态"] = "待办理";
                            }
                            else if (it.F_State2 == 17)
                            {
                                drNew["内线工单状态"] = "已撤回待指派";
                            }
                            #endregion
                            if (type == 1 || type == 4)
                            {
                                if (!string.IsNullOrEmpty(it.F_QuestionType))
                                {
                                    try
                                    {
                                        int b = int.Parse(it.F_QuestionType.Trim());
                                        Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                                        if (manage != null)
                                        {
                                            drNew["问题类别"] = manage.F_QuestionName;
                                        }
                                    }
                                    catch
                                    {
                                        drNew["问题类别"] = it.F_QuestionType;
                                    }
                                }
                                drNew["产品名称"] = it.F_TS_Category;
                                drNew["问题数量"] = it.F_ZX_Quantity;//投诉-（吨）
                                drNew["销售基地"] = it.F_SalesBase;
                            }
                            else if (type == 2 || type==5)
                            {
                                drNew["产品名称"] = it.F_TS_Category;
                                if (!string.IsNullOrEmpty(it.F_TS_Quantity))
                                {
                                    drNew["问题数量"] = it.F_TS_Quantity + "吨";//投诉-问题数量（吨）
                                }
                                else
                                    drNew["问题数量"] = "";
                                drNew["销售基地"] = it.F_SalesBase;
                                drNew["生产批次号"] = it.F_BatchNumber;
                                if (!string.IsNullOrEmpty(it.F_QuestionType))
                                {
                                    try
                                    {
                                        int b = int.Parse(it.F_QuestionType.Trim());
                                        Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                                        if (manage != null)
                                        {
                                            drNew["问题类别3"] = manage.F_QuestionName;
                                            if (manage.F_Label == "3")
                                            {
                                                Model.T_Wo_QuestionManage Manage1 = quesBLL.GetModel(int.Parse(manage.F_ParentId.ToString()));//获取问题类别
                                                Model.T_Wo_QuestionManage Manage2 = quesBLL.GetModel(int.Parse(Manage1.F_ParentId.ToString()));//获取问题类别
                                                drNew["问题类别1"] = Manage2.F_QuestionName;//问题类别1
                                                drNew["问题类别2"] = Manage1.F_QuestionName;//问题类别2
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        drNew["问题类别3"] = it.F_QuestionType; //问题类别（投诉抽捡和咨询类别不一样）
                                    }
                                }
                                drNew["重要级别"] = it.F_TS_Level;
                                drNew["品牌"] = it.F_Brand;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(it.F_QuestionType))
                                {
                                    try
                                    {
                                        int b = int.Parse(it.F_QuestionType.Trim());
                                        Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                                        if (manage != null)
                                        {
                                            drNew["问题类别"] = manage.F_QuestionName;
                                        }
                                    }
                                    catch
                                    {
                                        drNew["问题类别"] = it.F_QuestionType;
                                    }
                                }
                                drNew["抽检级别"] = it.F_CJ_Level;
                                drNew["抽检单位"] = it.F_CJ_Unit;
                                drNew["抽检吨数"] = it.F_CJ_Tonnage;
                                drNew["抽检袋数"] = it.F_CJ_BagNo;
                                drNew["抽检时间"] = it.F_CJ_Time;
                                drNew["化验单位"] = it.F_CJ_TestUnit;
                                drNew["生产批次号"] = it.F_BatchNumber;
                                drNew["公关费用金额"] = it.F_CJ_Outlay;
                            }
                            if (type == 2 || type == 3 || type==5)
                            {
                                #region 客户
                                Model.T_Cus_CustomerBaseNew cuModel = new Model.T_Cus_CustomerBaseNew();
                                if (!string.IsNullOrEmpty(it.F_CustomerID))
                                {
                                    cuModel = cusbll.GetModel(it.F_CustomerID.ToString());//通过客户编号获取客户资料
                                }
                                else
                                {
                                    var sqlt = $" and  F_LegalPhone ='" + it.F_CusPhone.Trim() + "'";
                                    cuModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sqlt).FirstOrDefault();
                                }
                                if (cuModel != null)
                                {
                                    drNew["客户编号"] = cuModel.F_CustomerCode;//客户编码

                                    if (!string.IsNullOrEmpty(cuModel.F_AreaID))
                                    {
                                        Model.T_Sys_Department pdModel = new T_Sys_Department();
                                        try
                                        {
                                            pdModel = departmentBLL.GetModel(int.Parse(cuModel.F_AreaID));//通过公司id获取部门
                                        }
                                        catch
                                        {
                                            pdModel = departmentBLL.GetModel(cuModel.F_AreaID);//通过公司id获取部门
                                        }

                                        if (pdModel != null)
                                        {
                                            drNew["大区名称"] = pdModel.F_DeptName;
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(cuModel.F_BranchID))
                                    {
                                        Model.T_Sys_Department pdModel1 = new T_Sys_Department();
                                        try
                                        {
                                            pdModel1 = departmentBLL.GetModel(int.Parse(cuModel.F_BranchID));//通过公司id获取部门
                                        }
                                        catch
                                        {
                                            pdModel1 = departmentBLL.GetModel(cuModel.F_BranchID);//通过公司id获取部门
                                        }
                                        if (pdModel1 != null)
                                        {
                                            drNew["分公司名称"] = pdModel1.F_DeptName;
                                        }
                                    }
                                    drNew["业务员"] = cuModel.F_Salesman;
                                    drNew["电话"] = cuModel.F_SalesPhone;
                                    drNew["公司名称"] = cuModel.F_CompanyName;//公司名称
                                    drNew["经营品牌"] = cuModel.F_Brands;
                                    drNew["渠道类型"] = cuModel.F_Channel;



                                }
                                #endregion
                                #region 物料
                                if (!string.IsNullOrEmpty(it.F_MaterialID))
                                {
                                    if (valcode(it.F_MaterialID.ToString(), 11))
                                    {
                                        drNew["物料编码"] = it.F_MaterialID;//验证物料编码为11位纯数字
                                        Model.T_Wo_MaterialManage maModel = mmBLL.GetModel(it.F_MaterialID);//通过物料编码获取物料信息
                                        if (maModel != null)
                                        {
                                            drNew["物料名称"] = maModel.F_MaterialName;
                                            drNew["型号"] = maModel.F_Model;
                                            drNew["规格"] = maModel.F_Specs;
                                            drNew["一级分类"] = maModel.F_Level1;
                                            drNew["二级分类"] = maModel.F_Level2;
                                            drNew["三级分类"] = maModel.F_Level3;
                                            drNew["物料品牌"] = maModel.F_Brand;
                                            drNew["复合肥肥效"] = maModel.F_MaterialEffect;
                                            drNew["产品线"] = maModel.F_Pipeline;
                                            drNew["工艺"] = maModel.F_Craft;
                                        }
                                    }
                                }


                            }

                            #endregion
                            #region 基本字段

                            drNew["客户姓名"] = it.F_CusName;//
                            drNew["客户电话"] = it.F_CusPhone;//
                            drNew["问题描述"] = it.F_Description;//
                            drNew["事发地-省"] = it.F_IncidentProvince;//
                            drNew["事发地-市"] = it.F_IncidentCity;//
                            drNew["事发地-县"] = it.F_IncidentCountry;//
                            drNew["事发地-乡"] = it.F_IncidentTownship;//
                            drNew["事发地-详细"] = it.F_IncidentDetailed;//
                            drNew["上级处理意见"] = AssCont(it.F_ID);//上级处理意见
                            drNew["处理详情-外线"] = it.F_DealContent;//处理内容
                            drNew["处理详情-内线"] = it.F_DealContent2;//处理内容
                            drNew["备注"] = it.F_VisitRemarks;//处理内容
                            drNew["注解"] = it.F_Annotation;//处理内容
                            drNew["超时时限"] = it.F_limit;//处理内容
                            #region 外线
                            float RemainingTime = float.Parse(string.Format("{0:f2}", TimeToOver(it.F_ID, it.F_limit)));
                            if (RemainingTime >= 0)
                            {
                                drNew["剩余时间-外线"] = RemainingTime;//处理内容
                            }
                            else
                            {
                                drNew["剩余时间-外线"] = "超时" + Math.Abs(RemainingTime);//处理内容
                            }
                            #endregion
                            #region 内线
                            float RemainingTime2 = float.Parse(string.Format("{0:f2}", TimeToOver(it.F_ID, it.F_limit, 2)));
                            if (RemainingTime2 >= 0)
                            {
                                drNew["剩余时间-内线"] = RemainingTime2;//处理内容
                            }
                            else
                            {
                                drNew["剩余时间-内线"] = "超时" + Math.Abs(RemainingTime2);//处理内容
                            }
                            #endregion
                            drNew["超时原因"] = it.F_Reasontimeout;//处理内容

                            var itemlasts = itembll.GetModelList("    F_WoID=" + it.F_ID + " ");
                            if (itemlasts != null)
                            {
                                foreach (var iv in itemlasts)
                                {
                                    if (drNew["工单记录"] != null)
                                    {
                                        drNew["工单记录"] += "--" + iv.F_OptContent;
                                    }
                                    else
                                    {
                                        drNew["工单记录"] = iv.F_OptContent;
                                    }

                                }
                            }
                            dt.Rows.Add(drNew);
                            #endregion
                        }
                        NPOIHelper npoi = new NPOIHelper();
                        if (npoi.ExportToExcel("超时工单列表", dt) == "")
                        {
                            return Success("导出成功");
                        }
                        else
                        {
                            return Error("导出失败");

                        }
                    }
                    return Error("无操作权限");
                }
                else
                {
                    int recordCount = 0;
                    if (!string.IsNullOrWhiteSpace(sql))
                    {

                        dt = BLL.PagerBLL.GetListPager(
                            "T_Wo_WorkOrder",
                            "F_ID",
                            "*",
                            sql,
                            "ORDER BY T_Wo_WorkOrder.F_ID desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount);
                    }
                    List<long> woid = new List<long>();
                    List<Model.T_Wo_WorkOrder> modlelist = new BLL.T_Wo_WorkOrder().DataTableToList(dt);
                    List<WorkOrderNewInput> Input = modeltooip(modlelist);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = Input,
                        total = recordCount
                    };
                    return Content(obj.ToJson()); ;
                }
            }

            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 工单导入
        /// 导入excel
        /// </summary>
        public ActionResult ImportExcel(int type = 2)
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            string ip = DTRequest.GetIP();
            if (!string.IsNullOrWhiteSpace(usercode))
            {
                HttpPostedFile _upFile = RequestString.GetFile("upFile");
                if (_upFile != null)
                {
                    int headrow = 0;
                    #region 上传文件
                    string filepath = "";
                    string datepath = DateTime.Now.ToString("yyyyMMddHHMMss");
                    string aLastName = Path.GetExtension(_upFile.FileName);
                    string oriname = Path.GetFileNameWithoutExtension(_upFile.FileName);
                    if (aLastName != ".xls" && aLastName != ".xlsx")
                    {
                        return Error("文件类型错误，请选择Excel文件");
                    }
                    string newpath = datepath + "_" + _upFile.FileName;
                    if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
                    {
                        Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
                    }
                    filepath = this.Request.ApplicationPath + "/ExcelData/" + newpath;
                    string PhysicalPath = Server.MapPath(filepath);
                    _upFile.SaveAs(PhysicalPath);
                    #endregion
                    #region 添加附件日志
                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = newpath;//附件名称
                    model_T_Sys_Accessories.F_FileType = aLastName;//附件类型
                    model_T_Sys_Accessories.F_FileUrl = filepath;//附件地址
                    model_T_Sys_Accessories.F_UserCode = usercode;//上传人  
                    model_T_Sys_Accessories.F_OriName = oriname;
                    int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    #endregion
                    NPOIHelper np = new NPOIHelper();
                    DataTable dt = np.ExcelToTable(_upFile, headrow);
                    string msg = string.Empty;
                    if (dt == null || dt.Rows.Count == 0)
                        return Error("文件没有数据");
                    else
                    {
                        Model.T_Wo_WorkOrder dModel = new Model.T_Wo_WorkOrder();
                        dModel.F_State = 13;
                        dModel.F_CreateBy = usercode;
                        dModel.F_IsDelete = 0;
                        dModel.F_Source = "4";
                        dModel.F_Files = fid.ToString();
                        dModel.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");  //工单编号  
                        foreach (DataRow dr in dt.Rows)
                        {
                            #region 数据入库
                            headrow = headrow + 1;

                            if (type > 0)
                            {
                                #region 基本字段
                                dModel.F_CusName = dr["客户姓名"].ToString();
                                dModel.F_CusPhone = dr["客户电话"].ToString();
                                dModel.F_CompanyName = dr["公司名称"].ToString();
                                dModel.F_IncidentProvince = dr["省"].ToString();
                                dModel.F_IncidentCity = dr["市"].ToString();
                                dModel.F_IncidentCountry = dr["县"].ToString();
                                dModel.F_IncidentTownship = dr["乡"].ToString();
                                dModel.F_IncidentDetailed = dr["详细地址"].ToString();
                                dModel.F_SalesBase = dr["销售基地"].ToString();
                                dModel.F_Description = dr["问题描述"].ToString();
                                dModel.F_QuestionType = dr["问题类别"].ToString();
                                dModel.F_DealType = dr["处理方式"].ToString();
                                dModel.F_DealBy = dr["处理人"].ToString();
                                if (!string.IsNullOrEmpty(dr["处理时间"].ToString()))
                                {
                                    string tt = dr["处理时间"].ToString();
                                    string dd = tt.Split('-')[0];
                                    string m = tt.Split('-')[1];
                                    string mm = m.Split('月')[0];
                                    string yyyy = tt.Split('-')[2];
                                    dModel.F_DealTime = DateTime.Parse(yyyy + "/" + mm + "/" + dd);
                                }
                                dModel.F_DealContent = dr["处理内容"].ToString();
                                dModel.F_DealResult = dr["处理结果"].ToString();
                                dModel.F_DealReasons = dr["未处理原因"].ToString();
                                if (!string.IsNullOrEmpty(dr["创建时间"].ToString()))
                                {

                                    string tt = dr["创建时间"].ToString();
                                    string dd = tt.Split('-')[0];
                                    string m = tt.Split('-')[1];
                                    string mm = m.Split('月')[0];
                                    string yyyy = tt.Split('-')[2];
                                    dModel.F_CreateOn = DateTime.Parse(yyyy + "/" + mm + "/" + dd);
                                }
                                #endregion
                                #region
                                if (type == 1)
                                {
                                    dModel.F_Type = "1";
                                    dModel.F_ZX_ProName = dr["产品名称"].ToString();
                                    dModel.F_ZX_Quantity = dr["问题数量"].ToString();
                                    dModel.F_ZX_Area = dr["大区"].ToString();
                                    dModel.F_ZX_Branch = dr["分公司"].ToString();
                                }
                                #region 
                                else if (type == 2 || type==5)
                                {
                                    dModel.F_Type = type.ToString();
                                    if (dr["客户编号"].ToString() != "")
                                    {
                                        if (valcode(dr["客户编号"].ToString(), 10))
                                        {
                                            dModel.F_CustomerID = dr["客户编号"].ToString();
                                        }
                                        else
                                        {
                                            msg = msg + "第" + headrow + "行，客户编号为10位纯数字，未导入<br>";
                                            return Error(msg);
                                        }
                                    }
                                    else
                                    {

                                        int i = 0;
                                        while (true)
                                        {
                                            if (!getunique(0, GetCusCode(i)))
                                            {
                                                dModel.F_CustomerID = GetCusCode(i);
                                                break;
                                            }
                                            else
                                            {
                                                i++;
                                            }
                                        }
                                    }
                                    var model = new Model.T_Cus_CustomerBaseNew();
                                    #region 保存客户基本信息
                                    if (dr["分公司"].ToString() != "")
                                    {
                                        Model.T_Sys_Department pdModel1 = departmentBLL.GetModel(dr["分公司"].ToString());
                                        if (pdModel1 != null)
                                        {
                                            model.F_BranchID = pdModel1.F_DeptId.ToString();
                                            Model.T_Sys_Department pdModel = departmentBLL.GetModel(pdModel1.F_ParentId);
                                            if (pdModel != null)
                                            {
                                                model.F_AreaID = pdModel1.F_DeptId.ToString();
                                            }
                                        }
                                    }
                                    model.F_CustomerCode = dModel.F_CustomerID.ToString();
                                    model.F_Salesman = dr["业务员"].ToString();
                                    model.F_CreateBy = usercode;
                                    model.F_CreateOn = DateTime.Now;
                                    model.F_IsDelete = 0;
                                    #endregion
                                    cusbll.Add(model);
                                    if (dr["物料编码"].ToString() != "")
                                    {
                                        if (valcode(dr["物料编码"].ToString(), 11))
                                        {
                                            dModel.F_MaterialID = dr["物料编码"].ToString();
                                        }
                                        else
                                        {
                                            msg = msg + "第" + headrow + "行，物料编码为11位纯数字，未导入<br>";
                                            return Error(msg);
                                        }
                                    }
                                    else
                                    {

                                        while (true)
                                        {
                                            while (true)
                                            {
                                                if (!gematerque(0, GetIntCode()))
                                                {
                                                    dModel.F_MaterialID = GetIntCode();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    var Materia = new Model.T_Wo_MaterialManage();
                                    #region
                                    Materia.F_MaterialCode = dModel.F_MaterialID;//物料编号
                                    Materia.F_MaterialName = dr["物料名称"].ToString();//物料名称
                                    Materia.F_Model = dr["型号"].ToString();//型号
                                    Materia.F_Specs = dr["规格"].ToString();//规格
                                    Materia.F_Level1 = dr["一级分类"].ToString();//一级分类
                                    Materia.F_Level2 = dr["二级分类"].ToString();//二级分类
                                    Materia.F_Level3 = dr["三级分类"].ToString();//三级分类
                                    Materia.F_Brand = dr["品牌"].ToString();//品牌
                                    Materia.F_MaterialEffect = dr["复合肥肥效"].ToString();//复合肥肥效
                                    Materia.F_Craft = dr["工艺"].ToString();//工艺
                                    Materia.F_Pipeline = dr["产品线"].ToString();//产品线
                                    Materia.F_IsDelete = 0;
                                    Materia.F_CreateOn = DateTime.Now;
                                    Materia.F_CreateBy = CurrentUser.UserData.F_UserCode;
                                    #endregion
                                    int b = mmBLL.Add(Materia);
                                    if (
                                        dr["生产批次号"].ToString() != "")
                                    {
                                        if (vaBatchNumber(dr["生产批次号"].ToString()))
                                        {
                                            dModel.F_BatchNumber = dr["生产批次号"].ToString();
                                        }
                                        else
                                        {
                                            msg = msg + "第" + headrow + "行，生产批次号错误，未导入<br>";
                                            return Error(msg);
                                        }
                                    }

                                    dModel.F_TS_Formula = dr["型号"].ToString();
                                    dModel.F_TS_Category = dr["产品线"].ToString();
                                    dModel.F_TS_Quantity = dr["问题数量"].ToString();
                                    dModel.F_TS_Level = dr["重要级别"].ToString();
                                    dModel.F_SC_ProductBase = dr["生产基地"].ToString();
                                    dModel.F_SC_QualityMonth = dr["超出质保期限"].ToString();
                                    dModel.F_SC_PreliminaryOpinion = dr["初审意见"].ToString();
                                    dModel.F_ZL_QualityEventLevel = dr["质量事件等级"].ToString();
                                    dModel.F_ZL_ClaimAmount = dr["索赔金额"].ToString();
                                    dModel.F_ZL_ResponsibleUnit = dr["责任单位"].ToString();
                                    dModel.F_ZL_ApprovalOpinions = dr["审批意见"].ToString();
                                    dModel.F_ZL_ApprovalDisagree = dr["不同意意见"].ToString();
                                    int company = 0, Region = 0, technology = 0, production = 0, logistics = 0;
                                    if (!string.IsNullOrEmpty(dr["公司承担"].ToString()))
                                    {
                                        company = int.Parse(dr["公司承担"].ToString());
                                    }
                                    if (!string.IsNullOrEmpty(dr["大区承担"].ToString()))
                                    {
                                        Region = int.Parse(dr["大区承担"].ToString());
                                    }
                                    if (!string.IsNullOrEmpty(dr["技术承担"].ToString()))
                                    {
                                        technology = int.Parse(dr["技术承担"].ToString());
                                    }
                                    if (!string.IsNullOrEmpty(dr["生产承担"].ToString()))
                                    {
                                        production = int.Parse(dr["生产承担"].ToString());
                                    }
                                    if (!string.IsNullOrEmpty(dr["物流承担"].ToString()))
                                    {
                                        logistics = int.Parse(dr["物流承担"].ToString());
                                    }
                                    if (company > 0 || Region > 0 || technology > 0 || production > 0 || logistics > 0)
                                    {
                                        dModel.F_ZL_CompensationMethod = "钱款";
                                    }
                                    if (company > 0)
                                    {
                                        dModel.F_ZL_CompensationMoney = company.ToString();
                                        dModel.F_ZL_CResponsibleUnits = "公司承担";
                                    }
                                    else if (Region > 0)
                                    {
                                        dModel.F_ZL_CompensationMoney = Region.ToString();
                                        dModel.F_ZL_CResponsibleUnits = "大区承担";
                                    }
                                    else if (technology > 0)
                                    {
                                        dModel.F_ZL_CompensationMoney = technology.ToString();
                                        dModel.F_ZL_CResponsibleUnits = "技术承担";
                                    }
                                    else if (production > 0)
                                    {
                                        dModel.F_ZL_CompensationMoney = production.ToString();
                                        dModel.F_ZL_CResponsibleUnits = "生产承担";
                                    }
                                    else if (logistics > 0)
                                    {
                                        dModel.F_ZL_CompensationMoney = logistics.ToString();
                                        dModel.F_ZL_CResponsibleUnits = "物流承担";
                                    }
                                    dModel.F_ZL_Fquantity = dr["确认实收数量"].ToString();
                                    dModel.F_ZL_ImprovementRequirements = dr["改进要求"].ToString();
                                    dModel.F_ZL_CApprovalNo = dr["对应审批工作流单号"].ToString();
                                }
                                #endregion
                                #region 
                                else if (type == 3)
                                {
                                    dModel.F_Type = "3";
                                    if (dr["客户编号"].ToString() != "")
                                    {
                                        if (valcode(dr["客户编号"].ToString(), 10))
                                        {
                                            dModel.F_CustomerID = dr["客户编号"].ToString();
                                        }
                                        else
                                        {
                                            msg = msg + "第" + headrow + "行，客户编号为10位纯数字，未导入<br>";
                                            return Error(msg);
                                        }
                                    }
                                    else
                                    {

                                        int i = 0;
                                        while (true)
                                        {
                                            if (!getunique(0, GetCusCode(i)))
                                            {
                                                dModel.F_CustomerID = GetCusCode(i);
                                                break;
                                            }
                                            else
                                            {
                                                i++;
                                            }
                                        }
                                    }
                                    var model = new Model.T_Cus_CustomerBaseNew();
                                    #region 保存客户基本信息
                                    if (dr["分公司"].ToString() != "")
                                    {
                                        Model.T_Sys_Department pdModel1 = departmentBLL.GetModel(dr["分公司"].ToString());
                                        if (pdModel1 != null)
                                        {
                                            model.F_BranchID = pdModel1.F_DeptId.ToString();
                                            Model.T_Sys_Department pdModel = departmentBLL.GetModel(pdModel1.F_ParentId);
                                            if (pdModel != null)
                                            {
                                                model.F_AreaID = pdModel1.F_DeptId.ToString();
                                            }
                                        }
                                    }
                                    model.F_CustomerCode = dModel.F_CustomerID.ToString();
                                    model.F_Salesman = dr["业务员"].ToString();
                                    model.F_CreateBy = usercode;
                                    model.F_CreateOn = DateTime.Now;
                                    model.F_IsDelete = 0;
                                    #endregion
                                    cusbll.Add(model);
                                    if (dr["物料编码"].ToString() != "")
                                    {
                                        if (valcode(dr["物料编码"].ToString(), 11))
                                        {
                                            dModel.F_MaterialID = dr["物料编码"].ToString();
                                        }
                                        else
                                        {
                                            msg = msg + "第" + headrow + "行，物料编码为11位纯数字，未导入<br>";
                                            return Error(msg);
                                        }
                                    }
                                    else
                                    {
                                        while (true)
                                        {
                                            while (true)
                                            {
                                                if (!gematerque(0, GetIntCode()))
                                                {
                                                    dModel.F_MaterialID = GetIntCode();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    var Materia = new Model.T_Wo_MaterialManage();
                                    #region
                                    Materia.F_MaterialCode = dModel.F_MaterialID;//物料编号
                                    Materia.F_MaterialName = dr["物料名称"].ToString();//物料名称
                                    Materia.F_Model = dr["型号"].ToString();//型号
                                    Materia.F_Specs = dr["规格"].ToString();//规格
                                    Materia.F_Level1 = dr["一级分类"].ToString();//一级分类
                                    Materia.F_Level2 = dr["二级分类"].ToString();//二级分类
                                    Materia.F_Level3 = dr["三级分类"].ToString();//三级分类
                                    Materia.F_Brand = dr["品牌"].ToString();//品牌
                                    Materia.F_MaterialEffect = dr["复合肥肥效"].ToString();//复合肥肥效
                                    Materia.F_Craft = dr["工艺"].ToString();//工艺
                                    Materia.F_Pipeline = dr["产品线"].ToString();//产品线
                                    Materia.F_IsDelete = 0;
                                    Materia.F_CreateOn = DateTime.Now;
                                    Materia.F_CreateBy = CurrentUser.UserData.F_UserCode;
                                    #endregion
                                    int b = mmBLL.Add(Materia);
                                    if (dr["生产批次号"].ToString() != "")
                                    {
                                        if (vaBatchNumber(dr["生产批次号"].ToString()))
                                        {
                                            dModel.F_BatchNumber = dr["生产批次号"].ToString();
                                        }
                                        else
                                        {
                                            msg = msg + "第" + headrow + "行，生产批次号错误，未导入<br>";
                                            return Error(msg);
                                        }
                                    }
                                    dModel.F_CJ_Time = DateTime.Parse(dr["抽检时间"].ToString());
                                    dModel.F_CJ_Level = dr["抽检级别"].ToString();
                                    dModel.F_CJ_Unit = dr["抽检单位"].ToString();
                                    dModel.F_CJ_TestUnit = dr["化验单位"].ToString();
                                    dModel.F_CJ_Tonnage = dr["抽检吨数"].ToString();
                                    dModel.F_CJ_BagNo = dr["抽检袋数"].ToString();
                                    dModel.F_SC_ProductBase = dr["生产基地"].ToString();
                                    dModel.F_SC_CJ_SpotResult = dr["抽检结果"].ToString();
                                    dModel.F_SC_CJ_SelfResult = dr["自检结果"].ToString();
                                    dModel.F_SC_CJ_ApprovalNo = dr["对应审批工作流单号"].ToString();
                                    dModel.F_SC_CJ_ReturnAccount = dr["确认返账金额"].ToString();
                                    dModel.F_ZL_CJ_IsRecord = dr["是否备案"].ToString();
                                }
                                #endregion
                                #endregion
                                var res = workOrder.Add(dModel);
                                if (res > 0)
                                {
                                    addoptlog(usercode, ip, EnumOpt.import.ToString(), res.ToString(), "导入成功,导入的文件为：" + newpath + ",当前为第" + headrow + "行");
                                }
                                else
                                {

                                    msg = msg + "第" + headrow + "行，导入失败<br>";
                                }


                            }
                            else
                                msg = msg + "第" + headrow + "行，未选择工单类型，未导入<br>";
                            #endregion
                        }
                        if (string.IsNullOrEmpty(msg))
                            return Success("导入成功 ");
                        else
                            return Error(msg);
                    }
                }
                return Error("数据源上传失败");
            }
            return Error("用户登录失败，请重新登录");
        }
        /// <summary>
        /// 验证客户编号是否唯一
        /// </summary>
        private bool getunique(int id, string code)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_CustomerCode='" + code + "')";
            if (id > 0)
                sql += " and F_CustomerId<>" + id;
            var count = cusbll.GetModelList(sql).Count();

            return count > 0;
        }

        /// <summary>
        /// 验证物料编号是否唯一
        /// </summary>
        private bool gematerque(int id, string code)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_MaterialCode='" + code + "')";
            if (id > 0)
                sql += " and F_Id<>" + id;
            var count = mmBLL.GetModelList(sql).Count();

            return count > 0;
        }
        private string GetCusCode(int i)
        {
            DateTime times = DateTime.Now.AddMinutes(i);
            string time = times.ToString("yyMMddhhmm");
            return time;
        }
        private string GetIntCode()
        {
            string time = DateTime.Now.ToString("hhmmss");
            Random ran = new Random();
            int RandKey = ran.Next(1000, 9999);
            string timecode = 3 + "" + RandKey + "" + time;
            return timecode;
        }
        /// <summary>
        /// 更新工单---判断外线超时工单
        /// </summary>
        private bool Refresh()
        {
            int type = 0;
            var modlelist = workOrder.GetModelList("  F_IsDelete=0" + "and F_IsOver=0" + " and F_State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," +
                (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.finish + ")");
            if (modlelist.Count > 0)
            {
                foreach (var it in modlelist)
                {
                    if (TimeforOver(it.F_ID))
                    {
                        type = 0;
                    }
                    else
                    {
                        type = 1;
                    }
                    if (type != it.F_IsOver)
                    {
                        it.F_IsOver = type;
                        bool n = workOrder.Update(it);
                        if (!n)
                        {
                            return false;
                        }
                    }
                }

            }
            return true;
        }
        /// <summary>
        /// 更新工单---判断内线超时工单
        /// </summary>
        private bool Refresh2()
        {
            int type = 0;
            var modlelist = workOrder.GetModelList("  F_IsDelete=0" + "and F_IsOver in(0,1)" + " and F_State2 in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," +
                (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.finish + ")");
            if (modlelist.Count > 0)
            {
                foreach (var it in modlelist)
                {
                    if (TimeforOver(it.F_ID, 2))
                    {
                        type = 0;
                    }
                    else
                    {
                        type = 2;
                    }
                    if (type != it.F_IsOver)
                    {
                        if (it.F_IsOver == 1)
                        {
                            if (type == 2)
                            {
                                it.F_IsOver = 3;
                            }
                            else
                            {
                                it.F_IsOver = 1;
                            }
                        }
                        else
                        {
                            it.F_IsOver = type;
                        }
                        bool n = workOrder.Update(it);
                        if (!n)
                        {
                            return false;
                        }
                    }
                }

            }
            return true;
        }
        /// <summary>
        /// 抄送工单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="content"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult SendCopy(int id = 0, string content = "", string users="")
        {

            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (id <= 0)
                    return Error("请选择工单");
                if (string.IsNullOrEmpty(users))
                    return Error("请选择抄送部门");
                JavaScriptSerializer Serializer = new JavaScriptSerializer();   //实例化⼀个能够序列化数据的类
                List<CopyMessage> list = Serializer.Deserialize<List<CopyMessage>>(users);
                var model = workOrder.GetModel(id);
                if (model != null)
                {
                    string userstr = "";
                    string deptmessage = "", deptname1 = "";
                    var dept1 = new BLL.T_Sys_Department().GetModel(ua.F_DeptId);
                    if (dept1 != null)
                        deptname1 = dept1.F_DeptName;
                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            string username = string.Empty;
                            var deptmodel = new BLL.T_Sys_Department().GetModel(Convert.ToInt32(item.deptid));
                            if (deptmodel == null)
                                return Error("抄送部门不存在！");
                            var clus = item.ucodelist;
                            Model.T_Wo_WorkCopy t_Wo_WorkCopy = new Model.T_Wo_WorkCopy();
                            if (clus.Count > 0)
                            {
                                t_Wo_WorkCopy.F_Flag = 0;
                                t_Wo_WorkCopy.F_SendCopyUser = string.Join(",",clus.ToArray());
                            }
                            else
                            {
                                t_Wo_WorkCopy.F_Flag = 1;
                                t_Wo_WorkCopy.F_SendCopyUser = "";
                            }
                            t_Wo_WorkCopy.F_WorkOrderID = model.F_ID;
                            t_Wo_WorkCopy.F_CreateOn = DateTime.Now;
                            t_Wo_WorkCopy.F_Content = content;
                            t_Wo_WorkCopy.F_CreateBy = ua.F_UserId.ToString();
                            t_Wo_WorkCopy.F_SendCopyOn = DateTime.Now;                      
                            t_Wo_WorkCopy.F_State = model.F_State;
                            t_Wo_WorkCopy.F_SendCopyDepts = Convert.ToInt32(item.deptid);
                            if (new BLL.T_Wo_WorkCopy().Add(t_Wo_WorkCopy) > 0)
                            {
                                #region 发送短信
                                int sms = 0;
                                if (clus.Count> 0)
                                {
                                    foreach (var noticlus in clus)
                                    {
                                        var usermodel = new BLL.T_Sys_UserAccount().GetModel(noticlus);
                                        username=string.IsNullOrEmpty(username)? usermodel.F_UserName: username+"，"+usermodel.F_UserName;
                                        string[] mag = { };
                                        if (!string.IsNullOrEmpty(usermodel.F_Mobile))
                                        {
                                            //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, noticlus.F_Mobile.Trim());
                                            //bool n = new SMSController().AddSmS(noticlus.F_Mobile.Trim(), "抄送工单", ua.F_UserId);
                                        }
                                    }
                                }
                                else
                                {
                                    var usermodel = new BLL.T_Sys_UserAccount().GetModelList($"F_DeptId={Convert.ToInt32(item.deptid)}");
                                    if (usermodel.Count > 0)
                                    {
                                        foreach (var user in usermodel)
                                        {
                                            username = string.IsNullOrEmpty(username) ? user.F_UserName : username + "，" + user.F_UserName;
                                            string[] mag = { };
                                            if (!string.IsNullOrEmpty(user.F_Mobile))
                                            {
                                                //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, noticlus.F_Mobile.Trim());
                                                //bool n = new SMSController().AddSmS(noticlus.F_Mobile.Trim(), "抄送工单", ua.F_UserId);
                                            }
                                        }
                                    }
                                }
                                #endregion
                            }
                            deptmessage =string.IsNullOrEmpty(deptmessage)? deptmodel.F_DeptName+"-"+ username: deptmessage+"；"+deptmodel.F_DeptName + "-" + username;
                        }
                        string message = "抄送工单给" + deptmessage;
                        if (!string.IsNullOrEmpty(content))
                            message += "，抄送内容：" + content;
                        AddLog(model.F_ID, model.F_State.Value, deptname1 + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + message, (int)EnumItemType.Copy, (int)EnumItemOpt.Copy, "", 0, ua, 0, 0, "", 1);
                        return Success("抄送成功");                  
                    }                  
                }
                else
                    return Error("工单不存在");

            }
            return Error("无操作权限！");
        }



        /// <summary>
        /// 获取催办工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUrgeList(string code, string cusname, string keywords, string cusphone, string companyname, string province, string city,
            string country, string township, string touser, int source = -1, int type = 0, int state = -1, int pageindex = 1, int pagesize = 10)
        {

            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string sql = "";

                DataTable dt = new DataTable();
                #region 筛选条件
                if (type > 0 && type < 6)//工单类型
                    sql += $" and F_Type=" + type;
                if (state >= 0)//工单状态
                    sql += $" and F_State=" + state;

                if (source > 0)//工单来源
                {
                    if (source == 1)
                        sql += $" and F_Source in (1,'')";
                    else
                        sql += $" and F_Source='" + source + "'";
                }
                if (!string.IsNullOrWhiteSpace(touser))//参与人
                    sql += $" and F_DealBy like '%" + touser.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(code))//工单编号
                    sql += $" and F_WorkOrderCode like '%" + code.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusname))//客户姓名
                    sql += $" and F_CusName like '%" + cusname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                    sql += $"  and F_WorkOrderCode like '%" + keywords.Trim() + "%' or F_CusName like '%" + keywords.Trim() + "%'or F_CusPhone like '%" + keywords.Trim() + "%'  ";
                if (!string.IsNullOrWhiteSpace(cusphone))//客户电话
                    sql += $" and F_CusPhone like '%" + cusphone.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(companyname))//公司名称
                    sql += $" and F_CompanyName like '%" + companyname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//省
                    sql += $" and F_IncidentProvince like '%" + province.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//市
                    sql += $" and F_IncidentCity like '%" + city.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//县
                    sql += $" and F_IncidentCountry like '%" + country.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//乡
                    sql += $" and F_IncidentTownship like '%" + township.Trim() + "%'";
                //sql += $" and F_State !=" + 10;
                //sql += $" and F_State !=" + 11;
                sql += $" and (F_State not in(10,11) or F_State2 not in (10,11)) ";
                #endregion
                int recordCount = 0;
                var list = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.urge);
                string str = "";
                foreach (var it in list)
                {
                    if (str != "")
                        str += "," + it.F_WoID;
                    else
                        str = "" + it.F_WoID;
                }
                if (str != "")
                {
                    sql += $"  and T_Wo_WorkOrder.F_ID in(" + str + ")";
                }
                else
                {
                    return Success("暂无工单");
                }

                if (!string.IsNullOrWhiteSpace(sql))
                {

                    dt = BLL.PagerBLL.GetListPager(
                        "T_Wo_WorkOrder",
                        "F_ID",
                        "*",
                        sql,
                       "ORDER BY T_Wo_WorkOrder.F_ID desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);
                    List<Model.T_Wo_WorkOrder> modlelist = new BLL.T_Wo_WorkOrder().DataTableToList(dt);
                    List<WorkOrderNewInput> Input = modeltooip(modlelist);
                    if (Input != null)
                    {
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            rows = Input,
                            total = recordCount
                        };
                        return Content(obj.ToJson());
                    }
                    else
                    {
                        return Success("暂无工单"); ;
                    }

                }
                else
                {
                    return Success("暂无工单"); ;
                }
            }
            else
            {
                return Error("无操作权限！");
            }

        }
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="usercode">操作人工号</param>
        /// <param name="ip">操作人IP</param>
        /// <param name="optcode">操作编号</param>
        /// <param name="optid">操作id</param>
        /// <param name="des">操作描述</param>
        private void addoptlog(string usercode, string ip, string optcode, string optid, string des)
        {
            new BLL.T_Sys_OperateLogs().AddOptLog("客户管理", usercode, ip, des, optcode, "T_Cus_CustomerBaseNew", optid);
        }
        /// <summary>
        /// 验证客户电话是否唯一
        /// </summary>
        private bool getunphone(int id, string phone)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_LegalPhone='" + phone + "')";
            if (id > 0)
                sql += " and F_CustomerId<>" + id;
            var count = cusbll.GetModelList(sql).Count();

            return count > 0;
        }
        public Model.T_Sys_UserAccount GetUser(Model.T_Sys_UserAccount ua)
        {
            if (ua != null)
            {
                //  int userId = CurrentUser.UserData.F_UserId;
                //   Model.T_Sys_UserAccount ua = userAccountBLL.GetModel(userId);

                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                //  var dept = departmentBLL.GetModel(deptmodel.F_ParentId);
                #region 业务员

                if (ro.F_RoleCode == "YWY")
                {
                    if (deptmodel != null)
                    {
                        Model.T_Sys_UserAccount userModel = sysUserAccountBll.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=60 ").FirstOrDefault();
                        if (userModel != null)
                            return userModel;
                        else
                        {
                            Model.T_Sys_UserAccount userModel1 = sysUserAccountBll.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                            return userModel1;
                        }
                        //if (deptmodel.F_Layer == 2)
                        //{
                        //    Model.T_Sys_UserAccount userModel = sysUserAccountBll.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=60 ").FirstOrDefault();
                        //    if (userModel != null)
                        //        return userModel;
                        //    else
                        //    {
                        //        var dept = departmentBLL.GetModel(deptmodel.F_ParentId);
                        //        if (dept != null)
                        //        {
                        //            Model.T_Sys_UserAccount userModel1 = sysUserAccountBll.GetModelList(" F_DeptId=" + dept.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                        //            return userModel1;
                        //        }
                        //    }
                        //}
                        //if (deptmodel.F_Layer == 1)
                        //{
                        //    Model.T_Sys_UserAccount userModel = sysUserAccountBll.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                        //    return userModel;
                        //}
                    }
                    else
                    {
                        return null;
                    }
                }
                #endregion
                #region 大区经理

                else if (ro.F_RoleCode == "DQJL")
                {
                    return null;
                }
                #endregion
                #region 分公司经理

                else if (ro.F_RoleCode == "FGSJL")
                {
                    if (deptmodel != null)
                    {
                        var dept = departmentBLL.GetModel(deptmodel.F_ParentId);
                        if (dept != null)
                        {
                            Model.T_Sys_UserAccount userModel = sysUserAccountBll.GetModelList(" F_DeptId=" + dept.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                            return userModel;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                }
                #endregion
                return null;
            }
            else
            {
                return null;
            }
        }

        public static bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");

        }
        /// <summary>
        /// 添加工单
        /// </summary>
        /// <returns></returns>
        public ActionResult Add(WorkOrderNewInput input, int overtime = 0, int sms = 0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string usercode = CurrentUser.UserData.F_UserCode;
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);

                if (!(input.F_Type > 0 && input.F_Type < 6))
                    return Error("工单类型错误！");
                if (string.IsNullOrEmpty(input.F_CusName))
                    return Error("请输入客户姓名！");
                if (input.F_Type == 2 || input.F_Type == 5)
                {
                    if (string.IsNullOrEmpty(input.F_SalesBase))
                        return Error("请输入基地！");
                    if (string.IsNullOrEmpty(input.F_QuestionType))
                        return Error("请选择问题类别！");
                }

                if (string.IsNullOrEmpty(input.F_CusPhone))
                    return Error("请输入客户电话！");
                //if (!string.IsNullOrEmpty(input.F_BatchNumber) && !vaBatchNumber(input.F_BatchNumber.Trim()))
                //{
                //    return Error("请输入正确的生产批次号！");
                //}
                //else
                //{
                //    if (!string.IsNullOrEmpty(input.F_BatchNumber))
                //    {
                //        var prono = input.F_BatchNumber.Substring(0, 6);
                //        try
                //        {
                //            var pronos = DateTime.ParseExact(prono, "yyMMdd", null).ToString("yyyy-MM-dd");
                //            var protime = Convert.ToDateTime(pronos);
                //            if (DateTime.Parse(pronos) > DateTime.Now)
                //            {
                //                return Error("生产批次号错误，生产日期不能大于当前时间！");
                //            }
                //        }
                //        catch
                //        {
                //            return Error("生产批次号错误，日期格式错误！");
                //        }
                //    }
                //}
                if (!string.IsNullOrEmpty(input.F_CustomerID) && !valcode(input.F_CustomerID.ToString(), 10))
                    return Error("客户编号为10为纯数字！");

                if (!string.IsNullOrEmpty(input.F_MaterialID) && !valcode(input.F_MaterialID.ToString(), 11))
                    return Error("物料编码为11为纯数字！");
                if (!string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var Customer = cusbll.GetModel(input.F_CustomerID.Trim());
                    if (Customer == null)
                        return Error("无此客户编码！");
                }
                if (!string.IsNullOrWhiteSpace(input.F_MaterialID))
                {
                    var Customer = mmBLL.GetModel(input.F_MaterialID.Trim());
                    if (Customer == null)
                        return Error("无此物料编码！");
                }
                if (input.F_Type == 3)
                {
                    if (string.IsNullOrEmpty(input.F_Files))
                        return Error("请上传抽检单");
                    if (string.IsNullOrEmpty(input.F_CJ_Time.ToString()))
                        return Error("请选择抽检时间");
                    if(string.IsNullOrEmpty(input.F_MailingNumber))
                        return Error("如非邮寄请填自送(快递单号写送样人手机号)");
                    if (string.IsNullOrEmpty(input.F_ExpressName))
                        return Error("如非邮寄请填自送");
                }
                if (!string.IsNullOrEmpty(input.F_SalesPhone))
                {
                    if (!IsNumeric(input.F_SalesPhone))
                        return Error("请输入正确的业务员电话");
                }

                var model = new Model.T_Wo_WorkOrder();
                #region 保存客户基本信息
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                model = inputtoobj(model, input, 2);
                model.F_limit = overtime;
                if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "YWY")
                {
                    model.F_State = (int)EnumWorkOrderState.audit;
                    model.F_State2 = (int)EnumWorkOrderState.audit;
                }
                #endregion
                long n = workOrder.Add(model);
                if (n > 0)
                {
                    string deptname = "";
                    var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    Model.T_Wo_WorkOrder modlelist = new BLL.T_Wo_WorkOrder().GetModel(n);

                    if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "YWY")
                    {

                        if (GetUser(ua) != null)
                        {
                            var user = GetUser(ua);
                            string deptname1 = "";
                            var deptmodel1 = departmentBLL.GetModel(user.F_DeptId);
                            if (deptmodel1 != null)
                            {
                                deptname1 = deptmodel1.F_DeptName + "-";
                            }

                            AddLog(modlelist.F_ID, 0, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "创建工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, user.F_UserCode, user.F_DeptId, ua, overtime, sms);
                            AddLog(modlelist.F_ID, modlelist.F_State.Value, deptname1 + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, ua, overtime, sms);
                            if (sms == 1 && !string.IsNullOrEmpty(user.F_Mobile))
                            {
                                SendSms(model.F_Type, user.F_Mobile, ua.F_UserId);
                            }
                        }
                        else
                        {

                            int dapt = 0, nextda = 0;
                            var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
                            string deptneme = "";
                            if (deptmodel1 != null)
                            {
                                dapt = deptmodel1.F_ParentId;
                                deptneme = deptmodel1.F_DeptName;
                            }
                            AddLog(modlelist.F_ID, 0, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "创建工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, "", 0, ua, overtime, sms);
                            string opt = "";

                            //if (dapt != 0)
                            //{
                            if (CirculMarket(ua.F_DeptId, 11))
                            {
                                nextda = 37;
                                opt = "流转市场管理科";
                            }
                            else if (CirculMarket(ua.F_DeptId, 14))
                            {
                                nextda = 57;
                                opt = "流转营销管理处";
                            }
                            else if (CirculMarket(ua.F_DeptId, 15))
                            {
                                nextda = 74;
                                opt = "流转策划推广";
                            }
                            else if (CirculMarket(ua.F_DeptId, 16))
                            {
                                nextda = 88;
                                opt = "流转销售部";
                            }
                            else if (CirculMarket(ua.F_DeptId, 18))
                            {
                                nextda = 268;
                                opt = "流转车用尿素";

                            }

                            else if (CirculMarket(ua.F_DeptId, 20))
                            {
                                nextda = 295;
                                opt = "流转新乡黑科质检";
                            }
                            else if (CirculMarket(ua.F_DeptId, 332))
                            {
                                nextda = 339;
                                opt = "流转营销管理处";


                            }
                            else if (ua.F_DeptId == 17 || ua.F_DeptId == 19 || ua.F_DeptId == 20 || ua.F_DeptId == 21)
                            {
                                nextda = ua.F_DeptId;
                                opt = "流转" + deptname;
                            }
                            //}
                            if (nextda != 0)
                            {
                                var res = AssignWO(ua, modlelist, input, opt, "", nextda, 0, 0, 0, 0, 0, 0, "", 1);
                                if (res)
                                    return Success("添加成功");
                                else
                                    return Error("流转失败！");
                            }
                            else
                            {
                                return Error("流转失败！");
                            }
                        }
                    }
                    else
                    {
                        AddLog(modlelist.F_ID, modlelist.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "创建工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, "", 0, ua, overtime, sms);
                    }
                    return Success("添加成功！");

                }
                else
                    return Error("添加失败！");
            }
            else
            {
                return Error("无操作权限！");
            }
        }

        /// <summary>
        /// 判断市场管理科
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="pdeptid"></param>
        /// <returns></returns>
        public bool CirculMarket(int deptid, int pdeptid)
        {
            string sql = " F_State=1 ";
            string dptcode = departmentBLL.GetModel(pdeptid).F_DeptCode;
            string arrsql = " select F_DeptCode from T_Sys_Department where F_DeptCode LIKE '" + dptcode + "%' ";
            sql += $" and F_DeptCode in ({arrsql}) and F_DeptId=" + deptid;
            var modellist = departmentBLL.GetModelList(sql);
            if (modellist.Count > 0)
                return true;
            else return false;
        }
        /// <summary>
        /// 添加客户
        /// </summary>
        private Model.T_Cus_CustomerBaseNew inputtooCustomer(Model.T_Cus_CustomerBaseNew model, WorkOrderNewInput input)
        {
            var newmodel = model;
            if (!string.IsNullOrWhiteSpace(input.F_CustomerID.ToString()))
                model.F_CustomerCode = input.F_CustomerID.ToString();
            else
                model.F_CustomerCode = model.F_CustomerCode;
            if (!string.IsNullOrWhiteSpace(input.F_CompanyName))
                model.F_CompanyName = input.F_CompanyName;
            #region 基本字段
            if (!string.IsNullOrEmpty(input.F_AreaName))
            {
                Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                try
                {
                    pdModel = departmentBLL.GetModel(int.Parse(input.F_AreaName));
                }
                catch
                {
                    pdModel = departmentBLL.GetModel(input.F_AreaName);
                }
                model.F_AreaID = pdModel.F_DeptId.ToString();
            }
            else
            {
                model.F_AreaID = "";
            }

            if (!string.IsNullOrEmpty(input.F_BranchName))
            {
                Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                try
                {
                    pdModel = departmentBLL.GetModel(int.Parse(input.F_BranchName));
                }
                catch
                {
                    pdModel = departmentBLL.GetModel(input.F_BranchName);
                }
                model.F_BranchID = pdModel.F_DeptId.ToString();
            }
            else
            {
                model.F_BranchID = "";
            }
            model.F_Salesman = input.F_Salesman;//业务员
            model.F_SalesPhone = input.F_SalesPhone;//业务员电话
            model.F_Channel = input.F_Channel;// 渠道类型:总经销、二级商、种田大户、农户、化工客户、公司员工
            model.F_Legal = input.F_CusName;//法人 
            model.F_LegalPhone = input.F_CusPhone;//法人电话
            model.F_AddressProvince = input.F_AddressProvince;//省
            model.F_AddressCity = input.F_AddressCity;//市
            model.F_AddressCountry = input.F_AddressCountry;//县
            model.F_AddressTownship = input.F_AddressTownship;//乡
            model.F_AddressFull = input.F_AddressFull;//详细地址
            model.F_Brands = input.F_Brands;// 经营品牌:心连心、手拉手、沃利沃、双心、空
            model.F_IsRunXLX = input.F_IsRunXLX;// 是否经营心连心:是、否
            model.F_AnnualSales = input.F_AnnualSales;//年销量
            model.F_Formula = input.F_Formula;//配方
            model.F_RaiseCrops = input.F_RaiseCrops;//种植作物
            model.F_PlantingArea = input.F_PlantingArea;//种植面积
            model.F_FertilizerBrand = input.F_FertilizerBrand;//用肥品牌
            model.F_FileId = 0;
            #endregion
            return model;
        }
        public ActionResult DeleteWorkOrder(int id)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                if (id <= 0)
                    return Error("参数错误！");
                var model = workOrder.GetModel(id);
                if (model == null)
                    return Error("查询不到此工单！");
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua == null)
                {
                    return Error("无操作权限！");
                }
                if (model.F_CreateBy != ua.F_UserCode)
                {
                    return Error("非创建人不能删除工单！");
                }
                if (workOrder.DeleteList(id.ToString()))
                {
                    return Success("设置成功");
                }
                else
                {
                    return Error("设置失败");
                }
            }
            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrder(string[] ids)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {

                if (ids != null && ids.Length > 0)
                {
                    bool res = true;
                    string idd = " ";
                    foreach (string str in ids)
                    {
                        idd += str + ",";
                    }

                    if (!string.IsNullOrEmpty(idd.Trim()))
                    {

                        if (workOrder.DeleteList(idd.TrimEnd(',')))
                        {

                            return Success("设置成功");

                        }
                        else
                        {
                            return Error("设置失败");
                        }

                    }
                    else
                    {
                        return Error("请选择工单");
                    }
                }
                else
                {
                    return Error("获取参数失败");
                }
            }
            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 修改工单
        /// </summary>
        /// <returns></returns>
        public ActionResult Update(WorkOrderNewInput input)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string usercode = CurrentUser.UserData.F_UserCode;
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                #region 添加验证判断
                if (input.F_ID <= 0)
                    return Error("参数错误！");
                if (!(input.F_Type > 0 && input.F_Type < 6))
                    return Error("工单类型错误！");
                if (string.IsNullOrEmpty(input.F_CusName))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_CusPhone))
                    return Error("请输入客户电话！");
                if (input.F_Type == 2 || input.F_Type == 5)
                {
                    if (string.IsNullOrEmpty(input.F_SalesBase))
                        return Error("请输入基地！");
                    if (string.IsNullOrEmpty(input.F_QuestionType))
                        return Error("请选择问题类别！");
                }

                //if (!string.IsNullOrEmpty(input.F_BatchNumber) && !vaBatchNumber(input.F_BatchNumber.Trim()))
                //{
                //    return Error("请输入正确的生产批次号！");
                //}
                //else
                //{
                //    if (!string.IsNullOrEmpty(input.F_BatchNumber))
                //    {
                //        var prono = input.F_BatchNumber.Substring(0, 6);
                //        try
                //        {
                //            var pronos = DateTime.ParseExact(prono, "yyMMdd", null).ToString("yyyy-MM-dd");
                //            var protime = Convert.ToDateTime(pronos);
                //            if (DateTime.Parse(pronos) > DateTime.Now)
                //            {
                //                return Error("生产批次号错误，生产日期不能大于当前时间！");
                //            }

                //        }
                //        catch
                //        {
                //            return Error("生产批次号错误，日期格式错误！");
                //        }
                //    }
                //}
                if (!string.IsNullOrEmpty(input.F_CustomerID) && !valcode(input.F_CustomerID.ToString(), 10))
                    return Error("客户编号为10为纯数字！");
                if (!string.IsNullOrEmpty(input.F_MaterialID) && !valcode(input.F_MaterialID, 11))
                    return Error("物料编码为11为纯数字！");
                #endregion
                var model = workOrder.GetModel(input.F_ID);
                if (model == null)
                    return Error("查询不到此工单！");

                if (ua.F_UserCode != "8000" & ua.F_UserCode != "9000")
                {

                    if (ro != null)
                    {
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX")
                        {
                            if (model.F_CreateBy != ua.F_UserCode)
                            {
                                return Error("非创建人不能修改工单！");
                            }
                        }
                    }
                    if (model.F_State == 2)
                    {
                        return Error("此工单已接单不能修改！");
                    }
                    else if (model.F_State == 11 || model.F_State == 10)
                    {
                        return Error("此工单已处理不能修改！");
                    }
                }

                if (!string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var Customer = cusbll.GetModel(input.F_CustomerID.Trim());
                    if (Customer == null)
                        return Error("无此客户编码！");
                }
                if (!string.IsNullOrWhiteSpace(input.F_MaterialID))
                {
                    var Customer = mmBLL.GetModel(input.F_MaterialID.Trim());
                    if (Customer == null)
                        return Error("无此物料编码！");
                }
                if (!string.IsNullOrEmpty(input.F_SalesPhone))
                {
                    if (!IsNumeric(input.F_SalesPhone))
                        return Error("请输入正确的业务员电话");
                }
                #region 保存客户基本信息
                model = inputtoobj(model, input, 1);
                #endregion
                bool n = workOrder.Update(model);
                if (n)
                {
                    WriteWorkOrderLog(model.F_WorkOrderCode, ua.F_UserCode, 0, "", 1, "修改工单");
                    #region 读取当前登录人的部门
                    string deptname = "";
                    var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    #endregion
                    AddLog(input.F_ID, model.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "修改工单", (int)EnumItemType.update, (int)EnumItemOpt.update, "", 0, ua, 0, 0, "", 1);
                    if (ro != null)
                    {
                        if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "YWY")
                        {
                            if (GetUser(ua) != null)
                            {
                                var user = GetUser(ua);
                                string deptname1 = "";
                                var deptmode = departmentBLL.GetModel(user.F_DeptId);
                                if (deptmode != null)
                                {
                                    deptname1 = deptmode.F_DeptName + "-";
                                }
                                var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
                                var itemlast = itembll.GetModelList("   F_WoID='" + model.F_ID + "' order by F_ID desc").FirstOrDefault();
                                int sms = 0;
                                if (itemlast != null)
                                    sms = (int)itemlast.F_IsSMS;
                                AddLog(input.F_ID, model.F_State.Value, deptname1 + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, ua, 0, sms);
                                if (sms == 1 && !string.IsNullOrEmpty(user.F_Mobile))
                                {
                                    SendSms(model.F_Type, user.F_Mobile, ua.F_UserId);
                                }
                            }
                            else
                            {
                                string deptname1 = "";
                                int dapt = 0, nextda = 0; string opt = "";
                                var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
                                if (deptmodel1 != null)
                                {
                                    deptname1 = deptmodel1.F_DeptName;
                                    dapt = deptmodel1.F_ParentId;
                                }
                                //if (dapt != 0)
                                //{
                                if (CirculMarket(ua.F_DeptId, 11))
                                {
                                    nextda = 37;
                                    opt = "流转市场管理科";
                                }
                                else if (CirculMarket(ua.F_DeptId, 14))
                                {
                                    nextda = 57;
                                    opt = "流转营销管理处";
                                }
                                else if (CirculMarket(ua.F_DeptId, 15))
                                {
                                    nextda = 74;
                                    opt = "流转策划推广";
                                }
                                else if (CirculMarket(ua.F_DeptId, 16))
                                {
                                    nextda = 88;
                                    opt = "流转销售部";
                                }
                                else if (CirculMarket(ua.F_DeptId, 18))
                                {
                                    nextda = 268;
                                    opt = "流转车用尿素";

                                }

                                else if (CirculMarket(ua.F_DeptId, 20))
                                {
                                    nextda = 295;
                                    opt = "流转新乡黑科质检";
                                }
                                else if (CirculMarket(ua.F_DeptId, 332))
                                {
                                    nextda = 339;
                                    opt = "流转营销管理处";

                                }
                                else if (ua.F_DeptId == 17 || ua.F_DeptId == 19 || ua.F_DeptId == 20 || ua.F_DeptId == 21)
                                {
                                    nextda = ua.F_DeptId;
                                    opt = "流转" + deptname1;
                                }
                                //}
                                if (nextda != 0)
                                {
                                    var res = AssignWO(ua, model, input, opt, "", nextda, 0, model.F_limit, 0, 0, 0, 0, "", 1);
                                    if (res)
                                        return Success("保存成功");
                                    else
                                        return Error("流转失败！");
                                }
                                else
                                {
                                    return Error("流转失败！");
                                }
                            }
                        }
                    }
                    return Success("保存成功！");
                }
                else
                    return Error("保存失败！");
            }
            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 验证生产批次号为15位
        /// </summary>
        private bool vaBatchNumber(string code)
        {
            var res = false;
            if (code.Length == 15)
            {
                char chr = code[12];
                if (chr > 'A' && chr < 'Z')
                {
                    string code1 = code.Substring(0, 12);
                    string code2 = code.Substring(15 - 2, 2);
                    if (Regex.IsMatch(code1, @"^\d{12}$") && Regex.IsMatch(code2, @"^\d{2}$"))
                        res = true;
                }
                else
                {
                    res = false;
                }


            }
            return res;
        }
        /// <summary>
        /// 验证物料编码为10位纯数字
        /// </summary>
        private bool valcode(string code, int number)
        {
            var res = false;
            //11位数字
            if (code.Length == number && Regex.IsMatch(code, @"^\d{" + number + "}$"))
                res = true;
            return res;
        }

        /// <summary>
        /// 根据model返回CustomerBaseNewInput对象
        /// </summary>
        private List<WorkOrderNewInput> modeltooip(List<Model.T_Wo_WorkOrder> model1)
        {
            int userId = CurrentUser.UserData.F_UserId;

            if (model1 != null && model1.Count > 0)
            {
                List<WorkOrderNewInput> Input = new List<WorkOrderNewInput>(model1.Count);
                for (int i = 0; i < model1.Count; i++)
                {
                    WorkOrderNewInput model = new WorkOrderNewInput();
                    Model.T_Cus_CustomerBaseNew cuModel = new Model.T_Cus_CustomerBaseNew();
                    if (!string.IsNullOrEmpty(model1[i].F_CustomerID))
                    {
                        cuModel = cusbll.GetModel(model1[i].F_CustomerID.ToString());//通过客户编号获取客户资料
                    }
                    else
                    {
                        var sql = $" and  F_LegalPhone ='" + model1[i].F_CusPhone.Trim() + "'";
                        cuModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sql).FirstOrDefault();
                    }
                    if (cuModel != null)
                    {
                        if (!string.IsNullOrEmpty(cuModel.F_AreaID))
                        {
                            Model.T_Sys_Department pdModel = new T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(cuModel.F_AreaID));//通过公司id获取部门
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(cuModel.F_AreaID);//通过公司id获取部门
                            }

                            if (pdModel != null)
                            {
                                model.F_AreaName = pdModel.F_DeptName;
                            }
                        }
                        if (!string.IsNullOrEmpty(cuModel.F_BranchID))
                        {
                            Model.T_Sys_Department pdModel1 = new T_Sys_Department();
                            try
                            {
                                pdModel1 = departmentBLL.GetModel(int.Parse(cuModel.F_BranchID));//通过公司id获取部门
                            }
                            catch
                            {
                                pdModel1 = departmentBLL.GetModel(cuModel.F_BranchID);//通过公司id获取部门
                            }
                            if (pdModel1 != null)
                            {
                                model.F_BranchName = pdModel1.F_DeptName;
                            }
                        }
                        model.F_CustomerID = cuModel.F_CustomerCode;//客户编码
                        model.F_Salesman = cuModel.F_Salesman;
                        model.F_SalesPhone = cuModel.F_SalesPhone;
                        model.F_Legal = cuModel.F_Legal;
                        model.F_LegalPhone = cuModel.F_LegalPhone;
                        model.F_AddressProvince = cuModel.F_AddressProvince;
                        model.F_AddressCity = cuModel.F_AddressCity;
                        model.F_AddressCountry = cuModel.F_AddressCountry;
                        model.F_AddressTownship = cuModel.F_AddressTownship;
                        model.F_AddressFull = cuModel.F_AddressFull;
                        model.F_Brands = cuModel.F_Brands;
                        model.F_Channel = cuModel.F_Channel;
                        model.F_CompanyName = cuModel.F_CompanyName;
                        model.F_IsRunXLX = cuModel.F_IsRunXLX;
                        model.F_AnnualSales = cuModel.F_AnnualSales;
                        model.F_Formula = cuModel.F_Formula;
                        model.F_RaiseCrops = cuModel.F_RaiseCrops;
                        model.F_PlantingArea = cuModel.F_PlantingArea;
                        model.F_FertilizerBrand = cuModel.F_FertilizerBrand;
                    }

                    if (valcode(model1[i].F_MaterialID.ToString(), 11))
                    {
                        model.F_MaterialID = model1[i].F_MaterialID;//验证物料编码为11位纯数字
                        Model.T_Wo_MaterialManage maModel = mmBLL.GetModel(model1[i].F_MaterialID.ToString());//通过物料编码获取物料信息
                        if (maModel != null)
                        {
                            model.F_MaterialName = maModel.F_MaterialName;
                            model.F_Model = maModel.F_Model;
                            model.F_Specs = maModel.F_Specs;
                            model.F_Level1 = maModel.F_Level1;
                            model.F_Level2 = maModel.F_Level2;
                            model.F_Level3 = maModel.F_Level3;
                            model.F_Brand = maModel.F_Brand;
                            model.F_MaterialEffect = maModel.F_MaterialEffect;
                            model.F_Pipeline = maModel.F_Pipeline;
                            model.F_Craft = maModel.F_Craft;
                        }
                    }
                    #region 基本字段
                    model.F_ID = model1[i].F_ID;//
                    model.F_WorkOrderCode = model1[i].F_WorkOrderCode;//工单编号
                    #region
                    if (!string.IsNullOrEmpty(model1[i].F_Source))
                    {
                        model.F_Source = int.Parse(model1[i].F_Source);//工单来源
                    }
                    else
                    {
                        model1[i].F_Source = "1";
                        model.F_Source = int.Parse(model1[i].F_Source);//工单来源
                    }
                    if (model1[i].F_Source == "1")
                    {
                        model.F_SourceName = "电话";
                    }
                    else if (model1[i].F_Source == "2")
                    {
                        model.F_SourceName = "微信业务员";
                    }
                    else if (model1[i].F_Source == "3")
                    {
                        model.F_SourceName = "微信客户";
                    }
                    else
                    {
                        model.F_SourceName = "官网";
                    }

                    model.F_Type = int.Parse(model1[i].F_Type);//工单来源
                    if (model1[i].F_Type == "1")
                    {
                        model.F_TypeName = "咨询";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else if (model1[i].F_Type == "2")
                    {
                        model.F_TypeName = "投诉";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else if (model1[i].F_Type == "3")
                    {
                        model.F_TypeName = "抽检";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else if (model1[i].F_Type == "5")
                    {
                        model.F_TypeName = "业务协办";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else
                    {
                        model.F_TypeName = "建议及其他";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    #region  外线工单状态
                    model.F_State = model1[i].F_State;
                    if (model1[i].F_State == 0)//工单状态
                    {
                        model.F_StateName = "待指派";
                    }
                    else if (model1[i].F_State == 1)
                    {
                        model.F_StateName = "待接单";
                    }
                    else if (model1[i].F_State == 2)
                    {
                        model.F_StateName = "待处理";
                    }
                    else if (model1[i].F_State == 3)
                    {
                        model.F_StateName = "已退回";
                    }
                    else if (model1[i].F_State == 4)
                    {
                        model.F_StateName = "异常退回";
                    }
                    else if (model1[i].F_State == 5)
                    {
                        model.F_StateName = "处理中";
                    }
                    else if (model1[i].F_State == 6)
                    {
                        model.F_StateName = "待回访";
                    }
                    else if (model1[i].F_State == 7)
                    {
                        model.F_StateName = "待完结";
                    }
                    else if (model1[i].F_State == 10)
                    {
                        model.F_StateName = "已处理";
                    }
                    else if (model1[i].F_State == 11)
                    {
                        model.F_StateName = "已回访";
                    }
                    else if (model1[i].F_State == 12)
                    {
                        model.F_StateName = "已退回";
                    }
                    else if (model1[i].F_State == 13)
                    {
                        model.F_StateName = "导入工单";
                    }
                    else if (model1[i].F_State == 14)
                    {
                        model.F_StateName = "待办理";
                    }
                    else if (model1[i].F_State == 15)
                    {
                        model.F_StateName = "微信未通过";
                    }
                    else if (model1[i].F_State == 16)
                    {
                        model.F_StateName = "待办理";
                    }
                    else if (model1[i].F_State == 17)
                    {
                        model.F_StateName = "已撤回待指派";
                    }
                    #endregion
                    #region  内线工单状态
                    model.F_State2 = model1[i].F_State2;
                    if (model1[i].F_State2 == 0)//工单状态
                    {
                        model.F_StateName2 = "待指派";
                    }
                    else if (model1[i].F_State2 == 1)
                    {
                        model.F_StateName2 = "待接单";
                    }
                    else if (model1[i].F_State2 == 2)
                    {
                        model.F_StateName2 = "待处理";
                    }
                    else if (model1[i].F_State2 == 3)
                    {
                        model.F_StateName2 = "已退回";
                    }
                    else if (model1[i].F_State2 == 4)
                    {
                        model.F_StateName2 = "异常退回";
                    }
                    else if (model1[i].F_State2 == 5)
                    {
                        model.F_StateName2 = "处理中";
                    }
                    else if (model1[i].F_State2 == 6)
                    {
                        model.F_StateName2 = "待回访";
                    }
                    else if (model1[i].F_State2 == 7)
                    {
                        model.F_StateName2 = "待完结";
                    }
                    else if (model1[i].F_State2 == 10)
                    {
                        model.F_StateName2 = "已处理";
                    }
                    else if (model1[i].F_State2 == 11)
                    {
                        model.F_StateName2 = "已回访";
                    }
                    else if (model1[i].F_State2 == 12)
                    {
                        model.F_StateName2 = "已退回";
                    }
                    else if (model1[i].F_State2 == 13)
                    {
                        model.F_StateName2 = "导入工单";
                    }
                    else if (model1[i].F_State2 == 14)
                    {
                        model.F_StateName2 = "待办理";
                    }
                    else if (model1[i].F_State2 == 15)
                    {
                        model.F_StateName2 = "微信未通过";
                    }
                    else if (model1[i].F_State2 == 16)
                    {
                        model.F_StateName2 = "待办理";
                    }
                    else if (model1[i].F_State2 == 17)
                    {
                        model.F_StateName2 = "已撤回待指派";
                    }
                    #endregion 内线工单状态
                    model.F_CusName = model1[i].F_CusName;//客户姓名
                    model.F_CusPhone = model1[i].F_CusPhone;//客户电话
                                                            //     model.F_CompanyName = model1[i].F_CompanyName;//公司名称
                    model.F_IncidentProvince = model1[i].F_IncidentProvince;//事发地-省
                    model.F_IncidentCity = model1[i].F_IncidentCity;//事发地-市
                    model.F_IncidentCountry = model1[i].F_IncidentCountry;//事发地-县
                    model.F_IncidentTownship = model1[i].F_IncidentTownship;//事发地-乡
                    model.F_IncidentDetailed = model1[i].F_IncidentDetailed;//事发地-详细
                    model.F_SalesBase = model1[i].F_SalesBase;//销售基地:新乡、新疆、九江、东北、其他(其它手动输入别的点选)
                    model.F_Description = model1[i].F_Description;//问题描述
                    model.F_Files = "0";//附件上传ids
                    model.F_DealType = model1[i].F_DealType;//处理方式:当即办理、电话转接、网络转办（点选）
                    model.F_WorkerBrand = model1[i].F_Brand;//工单品牌
                    //model.SuperiorOpinion = AssCont(model1[i].F_ID);//上级处理意见
                    model.SuperiorOpinion = model1[i].F_SuperiorOpinion;//处理结果-外线
                    model.SuperiorOpinion2 = model1[i].F_SuperiorOpinion2;//处理结果-内线
                    #endregion
                    if (!string.IsNullOrEmpty(model1[i].F_QuestionType))
                    {
                        try
                        {
                            int b = int.Parse(model1[i].F_QuestionType.Trim());
                            Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                            if (manage != null)
                            {
                                model.F_QuestionType = manage.F_QuestionName;//问题类别3
                                model.F_QuestionTypeid = manage.F_Id;
                                #region 20220215修改 肥效类增加作物字段
                                if (manage.F_Label == "3")
                                {
                                    Model.T_Wo_QuestionManage Manage1 = quesBLL.GetModel(int.Parse(manage.F_ParentId.ToString()));//获取问题类别2
                                    Model.T_Wo_QuestionManage Manage2 = quesBLL.GetModel(int.Parse(Manage1.F_ParentId.ToString()));//获取问题类别1
                                    model.F_QuestionTypeone = Manage2.F_QuestionName;//问题类别1
                                    model.F_QuestionTypeoneid = Manage2.F_Id;//问题类别1
                                    model.F_QuestionTypetwo = Manage1.F_QuestionName;//问题类别2
                                    model.F_QuestionTypetwoid = Manage1.F_Id;//问题类别2
                                    var cropid = 0;
                                    if (int.TryParse(model1[i].F_Crops.Trim(), out cropid))
                                    {
                                        model.F_QuestionTypefour = new BLL.T_Sys_DictionaryValue().GetModel(cropid)?.F_Name ?? "";//问题类别4
                                        model.F_QuestionTypefourid = cropid;//问题类别4
                                    }
                                }
                                #endregion
                                #region 修改前
                                //if (manage.F_Label == "3")
                                //   {
                                //    Model.T_Wo_QuestionManage Manage1 = quesBLL.GetModel(int.Parse(manage.F_ParentId.ToString()));//获取问题类别
                                //    Model.T_Wo_QuestionManage Manage2 = quesBLL.GetModel(int.Parse(Manage1.F_ParentId.ToString()));//获取问题类别
                                //    model.F_QuestionTypeone = Manage2.F_QuestionName;//问题类别1
                                //    model.F_QuestionTypeoneid = Manage2.F_Id ;//问题类别1
                                //    model.F_QuestionTypetwo = Manage1.F_QuestionName;//问题类别2
                                //    model.F_QuestionTypetwoid = Manage1.F_Id;//问题类别2

                                //}
                                #endregion
                            }

                        }
                        catch (Exception)
                        {
                            model.F_QuestionType = model1[i].F_QuestionType; //问题类别（投诉抽捡和咨询类别不一样）
                        }
                    }
                    #region 投诉类
                    model.F_BatchNumber = model1[i].F_BatchNumber;//生产批次号
                    model.F_TS_Formula = model1[i].F_TS_Formula;// 投诉-配方
                    model.F_TS_Category = model1[i].F_TS_Category;//投诉-产品种类：化肥、化工、其他
                    if (!string.IsNullOrEmpty(model1[i].F_TS_Quantity))
                    {
                        model.F_TS_Quantity = model1[i].F_TS_Quantity;//投诉-问题数量（吨）
                    }
                    else
                        model.F_TS_Quantity = "";
                    model.F_TS_Level = model1[i].F_TS_Level;//投诉-重要级别：轻微、一般、较大、重大

                    if (model1[i].F_SC_PreliminaryOpinion == "退换货")
                    {
                        List<T_Wo_MaterialItems> materlist = new BLL.T_Wo_MaterialItems().GetModelList($" F_WoID={model.F_ID}");
                        if (materlist != null)
                        {
                            model.MaterialItems = materlist;
                        }
                    }
                    else
                     model.MaterialItems = null;
                    model.F_CarNumber= model1[i].F_CarNumber;
                    model.F_DrivePhone = model1[i].F_DrivePhone;
                    model.F_LoadingFee = model1[i].F_LoadingFee;
                    model.F_UnLoadingFee = model1[i].F_UnLoadingFee;
                    model.F_MaterialFee = model1[i].F_MaterialFee;
                    model.F_EventReason= model1[i].F_EventReason;  //事件原因-内线
                    model.F_EventReason2 = model1[i].F_EventReason2;  //事件原因-内线
                    #endregion
                    #region 咨询类
                    //  model.F_ZX_ProName = model1[i].F_ZX_ProName;//咨询-产品名称：三聚氰胺、甲醇、液氨、二甲醚、糠醇、其他
                    model.F_ZX_Quantity = model1[i].F_ZX_Quantity;// 咨询-问题数量（吨）
                    model.F_ZX_Area = model1[i].F_ZX_Area;// 咨询-大区
                    model.F_ZX_Branch = model1[i].F_ZX_Branch;// 咨询-分公司
                    #endregion
                    #region 抽检类
                    model.F_CJ_Time = model1[i].F_CJ_Time;// 抽检-抽检时间
                    model.F_CJ_Level = model1[i].F_CJ_Level;// 抽检-抽检级别：乡镇级、县级、市级、省级及以上、个人送检
                    model.F_CJ_Unit = model1[i].F_CJ_Unit;// 抽检-抽检单位：市场监督、农业部、土肥站、工商、联合执法、其他
                    model.F_CJ_TestUnit = model1[i].F_CJ_TestUnit;//抽检-化验单位
                    model.F_CJ_Tonnage = model1[i].F_CJ_Tonnage;//抽检-抽检吨数
                    model.F_CJ_BagNo = model1[i].F_CJ_BagNo;//抽检-抽检袋数
                    model.F_CJ_Outlay = model1[i].F_CJ_Outlay;//抽检-公关费用金额：单位元
                    model.F_Production = model1[i].F_Production;
                    model.F_DealBy = model1[i].F_DealBy;//处理人
                    model.F_DealTime = model1[i].F_DealTime;//处理时间
                    model.F_DealContent = model1[i].F_DealContent;//处理内容---外线
                    model.F_DealContent2 = model1[i].F_DealContent2;//处理内容---内线
                    model.F_DealResult = model1[i].F_DealResult;//处理结果
                    model.F_DealReasons = model1[i].F_DealReasons;//未处理原因
                    model.F_SC_ProductBase = model1[i].F_SC_ProductBase;//市场管理科-生产基地（新乡、新疆、九江、东北、贴牌、无法确定）
                    model.F_SC_PreliminaryOpinion = model1[i].F_SC_PreliminaryOpinion;// 市场管理科-初审意见:退货、换货、补偿、自行处理
                    model.F_SC_QualityMonth = model1[i].F_SC_QualityMonth;//市场管理科-超出质保期限（算法：工单创建日期-生产日期，生产日期根据生产批次号获取，单位：月）
                    model.F_SC_CJ_SpotResult = model1[i].F_SC_CJ_SpotResult;/// 市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
                    model.F_SC_CJ_SelfResult = model1[i].F_SC_CJ_SelfResult;//市场管理科-抽检-自检结果
                    model.F_SC_CJ_ApprovalNo = model1[i].F_SC_CJ_ApprovalNo;// 市场管理科-抽检-对应审批工作流单号
                    model.F_SC_CJ_ReturnAccount = model1[i].F_SC_CJ_ReturnAccount;//市场管理科-抽检-确认返账金额（元）
                    model.F_ZL_QualityEventLevel = model1[i].F_ZL_QualityEventLevel;// 质量管理科-质量事件等级（未遂、一般、较大、重大）
                    model.F_ZL_ClaimAmount = model1[i].F_ZL_ClaimAmount;//质量管理科-索赔金额（单位元，对应责任单位）
                    model.F_ZL_ResponsibleUnit = model1[i].F_ZL_ResponsibleUnit;//质量管理科-责任单位（需列出，可选多个）
                    model.F_ZL_ApprovalOpinions = model1[i].F_ZL_ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                    model.F_ZL_ApprovalDisagree = model1[i].F_ZL_ApprovalDisagree;// 质量管理科-审批不同意意见
                    model.F_ZL_CompensationMethod = model1[i].F_ZL_CompensationMethod;//质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                    model.F_ZL_CompensationMoney = model1[i].F_ZL_CompensationMoney;// 质量管理科-补偿钱款
                    model.F_ZL_CResponsibleUnits = model1[i].F_ZL_CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                    model.F_ZL_Fquantity = model1[i].F_ZL_Fquantity;// 质量管理科-确认实收数量（吨）
                    model.F_ZL_ImprovementRequirements = model1[i].F_ZL_ImprovementRequirements;//质量管理科-改进要求
                    model.F_ZL_CApprovalNo = model1[i].F_ZL_CApprovalNo;//质量管理科-对应审批工作流单号
                    model.F_ZL_CJ_IsRecord = model1[i].F_ZL_CJ_IsRecord;//质量管理科-抽检-未备案、已备案
                    model.F_VisitRemarks = model1[i].F_VisitRemarks;//回访备注
                    if (model1[i].F_SMSReply == 1)
                    {
                        model.F_SMSReply = "满意";//短信回访结果
                    }
                    else if (model1[i].F_SMSReply == 2)
                    {
                        model.F_SMSReply = "一般";//短信回访结果
                    }
                    else if (model1[i].F_SMSReply == 3)
                    {
                        model.F_SMSReply = "不满意";//短信回访结果
                    }
                    else
                    {
                        model.F_SMSReply = "";//短信回访结果
                    }

                    if (model1[i].F_IsVisit == 1)
                    {

                        model.F_IsVisit = "是";//
                    }
                    else
                    {
                        model.F_IsVisit = "否";//
                    }
                    #region 外线超时时间计算
                    float c = TimeToOver(model1[i].F_ID, model1[i].F_limit);
                    float a = Math.Abs(c);
                    int days = (int)Math.Floor(Convert.ToDouble(a / 24));
                    int hours = days > 0
                                   ? (int)Math.Floor(Convert.ToDouble((a - days * 24)))
                                   : (int)Math.Floor(Convert.ToDouble(a));
                    float minutes = hours > 0
                                   ? a * 60 - days * 1440 - hours * 60
                                   : 0;
                    if (c > 0)
                        model.RemainingTime = string.Format("剩余{0:f0}天{1:f0}时{2:f0}分", days, hours, minutes);
                    else
                        model.RemainingTime = string.Format("超时{0:f0}天{1:f0}时{2:f0}分", days, hours, minutes);
                    #endregion

                    #region 内线超时时间计算
                    float c2 = TimeToOver(model1[i].F_ID, model1[i].F_limit, 2);
                    float a2 = Math.Abs(c2);
                    int days2 = (int)Math.Floor(Convert.ToDouble(a2 / 24));
                    int hours2 = days2 > 0
                                   ? (int)Math.Floor(Convert.ToDouble((a2 - days2 * 24)))
                                   : (int)Math.Floor(Convert.ToDouble(a2));
                    float minutes2 = hours2 > 0
                                   ? a2 * 60 - days2 * 1440 - hours2 * 60
                                   : 0;
                    if (c2 > 0)
                        model.RemainingTime2 = string.Format("剩余{0:f0}天{1:f0}时{2:f0}分", days2, hours2, minutes2);
                    else
                        model.RemainingTime2 = string.Format("超时{0:f0}天{1:f0}时{2:f0}分", days2, hours2, minutes2);
                    #endregion

                    model.F_VisitOn = model1[i].F_VisitOn;//回访时间
                    model.F_VisitBy = model1[i].F_VisitBy;//回访人
                    model.F_VisitResult = model1[i].F_VisitResult;//回访结果：非常满意、满意、一般、不满意
                    model.F_VisitReason = model1[i].F_VisitReason;// 回访不满意原因
                    model.F_Callresults = model1[i].F_Callresults;//呼叫结果
                    model.F_IsAudit = model1[i].F_IsAudit;//是否审核
                    model.F_Highopinions = model1[i].F_Highopinions;//高层处理意见
                    model.F_CreateOn = model1[i].F_CreateOn; ;//添加时间
                    model.F_Annotation = model1[i].F_Annotation; ;//注解
                    if (!string.IsNullOrEmpty(model1[i].F_CreateBy))
                    {
                        Model.T_Sys_UserAccount creatname = sysUserAccountBll.GetModel(model1[i].F_CreateBy);
                        if (creatname != null)
                        {
                            model.F_CreateBy = creatname.F_WorkNumber; ;//添加人
                            model.F_CreateName = creatname.F_UserName; ;//添加人
                            model.F_CreatePhone = creatname.F_Mobile;
                            model.CreateName = creatname.F_UserName + "(" + creatname.F_WorkNumber + ")";
                        }
                    }
                    model.F_UpdateBy = model1[i].F_UpdateBy;//修改人工号
                    model.F_UpdateOn = model1[i].F_UpdateOn; ;//修改人工号
                    if (model1[i].F_IsAudit != 0 && model1[i].F_IsAudit != null)
                    {
                        if (model1[i].F_AuditState == 0)
                        {
                            model.F_AuditState = "同意上报";
                        }
                        else if (model1[i].F_AuditState == 1)
                        {
                            model.F_AuditState = "驳回修订";
                        }
                        else if (model1[i].F_AuditState == 2)
                        {
                            model.F_AuditState = "强制结案";
                        }
                    }
                    else
                    {
                        model.F_AuditState = "";
                    }

                    model.F_Canal = model1[i].F_Canal;
                    model.F_limit = model1[i].F_limit;
                    int day = (int)Math.Floor(Convert.ToDouble(model.F_limit / 24));
                    int hour = day > 0
                                   ? (int)Math.Floor(Convert.ToDouble((model.F_limit - day * 24)))
                                   : (int)Math.Floor(Convert.ToDouble(model.F_limit));

                    string time = "";
                    if (day > 0) time += day + "天";
                    if (hour > 0) time += hour + "小时";
                    model.F_limitTime = time;
                    model.F_AuditBy = model1[i].F_AuditBy;//审核人
                    model.F_AuditOn = model1[i].F_AuditOn;//审核时间
                    model.F_AuditCont = model1[i].F_AuditCont;//审核内容
                    model.DelayTimelimit = DelayTimelimit(model1[i].F_ID, model1[i].F_limit);//申请时限
                    model.DelayTimename = DelayDeptid(model1[i].F_ID);//申请部门
                    model.F_Reasontimeout = model1[i].F_Reasontimeout;//超时原因
                    Model.T_Sys_UserAccount ua = new T_Sys_UserAccount();
                    if (userId > 0)
                    {
                        ua = sysUserAccountBll.GetModel(userId);
                    }
                    if (ua != null)
                    {
                        var itemlast = itembll.GetModelList("   F_WoID='" + model.F_ID + "' order by F_ID desc").FirstOrDefault();
                        if (itemlast != null)
                            model.F_UserCode = itemlast.F_CreateUser;
                        if (!string.IsNullOrEmpty(model.F_UserCode))
                        {
                            Model.T_Sys_UserAccount user = sysUserAccountBll.GetModel(model.F_UserCode);
                            if (user != null)
                                model.F_UserName = user.F_UserName;
                        }

                    }
                    //if (model1[i].F_Type != "3")
                    //{
                    //    #region 判断外线是否超时
                    //    if (TimeToOver(model1[i].F_ID, model1[i].F_limit) < 0)
                    //    {
                    //        model.F_IsOver = 1;
                    //    }
                    //    #endregion
                    //    #region 判断内线是否超时
                    //    else if (TimeToOver(model1[i].F_ID, model1[i].F_limit, 2) < 0)
                    //    {
                    //        model.F_IsOver = 2; //内线超时
                    //    }
                    //    #endregion
                    //    else
                    //    {
                    //        model.F_IsOver = model1[i].F_IsOver;
                    //    }
                    //}
                    model.F_IsOver = model1[i].F_IsOver;
                    model.F_VisitResultScore= model1[i].F_VisitResultScore;
                    model.F_EffectiveScore = model1[i].F_EffectiveScore;
                    model.F_ServiceAttitude = model1[i].F_ServiceAttitude;
                    model.F_ProductQuality = model1[i].F_ProductQuality;
                    model.F_NPS = model1[i].F_NPS;
                    model.F_EvaluationResult = model1[i].F_EvaluationResult;
                    model.F_MailingNumber = model1[i].F_MailingNumber;
                    model.F_ExpressName = model1[i].F_ExpressName;
                    model.F_WorkmanShip = model1[i].F_WorkmanShip;//质量管理科-工艺
                    model.F_Manufacturers = model1[i].F_Manufacturers;//质量管理科-原料及厂家
                    model.F_ProductionNum = model1[i].F_ProductionNum;//质量管理科-该批次生产数量
       

                    if (ua != null)
                    {
                        var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            model.F_Deptid = deptmodel.F_DeptId;
                            model.F_DeptName = deptmodel.F_DeptName;
                        }
                    }

                    #endregion
                    Input.Add(model);
                }
                return Input;
            }
            else
            {
                return null;
            }
        }
        private string AssCont(int id)
        {
            string cont = "";
            var itemlist = itembll.GetModelList("F_WoID=" + id + "and F_IsUsed=0" + "order by F_ID desc");
            if (itemlist.Count > 0)
            {
                cont = itemlist[0].F_OptContent;
            }
            return cont;
        }
        private int DelayTimelimit(int id, int limit)
        {
            int time = 0;
            var itemlist = itembll.GetModelList("F_WoID=" + id + "and F_OptType=" + (int)EnumItemOpt.Delay + "and F_ItemType = " + (int)EnumItemType.Delay);
            foreach (var it in itemlist)
            {

                time = int.Parse(it.F_LimitTime) - limit;
            }
            return time;
        }
        private string DelayDeptid(int id)
        {
            string str = "";

            var itemlist = itembll.GetModelList("F_WoID=" + id + "and F_OptType=" + (int)EnumItemOpt.Delay + "and F_ItemType = " + (int)EnumItemType.Delay);
            string usercode = "";
            foreach (var it in itemlist)
            {
                usercode = it.F_CreateUser;
            }

            if (usercode != "")
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(usercode);
                if (ua != null)
                {
                    Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                    if (dModel != null)
                    {
                        str = dModel.F_DeptName;
                    }
                }
            }

            return str;
        }
        /// <summary>
        /// 是否超时
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private float TimeToOver(int id, int limit, int flag = 1)
        {
            string strsql = "";
            if (flag == 1)
            {
                strsql = " and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = " and F_Type in(2,3)";
            }
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + "" + strsql + " and  F_WoID=" + id);
            string time1 = "", time2 = ""; int x = 0, y = 0;
            if (itemlasts.Count > 0)
            {
                for (int z = 0; z < itemlasts.Count; z++)
                {
                    if (itemlasts[z].F_WoState >= 1)
                    {
                        if (itemlasts[z].F_WoState == 1)
                        {
                            x = z;
                            time1 = itemlasts[z].F_CreateTime.ToString();
                            break;
                        }
                    }
                }
                for (int i = 0; i < itemlasts.Count; i++)
                {
                    if (itemlasts[i].F_WoState >= 1)
                    {
                        if (itemlasts[i].F_WoState == 10 || itemlasts[i].F_WoState == 11)
                        {
                            y = i;
                            time2 = itemlasts[i].F_CreateTime.ToString();
                        }
                    }
                }
                if (time2 != "")
                {
                    if (time1 != "")
                    {
                        if (y > x)
                        {
                            System.TimeSpan a = DateTime.Parse(time2) - DateTime.Parse(time1);
                            float b = limit - (float)a.TotalHours;
                            return b;
                        }
                        else
                        {
                            System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                            float b = limit - (float)a.TotalHours;
                            return b;
                        }
                    }
                    else
                    {
                        return 0;
                    }
                }
                else if (time1 != "")
                {
                    System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                    float b = limit - (float)a.TotalHours;
                    return b;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 0;
            }

        }
        /// <summary>
        /// 是否超时
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool TimeforOver(int id, int flag = 1)
        {
            string strsql = "";
            if (flag == 1)
            {
                strsql = " and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = " and F_Type in(2,3)";
            }
            var itemlasts = itembll.GetModelList("  F_WoID=" + id + strsql + "");
            // var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + id + " ");
            string time1 = "", time2 = ""; int x = 0, y = 0;
            float time = 0;
            if (itemlasts.Count > 0)
            {
                for (int z = 0; z < itemlasts.Count; z++)
                {
                    if (itemlasts[z].F_WoState >= 1)
                    {
                        if (itemlasts[z].F_WoState == 1)
                        {
                            x = z;
                            time1 = itemlasts[z].F_CreateTime.ToString();
                            time = float.Parse(itemlasts[z].F_LimitTime);
                            break; ;
                        }
                    }
                }

                for (int i = 0; i < itemlasts.Count; i++)
                {
                    if (itemlasts[i].F_WoState >= 1)
                    {
                        if (itemlasts[i].F_WoState == 10 || itemlasts[i].F_WoState == 11)
                        {
                            y = i;
                            time2 = itemlasts[i].F_CreateTime.ToString();
                        }
                    }
                }
                if (time2 != "")
                {
                    if (time1 != "")
                    {
                        if (y > x)
                        {
                            System.TimeSpan a = DateTime.Parse(time2) - DateTime.Parse(time1);


                            if ((float)a.TotalHours > time)
                            {
                                return false;
                            }
                        }
                        else
                        {
                            System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                            if ((float)a.TotalHours > time)
                            {
                                return false;
                            }
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
                else if (time1 != "")
                {
                    System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                    if ((float)a.TotalHours > time)
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return true;
            }
            return true;
        }

        private bool IsCustomerBaseNew(WorkOrderNewInput input)
        {
            bool n = false;
            if (!string.IsNullOrEmpty(input.F_CustomerID) || !string.IsNullOrEmpty(input.F_CompanyName)
               || !string.IsNullOrEmpty(input.F_AreaName) || !string.IsNullOrEmpty(input.F_BranchName)
                || !string.IsNullOrEmpty(input.F_Salesman) || !string.IsNullOrEmpty(input.F_SalesPhone)
              || !string.IsNullOrEmpty(input.F_Brands))
            {
                n = true;
            }
            return n;
        }

        /// <summary>
        /// 根据传入的对象和input的内容返回对象（添加修改使用）
        /// </summary>
        private Model.T_Wo_WorkOrder inputtoobj(Model.T_Wo_WorkOrder model, WorkOrderNewInput input, int type)
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            var newmodel = model;
            if (input.F_ID != 0)
            {
                model.F_ID = input.F_ID;

            }
            else
            {
                model.F_ID = model.F_ID;//工单ID

            }
            if (type == 2)
            {
                model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");  //工单编号  
                model.F_Source = model.F_Source;
            }
            else
            {
                model.F_WorkOrderCode = model.F_WorkOrderCode;//工单编号
                model.F_Source = model.F_Source.ToString();//工单来源
            }
            #region 基本字段
            if (input.F_Type == 2 || input.F_Type == 3 || input.F_Type==5)
            {
                if (string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var sql = $" and  F_LegalPhone  = '" + input.F_CusPhone.Trim() + "'";
                    var Customer = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sql).FirstOrDefault(); ;
                    if (Customer != null)
                    {
                        model.F_CustomerID = Customer.F_CustomerCode;
                        if (!string.IsNullOrEmpty(input.F_Salesman))
                            Customer.F_Salesman = input.F_Salesman;
                        if (!string.IsNullOrEmpty(input.F_SalesPhone))
                            Customer.F_SalesPhone = input.F_SalesPhone;
                        if (!string.IsNullOrEmpty(input.F_Brands))
                            Customer.F_Brands = input.F_Brands;

                        if (!string.IsNullOrEmpty(input.F_Channel))
                            Customer.F_Channel = input.F_Channel;
                        if (!string.IsNullOrEmpty(input.F_AreaName))
                        {
                            Model.T_Sys_Department pdModel = new T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(input.F_AreaName));
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(input.F_AreaName);
                            }
                            Customer.F_AreaID = pdModel.F_DeptId.ToString();
                        }
                        else
                        {
                            Customer.F_AreaID = "";
                        }

                        if (!string.IsNullOrEmpty(input.F_BranchName))
                        {
                            Model.T_Sys_Department pdModel = new T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(input.F_BranchName));
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(input.F_BranchName);
                            }
                            Customer.F_BranchID = pdModel.F_DeptId.ToString();
                        }
                        else
                        {
                            Customer.F_BranchID = "";
                        }
                        if (!string.IsNullOrEmpty(input.F_CompanyName))
                            Customer.F_CompanyName = input.F_CompanyName;
                        cusbll.Update(Customer);
                    }
                    else
                    {
                        if (IsCustomerBaseNew(input))
                        {

                            if (string.IsNullOrEmpty(input.F_CustomerID))
                            {
                                int i = 0;
                                while (true)
                                {
                                    if (!getunique(0, GetCusCode(i)))
                                    {
                                        input.F_CustomerID = GetCusCode(i);
                                        break;
                                    }
                                    else
                                    {
                                        i++;
                                    }
                                }
                            }
                            var CustomerBaseNewmodel = new Model.T_Cus_CustomerBaseNew();
                            CustomerBaseNewmodel.F_CustomerCode = input.F_CustomerID;
                            CustomerBaseNewmodel.F_CreateBy = usercode;
                            CustomerBaseNewmodel.F_CreateOn = DateTime.Now;
                            CustomerBaseNewmodel.F_IsDelete = 0;

                            cusbll.Add(inputtooCustomer(CustomerBaseNewmodel, input));
                        }
                    }
                }
                else
                {
                    var Customer = cusbll.GetModel(input.F_CustomerID.Trim());
                    if (Customer != null)
                    {
                        if (!string.IsNullOrEmpty(input.F_Salesman))
                            Customer.F_Salesman = input.F_Salesman;
                        if (!string.IsNullOrEmpty(input.F_SalesPhone))
                            Customer.F_SalesPhone = input.F_SalesPhone;
                        if (!string.IsNullOrEmpty(input.F_Brands))
                            Customer.F_Brands = input.F_Brands;
                        if (!string.IsNullOrEmpty(input.F_Channel))
                            Customer.F_Channel = input.F_Channel;
                        if (!string.IsNullOrEmpty(input.F_CompanyName))
                            Customer.F_CompanyName = input.F_CompanyName.Trim();
                        if (!string.IsNullOrEmpty(input.F_AreaName))
                        {
                            Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(input.F_AreaName));
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(input.F_AreaName);
                            }
                            Customer.F_AreaID = pdModel.F_DeptId.ToString();
                        }
                        else
                        {
                            Customer.F_AreaID = "";
                        }

                        if (!string.IsNullOrEmpty(input.F_BranchName))
                        {
                            {
                                Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                                try
                                {
                                    pdModel = departmentBLL.GetModel(int.Parse(input.F_BranchName));
                                }
                                catch
                                {
                                    pdModel = departmentBLL.GetModel(input.F_BranchName);
                                }
                                Customer.F_BranchID = pdModel.F_DeptId.ToString();
                            }
                        }
                        else
                        {
                            Customer.F_BranchID = "";
                        }
                        if (!string.IsNullOrEmpty(input.F_CompanyName))
                            Customer.F_CompanyName = input.F_CompanyName;
                        cusbll.Update(Customer);
                    }
                }
            }
            #endregion
            model.F_Canal = input.F_Canal;//生产批次号
            model.F_Type = input.F_Type.ToString();//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
            model.F_Production = input.F_Production;//生产单位
            model.F_CusName = input.F_CusName;//客户姓名
            model.F_CusPhone = input.F_CusPhone;//客户电话
            model.F_CompanyName = input.F_CompanyName;//公司名称
            model.F_IncidentProvince = input.F_IncidentProvince;//事发地-省
            model.F_IncidentCity = input.F_IncidentCity;//事发地-市
            model.F_IncidentCountry = input.F_IncidentCountry;//事发地-县
            model.F_IncidentTownship = input.F_IncidentTownship;//事发地-乡
            model.F_IncidentDetailed = input.F_IncidentDetailed;//事发地-详细
            model.F_SalesBase = input.F_SalesBase;//销售基地:新乡、新疆、九江、东北、其他(其它手动输入别的点选)
            model.F_Description = input.F_Description;//问题描述
            model.F_ZX_Area = input.F_ZX_Area;// 大区
            model.F_ZX_Branch = input.F_ZX_Branch;//分公司


            model.F_Brand = input.F_WorkerBrand;//工单品牌
            model.F_DealType = model.F_DealType;//处理方式:当即办理、电话转接、网络转办（点选）
            #endregion
            model.F_QuestionType = input.F_QuestionType;//问题类别（投诉抽捡和咨询类别不一样）
            model.F_CustomerID = input.F_CustomerID;//客户编号为10为纯数字
            if (!string.IsNullOrEmpty(input.F_MaterialID))
            {
                model.F_MaterialID = input.F_MaterialID.ToString();//物料编码为11为纯数字
            }
            #region 投诉类
            model.F_BatchNumber = input.F_BatchNumber;//生产批次号
            model.F_TS_Formula = input.F_TS_Formula;// 投诉-配方
            model.F_TS_Category = input.F_TS_Category;//投诉-产品种类：化肥、化工、其他
            model.F_TS_Quantity = input.F_TS_Quantity;//投诉-问题数量（吨）
            model.F_TS_Level = input.F_TS_Level;//投诉-重要级别：轻微、一般、较大、重大
            #region 肥效类增加作物字段 20220307
            if (!string.IsNullOrEmpty(input.F_Crops))
            {
                model.F_Crops = input.F_Crops;
            }
            #endregion
            #endregion
            #region 咨询类
            //   model.F_ZX_ProName = input.F_ZX_ProName;//咨询-产品名称：三聚氰胺、甲醇、液氨、二甲醚、糠醇、其他
            model.F_ZX_Quantity = input.F_ZX_Quantity;// 咨询-问题数量（吨）
            if (!string.IsNullOrEmpty(input.F_Files))
                model.F_Files = input.F_Files;//附件上传ids
            else
                model.F_Files = model.F_Files;//附件上传ids
            #endregion
            #region 抽检类
            model.F_CJ_Time = input.F_CJ_Time;// 抽检-抽检时间
            model.F_CJ_Level = input.F_CJ_Level;// 抽检-抽检级别：乡镇级、县级、市级、省级及以上、个人送检
            model.F_CJ_Unit = input.F_CJ_Unit;// 抽检-抽检单位：市场监督、农业部、土肥站、工商、联合执法、其他
            model.F_CJ_TestUnit = input.F_CJ_TestUnit;//抽检-化验单位
            model.F_CJ_Tonnage = input.F_CJ_Tonnage;//抽检-抽检吨数
            model.F_CJ_BagNo = input.F_CJ_BagNo;//抽检-抽检袋数
            model.F_CJ_Outlay = input.F_CJ_Outlay;//抽检-抽检袋数
            model.F_MailingNumber = input.F_MailingNumber;//抽检-样品邮寄单号
            model.F_ExpressName = input.F_ExpressName;//抽检-快递名称
            //model.F_Manufacturers = input.F_Manufacturers;//原料及厂家
            //model.F_ProductionNum = input.F_ProductionNum;//该批次生产数量

            // model.F_VisitRemarks = input.F_VisitRemarks;//回访备注
            //if (!string .IsNullOrEmpty (input.F_BatchNumber))
            //{
            //    if (type == 1)
            //    {
            //        model.F_SC_QualityMonth = new WorkOrderController().GetProTime(input.F_BatchNumber, DateTime.Parse(model.F_CreateOn.ToString())).ToString();
            //     }
            //    else
            //    {
            //        model.F_SC_QualityMonth = new WorkOrderController().GetProTime(input.F_BatchNumber, DateTime.Now).ToString();
            //    }
            //}

            if (type == 1)
            {
                model.F_State = model.F_State;//工单状态-外线
                model.F_State2 = model.F_State2;//工单状态-内线
                model.F_CreateOn = model.F_CreateOn;//添加时间
                model.F_CreateBy = model.F_CreateBy;//添加人
                model.F_UpdateBy = usercode;//修改人工号
                model.F_UpdateOn = DateTime.Now;//修改人工号

                if (input.F_UpdateCount != null)
                {
                    model.F_UpdateCount = model.F_UpdateCount + 1;//修改次数
                }
                else
                {
                    model.F_UpdateCount = 1;//修改次数
                }
                model.F_limit = model.F_limit;
            }
            else
            {
                model.F_State = (int)EnumWorkOrderState.neworder;
                model.F_State2 = (int)EnumWorkOrderState.neworder;
                model.F_CreateBy = usercode;
                model.F_CreateOn = DateTime.Now;
                //   model.F_limit =0;
            }
            model.F_IsVisit = 1;
            model.F_IsDelete = 0;
            model.F_IsOver = 0;
            #endregion
            return model;
        }

        /// <summary>
        /// 添加工单记录
        /// </summary>
        public long AddLog(long woid, int wostate, string content, int itemtype, int opttype, string nextuser, int nextdept, Model.T_Sys_UserAccount nowUser, float overtime, int sms, string create = "", int F_IsUsed = 0, int flag = 3)
        {
            Model.T_Wo_WorkOrderItem_New itemModel = new Model.T_Wo_WorkOrderItem_New();
            #region 
            string strsql = "";
            Model.T_Sys_RoleInfo ro = rolebll.GetModel(nowUser.F_RoleId);
            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY" && flag!=3)
            {
                strsql = $" F_OptType !=1 and isnull(F_IsUsed,'0')='0' and F_ItemType={itemtype} and  F_WoID={woid} and  F_CreateUser={nowUser.F_UserCode} and F_Type in({flag},3) ";
            }
            else
            {
                strsql = $" isnull(F_IsUsed,'0')='0' and F_ItemType={itemtype} and  F_WoID={woid} and  (F_CreateUser={nowUser.F_UserCode} or F_NextUser like '%{nowUser.F_UserCode}%')" 
                       + $" and F_Type in({flag},3)";
            }
            //处理当前工单的记录之前的记录过期
            //var itemlast = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_ItemType=" + itemtype + " and  F_WoID=" + woid + " ");
            var itemlast = itembll.GetModelList(strsql);
            if (F_IsUsed == 0)
            {
                if (itemlast != null && itemlast.Count > 0)
                {
                    foreach (var it in itemlast)
                    {
                        it.F_IsUsed = 1;
                        it.F_LimitTime = overtime.ToString();

                        itembll.Update(it);
                    }
                    itemModel.F_LastTime = itemlast.LastOrDefault().F_CreateTime;
                }
            }

            #endregion
            itemModel.F_WoID = woid;
            itemModel.F_IsSMS = sms;
            itemModel.F_WoState = wostate;
            itemModel.F_ItemType = itemtype;
            itemModel.F_OptType = opttype;
            itemModel.F_OptContent = content;
            itemModel.F_NextUser = nextuser;
            itemModel.F_NextDept = nextdept;
            itemModel.F_IsUsed = F_IsUsed;
            itemModel.F_LimitTime = overtime.ToString();
            itemModel.F_Type = flag;//区分内外线和公共部门
            if (create != "")
            {
                itemModel.F_CreateTime = DateTime.Parse(create);
            }
            else
            {
                itemModel.F_CreateTime = DateTime.Now;
            }
            itemModel.F_CreateUser = nowUser.F_UserCode;
            var res = itembll.Add(itemModel);
            return res;
        }
        public void WriteWorkOrderLog(string WorkOrderID, string UserCode, int IsDelete, string DelUserCode, int TypeId, string Remark)
        {
            var model = new Model.T_Wo_WorkOrder_Logs();
            model.WorkOrderID = WorkOrderID;        //工单编号
            model.UserCode = UserCode;              //修改人code
            model.AddTime = DateTime.Now;           //添加时间
            model.IsDelete = IsDelete;              //是否删除（0正常1删除）
            model.DelUserCode = DelUserCode;        //删除人code
            model.TypeId = TypeId;                  //类型（0添加，1修改）
            model.Remark = Remark;                  //备注
            blllogs.Add(model);
        }
        /// <summary>
        /// 创建工单时指派
        /// </summary>
        /// <returns></returns>
        public ActionResult Createass(WorkOrderNewInput input, string cont, WorkOrdeDeptment deptment, string F_Files, int isvisit = 1,
          int overtime = 0, int sms = 0, int clbm = 0, int clid = 0, int clbm2 = 0, int clid2 = 0,string jsonstr="",int flag=3)
        {
                int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string usercode = CurrentUser.UserData.F_UserCode;
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                //Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(1545);
                #region 添加验证判断
                if (!(input.F_Type > 0 && input.F_Type < 6))
                    return Error("工单类型错误！");
                //if (!string.IsNullOrEmpty(input.F_BatchNumber) && !vaBatchNumber(input.F_BatchNumber))
                //    return Error("请输入正确的生产批次号！");
                //else
                //{
                //    if (!string.IsNullOrEmpty(input.F_BatchNumber))
                //    {
                //        var prono = input.F_BatchNumber.Substring(0, 6);
                //        try
                //        {
                //            var pronos = DateTime.ParseExact(prono, "yyMMdd", null).ToString("yyyy-MM-dd");
                //            var protime = Convert.ToDateTime(pronos);
                //            if (DateTime.Parse(pronos) > DateTime.Now)
                //            {
                //                return Error("生产批次号错误，生产日期不能大于当前时间！");
                //            }
                //        }
                //        catch
                //        {
                //            return Error("生产批次号错误，日期格式错误！");
                //        }
                //    }
                //}
                if (string.IsNullOrEmpty(input.F_CusName))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_CusPhone))
                    return Error("请输入客户电话！");
                if (input.F_Type == 2 || input.F_Type == 5)
                {
                    if (string.IsNullOrEmpty(input.F_SalesBase))
                        return Error("请输入基地！");
                    if (string.IsNullOrEmpty(input.F_QuestionType))
                        return Error("请选择问题类别！");
                }

                if (!string.IsNullOrEmpty(input.F_CustomerID) && !valcode(input.F_CustomerID.ToString(), 10))
                    return Error("客户编号为10为纯数字！");

                if (!string.IsNullOrEmpty(input.F_MaterialID) && !valcode(input.F_MaterialID.ToString(), 11))
                    return Error("物料编码为11为纯数字！");
                if (!string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var Customer = cusbll.GetModel(input.F_CustomerID.Trim());
                    if (Customer == null)
                        return Error("无此客户编码！");
                }
                if (!string.IsNullOrWhiteSpace(input.F_MaterialID))
                {
                    var Customer = mmBLL.GetModel(input.F_MaterialID.Trim());
                    if (Customer == null)
                        return Error("无此物料编码！");
                }
                if (input.F_Type == 3)
                {
                    if (string.IsNullOrEmpty(input.F_Files))
                        return Error("请上传抽检单");
                    if (string.IsNullOrEmpty(input.F_CJ_Time.ToString()))
                        return Error("请选择抽检时间");
                    if (string.IsNullOrEmpty(input.F_MailingNumber))
                        return Error("如非邮寄请填自送(快递单号写送样人手机号)");
                    if (string.IsNullOrEmpty(input.F_ExpressName))
                        return Error("如非邮寄请填自送");
                }
                if (!string.IsNullOrEmpty(input.F_SalesPhone))
                {
                    if (!IsNumeric(input.F_SalesPhone))
                        return Error("请输入正确的业务员电话");
                }
                #endregion
                var model = new Model.T_Wo_WorkOrder();
                #region 保存客户基本信息
                model = inputtoobj(model, input, 2);
                model.F_limit = overtime;
                model.F_Flag = flag;
                if (flag == 1)
                {
                    if (clbm == 0 && clid == 0)
                    {
                        return Error("请选择外线接收部门");
                    }
                    else if (clid != 0)
                    {
                        Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(clid);
                        if (clus != null)
                        {
                            if (clus.F_WorkNumber == "7000")
                                return Error("不能转派到市场管理员");
                            else if (clus.F_RoleId == 1 || clus.F_RoleId == 4)
                                return Error("不能转派到话务人员");
                            else if (clus.F_RoleId == 58)
                                return Error("不能转派到业务员");
                            else if (clus.F_RoleId == 60)
                                return Error("不能转派到分公司经理");
                            else if (clus.F_RoleId == 62)
                                return Error("不能转派到大区经理");

                        }
                    }
                }
                else if (flag == 2)
                {
                    if (clbm2 == 0 && clid2 == 0)
                    {
                        return Error("请选择内线线接收部门");
                    }
                    else if (clid2 != 0)
                    {
                        Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(clid2);
                        if (clus != null)
                        {
                            if (clus.F_WorkNumber == "7000")
                                return Error("不能转派到市场管理员");
                            else if (clus.F_RoleId == 1 || clus.F_RoleId == 4)
                                return Error("不能转派到话务人员");
                            else if (clus.F_RoleId == 58)
                                return Error("不能转派到业务员");
                            else if (clus.F_RoleId == 60)
                                return Error("不能转派到分公司经理");
                            else if (clus.F_RoleId == 62)
                                return Error("不能转派到大区经理");

                        }
                    }
                }
                else if (flag == 3)
                {
                    if (clbm == 0 && clid == 0)
                    {
                        return Error("请选择外线接收部门");
                    }
                    else if (clid != 0)
                    {
                        Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(clid);
                        if (clus != null)
                        {
                            if (clus.F_WorkNumber == "7000")
                                return Error("不能转派到市场管理员");
                            else if (clus.F_RoleId == 1 || clus.F_RoleId == 4)
                                return Error("不能转派到话务人员");
                            else if (clus.F_RoleId == 58)
                                return Error("不能转派到业务员");
                            else if (clus.F_RoleId == 60)
                                return Error("不能转派到分公司经理");
                            else if (clus.F_RoleId == 62)
                                return Error("不能转派到大区经理");

                        }
                    }
                    if (clbm2 == 0 && clid2 == 0)
                    {
                        return Error("请选择内线线接收部门");
                    }
                    else if (clid2 != 0)
                    {
                        Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(clid2);
                        if (clus != null)
                        {
                            if (clus.F_WorkNumber == "7000")
                                return Error("不能转派到市场管理员");
                            else if (clus.F_RoleId == 1 || clus.F_RoleId == 4)
                                return Error("不能转派到话务人员");
                            else if (clus.F_RoleId == 58)
                                return Error("不能转派到业务员");
                            else if (clus.F_RoleId == 60)
                                return Error("不能转派到分公司经理");
                            else if (clus.F_RoleId == 62)
                                return Error("不能转派到大区经理");

                        }
                    }
                }
                #endregion
                long n = workOrder.Add(model);
                if (n > 0)
                {

                    Model.T_Wo_WorkOrder modlelist = new BLL.T_Wo_WorkOrder().GetModel(n);
                    string deptname = "";
                    var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    //var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    AddLog(modlelist.F_ID, 0, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "添加工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, "", 0, ua, 0, 0);
                    WorkOrderNewInput inputs = new WorkOrderNewInput();


                    if (deptmodel != null)
                    {
                        if (modlelist != null)
                        {
                            //if (modlelist.F_Type == "2")
                            //{
                            //    if (deptmodel.F_DeptId == 37)
                            //    {
                            //        inputs.F_SC_PreliminaryOpinion = deptment.PreliminaryOpinion;//市场管理科-初审意见:退货、换货、补偿、自行处理
                            //    }
                            //    else if (deptmodel.F_DeptId == 12)
                            //    {
                            //        inputs.F_IsVisit = isvisit.ToString();
                            //        inputs.F_ZL_QualityEventLevel = deptment.QualityEventLevel;//质量管理科-质量事件等级（未遂、一般、较大、重大）
                            //        inputs.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                            //        inputs.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 质量管理科-责任单位（需列出，可选多个）
                            //        inputs.F_ZL_ApprovalOpinions = deptment.ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                            //        inputs.F_ZL_ApprovalDisagree = deptment.ApprovalDisagree;// 质量管理科-审批不同意意见
                            //        inputs.F_ZL_CompensationMethod = deptment.CompensationMethod;// 质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                            //        inputs.F_ZL_CompensationMoney = deptment.CompensationMoney;// 质量管理科-补偿钱款
                            //        inputs.F_ZL_CResponsibleUnits = deptment.CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                            //        inputs.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                            //        inputs.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;//  质量管理科-改进要求
                            //        inputs.F_ZL_CApprovalNo = deptment.CApprovalNo;// 质量管理科-对应审批工作流单号

                            //    }
                            //}
                            //if (deptmodel.F_DeptId == 12 || deptmodel.F_DeptId == 36)
                            //{
                            //    modlelist.F_WorkmanShip = deptment.WorkmanShip;//质量管理科-工艺
                            //    modlelist.F_Manufacturers = deptment.Manufacturers;//质量管理科-原料及厂家
                            //    modlelist.F_ProductionNum = deptment.ProductionNum;//质量管理科-该批次生产数量
                            //}
                            if (model.F_Type == "2" || model.F_Type=="5")
                            {
                                if (deptmodel.F_DeptId == 37)
                                {
                                    // input. F_SC_QualityMonth = QualityMonth;//市场管理科-超出质保期限
                                    input.F_SC_PreliminaryOpinion = deptment.PreliminaryOpinion;//市场管理科-初审意见:退货、换货、补偿、自行处理
                                }
                                else if (deptmodel.F_DeptId == 12 || deptmodel.F_DeptId == 36)
                                {
                                    inputs.F_IsVisit = isvisit.ToString();
                                    inputs.F_ZL_QualityEventLevel = deptment.QualityEventLevel;//质量管理科-质量事件等级（未遂、一般、较大、重大）
                                    inputs.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                                    inputs.F_ZL_ApprovalOpinions = deptment.ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                                    inputs.F_ZL_ApprovalDisagree = deptment.ApprovalDisagree;// 质量管理科-审批不同意意见
                                    inputs.F_ZL_CompensationMethod = deptment.CompensationMethod;// 质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                                    inputs.F_ZL_CompensationMoney = deptment.CompensationMoney;// 质量管理科-补偿钱款
                                    inputs.F_ZL_CResponsibleUnits = deptment.CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                                    inputs.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                                    //inputs.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;//  质量管理科-改进要求
                                    inputs.F_ZL_CApprovalNo = deptment.CApprovalNo;// 质量管理科-对应审批工作流单号
                                    //if (string.IsNullOrEmpty(deptment.EventReason))
                                    //    return Error("请填写事件原因！");
                                    //if (string.IsNullOrEmpty(deptment.ResponsibleUnit))
                                    //    return Error("请填写责任单位！");
                                    //inputs.F_EventReason = deptment.EventReason;// 质量管理科-事件原因
                                    inputs.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 质量管理科-责任单位（需列出，可选多个）

                                }
                                else if (deptmodel.F_DeptName == "成品库" && model.F_SC_PreliminaryOpinion == "退换货") //退换货成品库录入物料信息
                                {
                                    if (string.IsNullOrEmpty(jsonstr))
                                    {
                                        return Error("请输入物料信息！");
                                    }
                                    else
                                    {
                                        JavaScriptSerializer Serializer = new JavaScriptSerializer();   //实例化⼀个能够序列化数据的类
                                        List<Material> list = Serializer.Deserialize<List<Material>>(jsonstr);
                                        List<T_Wo_MaterialItems> itemlist = new List<T_Wo_MaterialItems>();

                                        if (list != null && list.Count > 0)
                                        {
                                            foreach (var item in list)
                                            {
                                                T_Wo_MaterialItems itemodel = new T_Wo_MaterialItems();
                                                if (!string.IsNullOrEmpty(item.fid))
                                                {
                                                    itemodel.F_Id = Convert.ToInt32(item.fid);
                                                }
                                                itemodel.F_MaterialCode = item.materialcode;
                                                itemodel.F_MaterialName = item.materialname;
                                                itemodel.F_Formula = item.formula;
                                                itemodel.F_ReturnQuantity = item.returnum;
                                                itemodel.F_WoID = model.F_ID;//工单id
                                                itemodel.F_CreateOn = DateTime.Now;
                                                itemodel.F_Remark = item.specs;//规格
                                                itemlist.Add(itemodel);
                                            }
                                            modlelist.MaterialItems = itemlist;
                                        }

                                    }

                                }
                                else if (deptmodel.F_DeptId == 248 && model.F_SC_PreliminaryOpinion == "退换货")
                                {
                                    inputs.F_CarNumber = deptment.CarNumber;//返厂车牌号
                                    inputs.F_LoadingFee = deptment.LoadingFee;//装车费
                                    inputs.F_UnLoadingFee = deptment.UnLoadingFee;//卸车费
                                    inputs.F_MaterialFee = deptment.MaterialFee;//返料费
                                    input.F_DrivePhone = deptment.DrivePhone;//电话号码
                                }
                                //else if (deptmodel.F_DeptName == "销售内勤" && (model.F_SC_PreliminaryOpinion == "退货" || model.F_SC_PreliminaryOpinion == "换货"))//部门id=193
                                //{
                                //    modlelist.F_SC_CJ_ReturnAccount = deptment.ReturnAccount2;//销售内勤-确认返账金额                               
                                //}
                            }
                            else if (modlelist.F_Type == "3")
                            {
                                if (deptmodel.F_DeptId == 37)
                                {
                                    inputs.F_SC_CJ_SpotResult = deptment.SpotResult;//市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
                                    inputs.F_SC_CJ_SelfResult = deptment.SelfResult;//市场管理科-抽检-自检结果
                                    inputs.F_SC_CJ_ApprovalNo = deptment.ApprovalNo;//市场管理科-抽检-对应审批工作流单号
                                    inputs.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//市场管理科-抽检-确认返账金额
                                }
                                else if (deptmodel.F_DeptId == 12)
                                {
                                    inputs.F_IsVisit = isvisit.ToString();
                                    inputs.F_ZL_CJ_IsRecord = deptment.IsRecord;//质量管理科-抽检-未备案、已备案
                                    inputs.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                                }
                            }
                            //if (deptmodel.F_DeptId == 25)
                            //{

                            //    inputs.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//销售内勤-确认返账金额
                            //}
                            if (deptmodel.F_DeptName == "销售内勤")//部门id=193
                            {
                                inputs.F_SC_CJ_ReturnAccount = deptment.ReturnAccount2;//销售内勤-确认返账金额                               
                            }
                            else if (deptmodel.F_DeptId == 36)
                            {
                                inputs.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                            }
                        }
                        else
                            return Error("工单不存在！");
                    }
                    else
                    {
                        return Error("请选择接收部门");
                    }

                    if (modlelist != null)
                    {
                        if (flag == 3)
                        {
                            var res = AssignWO(ua, modlelist, inputs, cont, F_Files, clbm, clid, overtime, sms);
                            var res1 = AssignWO(ua, modlelist, inputs, cont, F_Files, clbm2, clid2, overtime, sms, 0, 0, 0, "", 0, 2);
                        }
                        else if (flag == 2)
                        {
                            var res1 = AssignWO(ua, modlelist, inputs, cont, F_Files, clbm2, clid2, overtime, sms, 0, 0, 0, "", 0, 2);
                            DealWO(ua, modlelist, input, cont, "", 1, "", 1, "");
                        }
                        else
                        {
                            var res = AssignWO(ua, modlelist, inputs, cont, F_Files, clbm, clid, overtime, sms);
                            DealWO(ua, modlelist, input, cont, "", 1, "", 2, "");

                        }
                        return Success("转派成功");
                    }
                    else
                        return Error("工单不存在！");

                }
                else
                    return Error("添加失败！");
            }
            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 注解
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="cont"></param>
        /// <returns></returns>
        public ActionResult Annotation(int orderid, string cont, int flag = 0)
        {
            //注解给超级管理员开通编辑删除修改权限 20220221
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string Annotationstr = "";
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息 
                    if (model != null)
                    {
                        #region 添加注解表
                        Model.T_Wo_AnnotationTab annotab = new T_Wo_AnnotationTab();
                        annotab.F_Contents = cont;
                        annotab.F_AnnotationPerson = ua.F_UserCode;
                        annotab.F_CreateTime =Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        annotab.F_Wocode = model.F_WorkOrderCode;
                        new BLL.T_Wo_AnnotationTab().Add(annotab);
                        #endregion
                        Annotationstr = cont + "-" + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");                   
                     if (flag == 1)
                        {
                            if (ro.F_RoleCode == "XTGLY")
                            {
                                model.F_Annotation = Annotationstr;
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(model.F_Annotation))
                                {
                                    model.F_Annotation = Annotationstr; 
                                }
                                else
                                {
                                    model.F_Annotation = model.F_Annotation + "\n" + Annotationstr;
                                }
                            }

                        }
                        else
                        {
                            if (string.IsNullOrEmpty(model.F_Annotation))
                            {
                                model.F_Annotation = Annotationstr;
                            }
                            else
                            {
                                model.F_Annotation = model.F_Annotation + "\n" + Annotationstr;
                            }
                        }
                        var res = workOrder.Update(model);
                        if (res)
                        #region 增加注解通知市场部功能  20220216
                        {
                            string touser = "";
                            string strwhere = "";
                            string contens = "";
                            strwhere = $" F_DeptId in (select top 1 F_NextDept  from T_Wo_WorkOrderItem_New where F_WoID={model.F_ID} and F_NextDept in(37,57,74,88,268,295,339) order by F_CreateTime desc)";
                            var deptmodel = departmentBLL.GetModelList(strwhere).FirstOrDefault();
                            if (deptmodel != null)
                            {
                                var userlist = sysUserAccountBll.GetModelList("F_DeptId=" + deptmodel.F_DeptId);
                                if (userlist.Count > 0)
                                {
                                    if (flag == 1)
                                        contens = $" 修改注解,工单编号 <a href='./WorkOrder/commonHtml/orderDetails.html?oid={model.F_ID}'>"+ model.F_WorkOrderCode +"</a>" ;

                                    //< span class="top_notices_con">系统维护管理员 修改注解, 工单编号 20220527152927398</span>
                                    else
                                        contens = $" 附加注解,工单编号 <a href='./WorkOrder/commonHtml/orderDetails.html?oid={model.F_ID}'>"+ model.F_WorkOrderCode + "</a>";
                                    foreach (var item in userlist)
                                    {
                                        touser = item.F_UserCode; ;
                                        Model.T_Msg_List msg = new Model.T_Msg_List();
                                        msg.Type = (int)Model.MSGType.Annotation;
                                        msg.ToUser = touser;
                                        msg.ToID = (int)model.F_ID;
                                        msg.Detail = $"<span class='top_notices_con'> "+ua.F_UserName + contens+ "</span>";
                                        msg.State = 0;
                                        msg.IsDel = 0;
                                        msg.CreateDate = DateTime.Now;
                                        msg.ReadDate = DateTime.Now;
                                        new BLL.T_Msg_List().Add(msg);
                                        //sendsysmsg(model, ua, touser, (int)model.F_ID, "增加注解");
                                    }
                                }
                            }
                            return Success("注解成功");
                        }
                        #endregion
                        else
                            return Error("注解失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }

        public ActionResult ReturnVisit(int orderid, string cont)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                //河南心连心化学工业集团股份有限公司-系统维护管理员(8000)指派工单给 李波(80324),张绍申(80325),杜爱国(80326)，说明：无
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息 
                    if (model != null)
                    {
                        if (model.F_State != 11 && model.F_State != 10)
                            return Error("无操作权限！");
                        if (model.F_State == 11 && model.F_VisitResult != "不满意")
                            return Error("非不满意工单不可退回");
                        var res = BackWO(ua, model, cont);
                        if (res)
                            return Success("退回成功");
                        else
                            return Error("退回失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 退回工单
        /// </summary>
        public bool BackWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont)
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            string creatuser = "";
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 10)
                    {
                        creatuser = it.F_CreateUser;
                    }
                }
            }
            var opt = "退回";
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单，退回说明：" + cont;
            //获取上一级处理人员
            int deptid = 0;
            var touser = new BLL.T_Sys_UserAccount().GetModel(creatuser);
            if (touser != null)
            {
                deptid = touser.F_DeptId;
            }
            string smscont = "";


            var itemid = AddLog((int)model.F_ID, 3, content, (int)EnumItemType.deal, 4, creatuser, deptid, nowUser, model.F_limit, sms);
            if (itemid > 0)
            {
                if (model.F_Type == "1")
                {
                    smscont = "咨询";
                }
                else if (model.F_Type == "2")
                {
                    smscont = "投诉";
                }
                else if (model.F_Type == "3")
                {
                    smscont = "抽检";
                }
                else if (model.F_Type == "5")
                {
                    smscont = "业务协办";
                }
                else
                {
                    smscont = "建议";
                }
                string[] mag = { smscont };
                string smsmsg = "您好，您有一条新的" + smscont + "工单，请及时接单处理！";
                if (touser != null)
                {
                    if (!string.IsNullOrEmpty(touser.F_Mobile))
                    {

                        SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, touser.F_Mobile.Trim());
                        bool n = new SMSController().AddSmS(touser.F_Mobile.Trim(), smsmsg, nowUser.F_UserId);
                    }
                }

                #region 处理工单
                model.F_State = 2;
                workOrder.Update(model);
                #endregion
                #region 推送消息
                #region 向上一级操作人员推送消息
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        /// <summary>
        /// 创建工单时完结
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult CreatOver(WorkOrderNewInput input, int sms, int overtime = 0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string usercode = CurrentUser.UserData.F_UserCode;
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);

                #region 添加验证判断
                if (!(input.F_Type > 0 && input.F_Type < 6))
                    return Error("工单类型错误！");
                //if (!string.IsNullOrEmpty(input.F_BatchNumber) && !vaBatchNumber(input.F_BatchNumber.Trim()))
                //    return Error("请输入正确的生产批次号！");
                //else
                //{
                //    if (!string.IsNullOrEmpty(input.F_BatchNumber))
                //    {
                //        var prono = input.F_BatchNumber.Substring(0, 6);
                //        try
                //        {
                //            var pronos = DateTime.ParseExact(prono, "yyMMdd", null).ToString("yyyy-MM-dd");
                //            var protime = Convert.ToDateTime(pronos);
                //            if (DateTime.Parse(pronos) > DateTime.Now)
                //            {
                //                return Error("生产批次号错误，生产日期不能大于当前时间！");
                //            }

                //        }
                //        catch
                //        {
                //            return Error("生产批次号错误，日期格式错误！");
                //        }
                //    }
                //}

                if (string.IsNullOrEmpty(input.F_CusName))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_CusPhone))
                    return Error("请输入客户电话！");
                if (input.F_Type == 2 || input.F_Type==5)
                {
                    if (string.IsNullOrEmpty(input.F_SalesBase))
                        return Error("请输入基地！");
                    if (string.IsNullOrEmpty(input.F_QuestionType))
                        return Error("请选择问题类别！");
                }

                #endregion
                if (!string.IsNullOrEmpty(input.F_CustomerID) && !valcode(input.F_CustomerID.ToString(), 10))
                    return Error("客户编号为10为纯数字！");

                if (!string.IsNullOrEmpty(input.F_MaterialID) && !valcode(input.F_MaterialID.ToString(), 11))
                    return Error("物料编码为11为纯数字！");
                if (!string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var Customer = cusbll.GetModel(input.F_CustomerID.Trim());
                    if (Customer == null)
                        return Error("无此客户编码！");
                }
                if (!string.IsNullOrWhiteSpace(input.F_MaterialID))
                {
                    var Customer = mmBLL.GetModel(input.F_MaterialID.Trim());
                    if (Customer == null)
                        return Error("无此物料编码！");
                }
                if (!string.IsNullOrEmpty(input.F_SalesPhone))
                {
                    if (!IsNumeric(input.F_SalesPhone))
                        return Error("请输入正确的业务员电话");
                }
                if (input.F_Type == 3)
                {
                    if (string.IsNullOrEmpty(input.F_Files))
                        return Error("请上传抽检单");
                    if (string.IsNullOrEmpty(input.F_CJ_Time.ToString()))
                        return Error("请选择抽检时间");
                    if (string.IsNullOrEmpty(input.F_MailingNumber))
                        return Error("如非邮寄请填自送(快递单号写送样人手机号)");
                    if (string.IsNullOrEmpty(input.F_ExpressName))
                        return Error("如非邮寄请填自送");

                }

                var model = new Model.T_Wo_WorkOrder();
                #region 保存客户基本信息
                model = inputtoobj(model, input, 2);
                model.F_limit = overtime;
                #endregion
                long n = workOrder.Add(model);
                if (n > 0)
                {
                    Model.T_Wo_WorkOrder modlelist = new BLL.T_Wo_WorkOrder().GetModel(n);
                    WorkOrderNewInput inputs = new WorkOrderNewInput();

                    modlelist.F_SC_ProductBase = input.F_SC_ProductBase;//市场管理科-生产基地（新乡、新疆、九江、东北、贴牌、无法确定）
                    modlelist.F_SC_PreliminaryOpinion = input.F_SC_PreliminaryOpinion;//市场管理科-初审意见:退货、换货、补偿、自行处理
                    modlelist.F_SC_CJ_SpotResult = input.F_SC_CJ_SpotResult;//市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
                    modlelist.F_SC_CJ_SelfResult = input.F_SC_CJ_SelfResult;// 市场管理科-抽检-自检结果
                    modlelist.F_SC_CJ_ApprovalNo = input.F_SC_CJ_ApprovalNo;//市场管理科-抽检-对应审批工作流单号
                    modlelist.F_SC_CJ_ReturnAccount = input.F_SC_CJ_ReturnAccount;//市场管理科-抽检-确认返账金额（元）
                    modlelist.F_ZL_QualityEventLevel = input.F_ZL_QualityEventLevel;//质量管理科-质量事件等级（未遂、一般、较大、重大）
                    modlelist.F_ZL_ClaimAmount = input.F_ZL_ClaimAmount;//质量管理科-索赔金额（单位元，对应责任单位）
                    modlelist.F_ZL_ResponsibleUnit = input.F_ZL_ResponsibleUnit;// 质量管理科-责任单位（需列出，可选多个）
                    modlelist.F_ZL_ApprovalOpinions = input.F_ZL_ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                    modlelist.F_ZL_ApprovalDisagree = input.F_ZL_ApprovalDisagree;//质量管理科-审批不同意意见
                    modlelist.F_ZL_CompensationMethod = input.F_ZL_CompensationMethod;//质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                    modlelist.F_ZL_CompensationMoney = input.F_ZL_CompensationMoney;// 质量管理科-补偿钱款
                    modlelist.F_ZL_CResponsibleUnits = input.F_ZL_CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                    modlelist.F_ZL_Fquantity = input.F_ZL_Fquantity;//质量管理科-确认实收数量（吨）
                    modlelist.F_ZL_ImprovementRequirements = input.F_ZL_ImprovementRequirements;// 质量管理科-改进要求
                    modlelist.F_ZL_CApprovalNo = input.F_ZL_CApprovalNo;// 质量管理科-对应审批工作流单号
                    modlelist.F_ZL_CJ_IsRecord = input.F_ZL_CJ_IsRecord;// 质量管理科-抽检-未备案、已备案
                    modlelist.F_DealBy = ua.F_UserCode;// 处理人
                    modlelist.F_DealTime = DateTime.Now;// 处理时间
                    modlelist.F_DealContent = input.F_DealContent;//完结内容
                    modlelist.F_DealType = "当即办理";//处理方式:当即办理、电话转接、网络转办
                    model.F_IsVisit = 0;
                    bool f = workOrder.Update(modlelist);
                    if (!f)
                    {
                        return Error("完结失败！");
                    }
                    if (modlelist != null)
                    {
                        string deptname = "";
                        var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            deptname = deptmodel.F_DeptName + "-";
                        }
                        AddLog(modlelist.F_ID, modlelist.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "添加工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, "", 0, ua, overtime, sms);
                        var res = Overorder(ua, modlelist, 1);
                        if (res)
                            return Success("完结成功");
                    }
                }
            }
            else
            {
                return Error("无操作权限！");
            }
            return Error("完结失败！");
        }
        /// <summary>
        /// 指派/转派工单
        ///  <param name="orderid">工单id</param>
        /// <param name="cont">指派说明</param>
        ///  <param name="clbm">指派部门</param>
        ///  <param name="clid">指派人</param>
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AssignWorkOrder(long orderid, string cont, WorkOrdeDeptment deptment, string F_Files, int isvisit = 1,
            int overtime = 0, int sms = 0, int clbm = 0, int clid = 0, int isApprovalp = 0, int hclbm = 0, int hclid = 0, int clbm2 = 0, int clid2 = 0,string jsonstr="",int flag=1)
        {
            int userId = CurrentUser.UserData.F_UserId;
            string usercode = CurrentUser.UserData.F_UserCode;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua == null)
                {
                    return Error("无操作权限！");
                }
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                if (model == null)
                {
                    return Error("工单不存在！");
                }
                if (model.F_State == 1  && model.F_CreateBy == ua.F_UserCode)
                {
                    return Error("工单已转派请勿重复操作！");
                }

                if (model.F_State != 0)
                {
                    string strsql = " and F_Type in(3,"+ua.F_Flag+")";
                    var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + strsql+" and F_IsUsed=0 order by   F_ID desc ").FirstOrDefault();
                    if (modellist != null)
                    {
                        if (modellist.F_NextUser != ua.F_UserCode)
                            return Error("非接单人不可操作工单");
                    }
                }

                WorkOrderNewInput input = new WorkOrderNewInput();
                if (clid != 0)
                {
                    Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(clid);

                    if (clus != null)
                    {
                        if (clus.F_WorkNumber == "7000")
                            return Error("不能转派到市场管理员");
                        else if (clus.F_RoleId == 1 || clus.F_RoleId == 4)
                            return Error("不能转派到话务人员");
                        else if (clus.F_RoleId == 58)
                            return Error("不能转派到业务员");
                        else if (clus.F_RoleId == 60)
                            return Error("不能转派到分公司经理");
                        else if (clus.F_RoleId == 62)
                            return Error("不能转派到大区经理");
                    }
                }
                if (clid2 != 0)
                {
                    Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(clid2);

                    if (clus != null)
                    {
                        if (clus.F_WorkNumber == "7000")
                            return Error("不能转派到市场管理员");
                        else if (clus.F_RoleId == 1 || clus.F_RoleId == 4)
                            return Error("不能转派到话务人员");
                        else if (clus.F_RoleId == 58)
                            return Error("不能转派到业务员");
                        else if (clus.F_RoleId == 60)
                            return Error("不能转派到分公司经理");
                        else if (clus.F_RoleId == 62)
                            return Error("不能转派到大区经理");
                    }
                }

                if (hclid == 0 && hclbm == 0 && isApprovalp != 0)
                {
                    return Error("请选择接收部门");
                }
                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                {
                    model.F_Flag = flag;
                    if (flag == 3)
                    {
                        if ((clbm == 0 && clid == 0) || (clbm2 == 0 && clid2 == 0))
                        {
                            return Error("请选择接收部门");

                        }                     
                        var res = AssignWO(ua, model, input, cont, F_Files, clbm, clid, overtime, sms, isApprovalp, hclbm, hclid);
                        var res1 = AssignWO(ua, model, input, cont, F_Files, clbm2, clid2, overtime, sms, isApprovalp, hclbm, hclid, "", 0, 2);

                    }
                    else if (flag == 2)
                    {
                        if (clbm2 == 0 && clid2 == 0)
                        {
                            return Error("请选择接收部门");
                        }
                        var res1 = AssignWO(ua, model, input, cont, F_Files, clbm2, clid2, overtime, sms, isApprovalp, hclbm, hclid, "", 0, 2);
                        DealWO(ua, model, input, cont, "", 1, "", 1, "");
                    }
                    else
                    {
                        if (clbm == 0 && clid == 0)
                        {
                            return Error("请选择接收部门");
                        }
                        var res = AssignWO(ua, model, input, cont, F_Files, clbm, clid, overtime, sms, isApprovalp, hclbm, hclid);
                        DealWO(ua, model, input, cont, "", 1, "", 2, "");
                    }
                    return Success("转派成功");
                }
                else
                {
                    if (clbm == 0 && clid == 0)
                    {
                        return Error("请选择接收部门");
                    }
                    else
                    {
                        var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            if (model != null)
                            {
                                if (deptmodel.F_DeptId == 12 || deptmodel.F_DeptId == 36)
                                {
                                    input.F_WorkmanShip = deptment.WorkmanShip;//质量管理科-工艺
                                    input.F_Manufacturers = deptment.Manufacturers;//质量管理科-原料及厂家
                                    input.F_ProductionNum = deptment.ProductionNum;//质量管理科-该批次生产数量
                                }
                                if (model.F_Type == "2" || model.F_Type=="5")
                                {
                                    if (deptmodel.F_DeptId == 37)
                                    {
                                        // input. F_SC_QualityMonth = QualityMonth;//市场管理科-超出质保期限
                                        input.F_SC_PreliminaryOpinion = deptment.PreliminaryOpinion;//市场管理科-初审意见:退货、换货、补偿、自行处理
                                    }
                                    else if (deptmodel.F_DeptId == 12 || deptmodel.F_DeptId == 36)
                                    {
                                        input.F_IsVisit = isvisit.ToString();
                                        input.F_ZL_QualityEventLevel = deptment.QualityEventLevel;//质量管理科-质量事件等级（未遂、一般、较大、重大）
                                        input.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                                        input.F_ZL_ApprovalOpinions = deptment.ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                                        input.F_ZL_ApprovalDisagree = deptment.ApprovalDisagree;// 质量管理科-审批不同意意见
                                        input.F_ZL_CompensationMethod = deptment.CompensationMethod;// 质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                                        input.F_ZL_CompensationMoney = deptment.CompensationMoney;// 质量管理科-补偿钱款
                                        input.F_ZL_CResponsibleUnits = deptment.CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                                        input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                                        //input.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;//  质量管理科-改进要求
                                        input.F_ZL_CApprovalNo = deptment.CApprovalNo;// 质量管理科-对应审批工作流单号
                                        //if (string.IsNullOrEmpty(deptment.EventReason))
                                        //    return Error("请填写事件原因！");
                                        //if (string.IsNullOrEmpty(deptment.ResponsibleUnit))
                                        //    return Error("请填写责任单位！");
                                        //input.F_EventReason = deptment.EventReason;// 质量管理科-事件原因
                                        //input.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 质量管理科-责任单位（需列出，可选多个）

                                    }
                                   else if (deptmodel.F_DeptName == "成品库" && model.F_SC_PreliminaryOpinion == "退换货") //退换货成品库录入物料信息
                                    {
                                        //if (string.IsNullOrEmpty(jsonstr))
                                        //{
                                        //    return Error("请输入物料信息！");
                                        //}
                                        if (!string.IsNullOrEmpty(jsonstr))
                                        {
                                            JavaScriptSerializer Serializer = new JavaScriptSerializer();   //实例化⼀个能够序列化数据的类
                                            List<Material> list = Serializer.Deserialize<List<Material>>(jsonstr);
                                            List<T_Wo_MaterialItems> itemlist = new List<T_Wo_MaterialItems>();

                                            if (list != null && list.Count > 0)
                                            {
                                                foreach (var item in list)
                                                {
                                                    T_Wo_MaterialItems itemodel = new T_Wo_MaterialItems();
                                                    itemodel.F_MaterialCode = item.materialcode;
                                                    itemodel.F_MaterialName = item.materialname;
                                                    itemodel.F_Formula = item.formula;
                                                    itemodel.F_ReturnQuantity = item.returnum??0;
                                                    itemodel.F_WoID = model.F_ID;//工单id
                                                    itemodel.F_CreateOn = DateTime.Now;
                                                    itemodel.F_Remark = item.specs;//规格
                                                    itemlist.Add(itemodel);
                                                }
                                                model.MaterialItems = itemlist;
                                            }

                                        }

                                    }
                                    else if (deptmodel.F_DeptId == 248 && model.F_SC_PreliminaryOpinion == "退换货" )
                                    {
                                        input.F_CarNumber = deptment.CarNumber;//返厂车牌号
                                        input.F_LoadingFee= deptment.LoadingFee;//装车费
                                        input.F_UnLoadingFee = deptment.UnLoadingFee;//卸车费
                                        input.F_MaterialFee = deptment.MaterialFee;//返料费
                                        input.F_DrivePhone = deptment.DrivePhone;//电话号码
                                        if (!string.IsNullOrEmpty(jsonstr))
                                        {
                                            JavaScriptSerializer Serializer = new JavaScriptSerializer();   //实例化⼀个能够序列化数据的类
                                            List<Material> list = Serializer.Deserialize<List<Material>>(jsonstr);
                                            List<T_Wo_MaterialItems> itemlist = new List<T_Wo_MaterialItems>();

                                            if (list != null && list.Count > 0)
                                            {
                                                foreach (var item in list)
                                                {
                                                    T_Wo_MaterialItems itemodel = new T_Wo_MaterialItems();
                                                    if (!string.IsNullOrEmpty(item.fid))
                                                    {
                                                        itemodel.F_Id = Convert.ToInt32(item.fid);
                                                    }
                                                    itemodel.F_MaterialCode = item.materialcode;
                                                    itemodel.F_MaterialName = item.materialname;
                                                    itemodel.F_Formula = item.formula;
                                                    itemodel.F_ReturnQuantity = item.returnum ?? 0;
                                                    itemodel.F_WoID = model.F_ID;//工单id
                                                    itemodel.F_CreateOn = DateTime.Now;
                                                    itemodel.F_Remark = item.specs;//规格
                                                    itemlist.Add(itemodel);
                                                }
                                                model.MaterialItems = itemlist;
                                            }

                                        }
                                    }
                                    //else if (deptmodel.F_DeptName == "销售内勤" && (model.F_SC_PreliminaryOpinion == "退货" || model.F_SC_PreliminaryOpinion == "换货"))//部门id=193
                                    //{
                                    //    model.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//销售内勤-确认返账金额                               
                                    //}
                                }
                                else if (model.F_Type == "3")
                                {
                                    if (deptmodel.F_DeptId == 37)
                                    {

                                        input.F_SC_CJ_SpotResult = deptment.SpotResult;//市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
                                        input.F_SC_CJ_SelfResult = deptment.SelfResult;//市场管理科-抽检-自检结果
                                        input.F_SC_CJ_ApprovalNo = deptment.ApprovalNo;//市场管理科-抽检-对应审批工作流单号
                                        input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//市场管理科-抽检-确认返账金额
                                    }
                                    else if (deptmodel.F_DeptId == 12 || deptmodel.F_DeptId == 36)
                                    {
                                        input.F_IsVisit = isvisit.ToString();
                                        input.F_ZL_CJ_IsRecord = deptment.IsRecord;//质量管理科-抽检-未备案、已备案
                                        input.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                                    }
                                }
                                //if (deptmodel.F_DeptId == 25)
                                //{

                                //    input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//销售内勤-确认返账金额
                                //}
                                if (deptmodel.F_DeptName == "销售内勤")//部门id=193
                                {
                                    input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount2;//销售内勤-确认返账金额                               
                                }
                                if (deptmodel.F_DeptId == 260)//销售财务
                                {
                                    input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount3;//销售内勤-确认返账金额                               
                                }
                                if (deptmodel.F_DeptId == 36)
                                {
                                    input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                                }
                            }
                            else
                                return Error("工单不存在！");
                        }
                        else
                        {
                            return Error("请选择接收部门");
                        }
                    }

                    var res = AssignWO(ua, model, input, cont, F_Files, clbm, clid, overtime, sms, isApprovalp, hclbm, hclid, "", 0, ua.F_Flag);
                    if (res)
                    {
                        return Success("转派成功");
                    }
                    else
                        return Error("转派失败！");
                }

            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 接单 - 确认工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SureWorkOrder(long orderid)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);

                    if (model != null)
                    {
                        string strsql = "";
                        if (ua.F_Flag == 1)
                        {
                            strsql = " and F_Type in(1,3)";
                        }
                        else if (ua.F_Flag == 2)
                        {
                            strsql = " and F_Type in(2,3)";
                        }

                        var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + "and F_IsUsed=0 " + strsql + "  order by  F_ID desc ").FirstOrDefault();
                        if (modellist != null)
                        {
                            if (!string.IsNullOrEmpty(modellist.F_NextUser))
                            {
                                string[] sprt = modellist.F_NextUser.Split(',');
                                if (sprt.Length == 1)
                                {
                                    if (modellist.F_NextUser != ua.F_UserCode)
                                        return Error("非接单人不可操作工单");
                                }
                            }

                        }
                        if (ua.F_Flag == 1)
                        {
                            if (model.F_State == 2)
                                return Error("工单已接单无需重新接单");
                        }
                        else if (ua.F_Flag == 2)
                        {
                            if (model.F_State2 == 2)
                                return Error("工单已接单无需重新接单");
                        }
                        var res = SureWO(ua, model, ua.F_Flag);
                        if (res)
                            return Success("接单成功");
                        else
                            return Error("接单失败");
                    }
                    else
                        return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        public ActionResult GetDeptment()
        {
            int userId = CurrentUser.UserData.F_UserId;
            Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
            var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
            if (deptmodel != null)
                return Success("获取部门信息成功", new
                {
                    deptid = deptmodel.F_DeptId,
                    depname = deptmodel.F_DeptName,
                    sort = deptmodel.F_Sort,
                    parentid = deptmodel.F_ParentId,
                    parentname = deptmodel.F_ParentName,
                    remark = deptmodel.F_Remark,
                    layerType = deptmodel.F_Layer,
                    //部门类型0不区分1大区2分公司
                    //    headerid = dModel.F_Header,    //部门权限范围：9全部，1区域，2项目，3期
                    //   TypeId = dModel.F_Type,    //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                });
            return Error("获取部门信息失败");
        }
        /// <summary>
        /// 查询部门
        /// </summary>
        /// <returns></returns>
        public ActionResult GetModelDeptName(string F_DeptName)
        {
            int userId = CurrentUser.UserData.F_UserId;
            Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
            var deptmodel = departmentBLL.GetModel(F_DeptName);
            if (deptmodel != null)
                return Success("获取部门信息成功", new
                {
                    deptid = deptmodel.F_DeptId,
                    depname = deptmodel.F_DeptName,
                    sort = deptmodel.F_Sort,
                    parentid = deptmodel.F_ParentId,
                    parentname = deptmodel.F_ParentName,
                    remark = deptmodel.F_Remark,
                    layerType = deptmodel.F_Layer,
                    //部门类型0不区分1大区2分公司
                    //    headerid = dModel.F_Header,    //部门权限范围：9全部，1区域，2项目，3期
                    //   TypeId = dModel.F_Type,    //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                });
            return Success("获取部门信息失败", null);
        }
        /// <summary>
        /// 处理工单信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DealWorkOrder(long orderid, string cont, WorkOrdeDeptment deptment,
     string F_Files, string uncont = "",
          int isvisit = 1, int isover = 0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                string markdepts = "37,57,74,88,268,422,339";
                string qualdepts = "12,36,295,245"; //245:九江心连心化肥有限公司-质量督察处
                if (string.IsNullOrEmpty(cont))
                    return Error("请输入处理内容");           
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                WorkOrderNewInput input = new WorkOrderNewInput();
                if (ua != null)
                {
                    if (!markdepts.Contains(ua.F_DeptId.ToString()) && !qualdepts.Contains(ua.F_DeptId.ToString()))
                    return Error("权限不足");
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    if (deptmodel != null)
                    {
                        if (model != null)
                        {
                            string strsql = "";
                            if (ua.F_Flag == 1)
                            {
                                strsql = " and F_Type in(1,3)";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                strsql = " and F_Type in(2,3)";
                            }

                            var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + "and F_IsUsed=0 " + strsql + "  order by  F_ID desc ").FirstOrDefault();
                            if (modellist != null)
                            {
                                if (modellist.F_NextUser != ua.F_UserCode)
                                    return Error("非接单人不可操作工单");
                            }
                            if (markdepts.Contains(ua.F_DeptId.ToString()) || qualdepts.Contains(ua.F_DeptId.ToString()))
                            {
                                input.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 责任单位
                                //input.F_EventReason = deptment.EventReason;// 事件原因
                                input.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;// 改进要求

                            }
                            #region nouser
                            //if (model.F_Type == "2" || model.F_Type=="5")
                            //{
                            //    if (deptmodel.F_DeptId == 37)
                            //    {
                            //        input.F_SC_ProductBase = deptment.ProductBase;//

                            //    }
                            //    else if (deptmodel.F_DeptId == 12)
                            //    {
                            //        input.F_IsVisit = isvisit.ToString();
                            //        input.F_ZL_QualityEventLevel = deptment.QualityEventLevel;//质量管理科-质量事件等级（未遂、一般、较大、重大）
                            //        input.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                            //        input.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 质量管理科-责任单位（需列出，可选多个）
                            //        input.F_ZL_ApprovalOpinions = deptment.ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                            //        input.F_ZL_ApprovalDisagree = deptment.ApprovalDisagree;// 质量管理科-审批不同意意见
                            //        input.F_ZL_CompensationMethod = deptment.CompensationMethod;// 质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                            //        input.F_ZL_CompensationMoney = deptment.CompensationMoney;// 质量管理科-补偿钱款
                            //        input.F_ZL_CResponsibleUnits = deptment.CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                            //        input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                            //        input.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;//  质量管理科-改进要求
                            //        input.F_ZL_CApprovalNo = deptment.CApprovalNo;// 质量管理科-对应审批工作流单号
                            //    }

                            //}
                            //else if (model.F_Type == "3")
                            //{
                            //    if (deptmodel.F_DeptId == 37)
                            //    {
                            //        input.F_SC_ProductBase = deptment.ProductBase;//
                            //    }
                            //    else if (deptmodel.F_DeptId == 12)
                            //    {
                            //        input.F_IsVisit = isvisit.ToString();
                            //        input.F_ZL_CJ_IsRecord = deptment.IsRecord;//质量管理科-抽检-未备案、已备案
                            //    }
                            //}
                            //if (deptmodel.F_DeptId == 25)
                            //{

                            //    input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//销售内勤-确认返账金额
                            //}
                            //else if (deptmodel.F_DeptId == 36)
                            //{
                            //    input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                            //}
                            #endregion
                        }
                        else
                            return Error("工单不存在！");
                    }
                    else
                    {
                        return Error("请选择接收部门");
                    }
                    if (model != null)
                    {
                        if (model.F_State == 10 && model.F_State2 == 10)
                            return Error("工单已处理请勿重复操作！");
                        else
                        {

                            var res = DealWO(ua, model, input, cont, F_Files, isover, uncont, ua.F_Flag, deptment.EventReason);

                            if (res)
                                return Success("处理成功");
                            else
                                return Error("处理失败！");
                        }

                    }
                    else
                        return Error("工单不存在！");
                }
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 高层审批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult HigApprovalOrder(long orderid, string cont)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        var itemlast = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.audit + " and  F_OptType=" + (int)EnumItemOpt.audit + "and F_NextUser= '" + ua.F_UserCode + "'" + "and F_IsUsed=2  and  F_WoID = " + orderid);
                        if (itemlast.Count > 0)
                        {
                            foreach (var it in itemlast)
                            {
                                it.F_IsUsed = 1;
                                itembll.Update(it);
                            }
                        }
                        model.F_Highopinions = cont;
                        string deptname = "";
                        var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            deptname = deptmodel.F_DeptName + "-";
                        }
                        AddLog(model.F_ID, model.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "高层已审批", (int)EnumItemType.audit, (int)EnumItemOpt.reaudit, "", 0, ua, 0, 0, "", 1);
                        bool n = workOrder.Update(model);
                        if (n)
                            return Success("审批成功");
                        else
                            return Error("审批失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 填写超时原因
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult Reasontimeout(long orderid, string cont)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        model.F_Reasontimeout = cont;
                        bool n = workOrder.Update(model);
                        if (n)
                            return Success("填写成功");
                        else
                            return Error("填写失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 退回工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult BackWorkOrder(long orderid, string cont, int type = 0)
        {//办理人员和监管可以退回工单
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                //河南心连心化学工业集团股份有限公司-系统维护管理员(8000)指派工单给 李波(80324),张绍申(80325),杜爱国(80326)，说明：无
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息 
                    if (model != null)
                    {
                        //if (model.F_State != (int)EnumWorkOrderState.assign)
                        //{
                        //    return Error("此工单状态已经过时，请刷新");
                        //}
                        string strsql = "";
                        if (ua.F_Flag == 1)
                        {
                            strsql = $" and F_Type in(1,3)";
                        }
                        else if (ua.F_Flag == 2)
                        {
                            strsql = $" and F_Type in(2,3)";
                        }

                        var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList($"F_WoID={model.F_ID} and F_IsUsed=0 {strsql} order by   F_ID desc ").FirstOrDefault();

                        if (modellist != null)
                        {
                            string[] sprt = modellist.F_NextUser.Split(',');
                            if (sprt.Length == 1)
                            {
                                if (modellist.F_NextUser != ua.F_UserCode)
                                    return Error("非接单人不可操作工单");
                            }
                        }

                        var res = BackWO(ua, model, cont, type,ua.F_Flag);
                        if (res)
                            return Success("退回成功");
                        else
                            return Error("退回失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 撤回工单
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="cont"></param>
        /// <returns></returns>
         //[Authority]
        public ActionResult RevokeWo(long orderid, string cont)
        {
            int userId = CurrentUser.UserData.F_UserId; ;
            int flag = 0;
            if (userId != 0)
            {
                //增加撤回功能
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                    //验证信息 
                    if (model != null)
                    {
                        var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + "and F_IsUsed=0 order by   F_ID desc ").FirstOrDefault();

                        if (modellist != null)
                        {
                            string createuser = modellist.F_CreateUser;
                            if (!string.IsNullOrEmpty(createuser))
                            {
                                if (createuser != ua.F_UserCode)
                                    return Error("无操作权限");
                            }
                            //if (modellist.F_WoState == (int)EnumWorkOrderState.assign)
                            //{
                            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                            {
                                flag = 3;
                            }
                            else
                            {
                                flag = ua.F_Flag;
                            }
                            var res = RevWO(ua, model, cont, flag);
                            if (res)
                                return Success("撤回成功");
                            //}
                            //else
                            //    return Error("撤回失败！");
                        }
                        return Error("操作失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 工单回访
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult ReturnvisitOrder(long orderid, string reason, string call, string F_VisitRemarks, int isOver = 0, int sms = 0,int resultscore=0,int effectscore=0,int servicescore=0,int qualityscore=0,int npscore=0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            string cont = "";
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        //if (model.F_State != (int)EnumWorkOrderState.dealed)
                        //{
                        //    return Error("此工单状态已经过时，请刷新");
                        //}
                        decimal evaluationscore = 0;
                        evaluationscore =Convert.ToDecimal(Math.Round((double)(resultscore + effectscore + servicescore + qualityscore)/4,1));//9-10非常满意，7-8满意，5-6一般，5分一下不满意
                        if (evaluationscore < 5)
                            cont = "不满意";
                        else if (evaluationscore == 5 || evaluationscore == 6)
                            cont = "一般";
                        else if (evaluationscore == 7 || evaluationscore == 8)
                            cont = "一般";
                        else if (evaluationscore == 9 || evaluationscore == 10)
                            cont = "非常满意";
                        model.F_VisitResultScore = resultscore;
                        model.F_EffectiveScore = effectscore;
                        model.F_ServiceAttitude = servicescore;
                        model.F_ProductQuality = qualityscore;
                        model.F_NPS = npscore;
                        model.F_EvaluationResult = evaluationscore;
                        var res = Retu(ua, model, cont, reason, F_VisitRemarks, call, isOver, sms);
                        if (res)
                            return Success("回访成功");
                        else
                            return Error("回访失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 工单完结
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult EndOrder(long orderid, int isover = 0)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        var res = Overorder(ua, model, isover);
                        if (res)
                            return Success("完结成功");
                        else
                            return Error("完结失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        ///申请延期
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DelayWorkOrder(long orderid, string cont, float limit = 0)
        {
            //办理人员和监管可以延期工单
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        var res = DeWO(ua, model, cont, limit);
                        if (res)
                            return Success("申请成功");
                        else
                            return Error("延期失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");

        }
        /// <summary>
        /// 催办工单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderRemind(long orderid, string cont)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = workOrder.GetModel(orderid);
                    if (model != null)
                    {
                        var res = RemindWO(ua, model, cont);
                        if (res)
                            return Success("催办成功！");
                        else
                            return Error("操作失败！");
                    }
                    return Error("工单不存在！");
                }
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 催办工单
        /// </summary>
        public bool RemindWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont)
        {

            string strsql = " and F_Type in(1,2)";
            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "'"+ strsql + " and F_IsUsed=0 order by F_ID desc");
            #region 接收人
            int todept = 0; string touser = ""; int flag = 3;
            if (itemlast != null && itemlast.Count > 0)
            {
                foreach (var item in itemlast)
                {
                    touser = item.F_NextUser;
                    todept = item.F_NextDept.Value;
                    if (string.IsNullOrWhiteSpace(touser))
                        touser = item.F_CreateUser;
                    var usermodel= sysUserAccountBll.GetModel(touser);
                    if (usermodel != null)
                        flag = usermodel.F_Flag;
                    #region 读取被催办人部门
                    if (todept == 0 && !string.IsNullOrWhiteSpace(touser))
                    {
                        var tomodel = sysUserAccountBll.GetModel(touser);
                        if (tomodel != null)
                            todept = tomodel.F_DeptId;
                    }
                    #endregion
                    #region 读取当前登录人部门
                    string deptname = "";
                    var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    #endregion
                    var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")催办工单，催办说明：" + cont;
                    long itemid = AddLog(model.F_ID, model.F_State.Value, content, (int)EnumItemType.urge, (int)EnumItemOpt.urge, touser, todept, nowUser, model.F_limit, int.Parse(item.F_IsSMS.ToString()),"",0, flag);
                    if (itemid > 0)
                    {
                        if (!string.IsNullOrWhiteSpace(touser))
                        {
                            sendsysmsg(model, nowUser, touser, Int32.Parse(itemid.ToString()), "催办");
                            //var tousers = sysUserAccountBll.GetModel(touser);
                            //if (tousers != null && !string.IsNullOrWhiteSpace(tousers.F_WxOpenId))
                            //{
                            //    sendwxmsg(model, tousers.F_WxOpenId, nowUser, "催办");
                            //}
                        }
                    }
                }
                return true;
            }
            return false;
            #endregion
        }
        /// <summary>
        ///申请延期
        /// </summary>
        public bool DeWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont, float limit)
        {
            #region 工单处理
            int sms = 0; int wostate = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                    itembll.Update(it);
                    wostate = int.Parse(it.F_WoState.ToString());

                }
            }
            int optbut = (int)EnumItemOpt.Delay;
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "延期工单，延期说明：" + cont;
            //获取上一级处理人员
            var touser = "";
            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
            if (itemlast != null)
                touser = itemlast.F_CreateUser;


            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.Delay, optbut, touser, 0, nowUser, limit + model.F_limit, sms, "", 1);

            #endregion

            return true;
        }
        /// <summary>
        /// 退回工单
        /// </summary>
        public bool BackWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont, int type,int flag=1)
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            var opt = "退回";
            int F_OptType = 1;
            int optbut = (int)EnumItemOpt.reback;
            int wostate = (int)EnumWorkOrderState.reback;
            if (type == 1)
            {
                opt = "异常退回";
                optbut = (int)EnumItemOpt.abreback;
                wostate = (int)EnumWorkOrderState.abreback;
                F_OptType = 2;
            }
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单，退回说明：" + cont;
            //获取上一级处理人员

            var touser = ""; var deptid = 0;
            string strsql = "";
            if (flag == 1)
            {
                strsql = $" and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = $" and F_Type in(2,3)";
            }

            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and F_NextDept =" + nowUser.F_DeptId + " and F_WoState =" + F_OptType +  " and  F_WoID='" + model.F_ID + "'"+ strsql+" order by F_ID desc").FirstOrDefault();
            if (itemlast != null)
            {
                touser = itemlast.F_CreateUser;
                if (!string.IsNullOrEmpty(touser))
                {
                    var ua = sysUserAccountBll.GetModel(touser);
                    if (ua != null)
                    {
                        deptid = ua.F_DeptId;
                    }
                }
            }


            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, touser, deptid, nowUser, model.F_limit, sms,"",0,flag);
            if (itemid > 0)
            {
                string smscont = "";
                if (model.F_Type == "1")
                {
                    smscont = "咨询";
                }
                else if (model.F_Type == "2")
                {
                    smscont = "投诉";
                }
                else if (model.F_Type == "3")
                {
                    smscont = "抽检";
                }
                else if (model.F_Type == "5")
                {
                    smscont = "业务协办";
                }
                else
                {
                    smscont = "建议";
                }
                string[] mag = { smscont };
                string smsmsg = "您好，您有一条新的" + smscont + "工单，请及时接单处理！";
                var tousermodel = new BLL.T_Sys_UserAccount().GetModel(touser);
                if (tousermodel != null)
                {
                    if (!string.IsNullOrEmpty(tousermodel.F_Mobile))
                    {
                        SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, tousermodel.F_Mobile.Trim());
                        bool n = new SMSController().AddSmS(tousermodel.F_Mobile.Trim(), smsmsg, nowUser.F_UserId);
                    }
                }
                #region 处理工单
                if (deptid == 2)
                {
                    if (flag == 1)
                    {
                        model.F_State = (int)EnumWorkOrderState.reassign;
                    }
                    else if (flag == 2)
                    {
                        model.F_State2 = (int)EnumWorkOrderState.reassign;
                    }
                }
                else
                {
                    if (flag == 1)
                    {
                        model.F_State = wostate;
                    }
                    else if (flag == 2)
                    {
                        model.F_State2 = wostate;
                    }

                }
                workOrder.Update(model);
                #endregion
                #region 推送消息
                #region 向上一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser) && touser != nowUser.F_UserCode)
                {//排除上一级指派人是自己
                    sendsysmsg(model, nowUser, touser, (int)itemid, opt);
                    var lastUser = sysUserAccountBll.GetModel(touser);
                    //if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                    //   sendwxmsg(model, lastUser.F_WxOpenId, nowUser, opt);
                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }

        /// <summary>
        /// 撤回工单
        /// </summary>
        public bool RevWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont,int flag=1)
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            var opt = "撤回";
            int F_OptType = 1;
            int optbut = (int)EnumItemOpt.revoke;
            int wostate = (int)EnumWorkOrderState.revoke;
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单，撤回说明：" + cont;
            //获取上一级处理人员

            var touser = ""; var deptid = 0;
            string strsql = "";
            if (flag == 1)
            {
                strsql = " and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = " and F_Type in(2,3)";
            }
            else
            {
                strsql = "";
            }

            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_IsUsed=0 and F_WoState =" + F_OptType + " and  F_WoID='" + model.F_ID + "'"+strsql+" order by F_ID desc");
            if (itemlast != null && itemlast.Count>0)
            {
                foreach (var item in itemlast)
                {
                    touser = item.F_NextUser;
                    if (!string.IsNullOrEmpty(touser))
                    {
                        var ua = sysUserAccountBll.GetModel(touser);
                        if (ua != null)
                        {
                            deptid = ua.F_DeptId;
                        }
                    }
                }
            }
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, nowUser.F_UserCode, nowUser.F_DeptId, nowUser, model.F_limit, sms,"",0,flag);
            if (itemid > 0)
            {
                #region 发短信
                //string smscont = "";
                //if (model.F_Type == "1")
                //{
                //    smscont = "咨询";
                //}
                //else if (model.F_Type == "2")
                //{
                //    smscont = "投诉";
                //}
                //else if (model.F_Type == "3")
                //{
                //    smscont = "抽检";
                //}
                //else
                //{
                //    smscont = "建议";
                //}
                //string[] mag = { smscont };
                //string smsmsg = "您好，您有一条待处理的工单已被撤回,请留意！";
                //var tousermodel = new BLL.T_Sys_UserAccount().GetModel(touser);
                //if (tousermodel != null)
                //{
                //    if (!string.IsNullOrEmpty(tousermodel.F_Mobile))
                //    {
                //        SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, tousermodel.F_Mobile.Trim());
                //        bool n = new SMSController().AddSmS(tousermodel.F_Mobile.Trim(), smsmsg, nowUser.F_UserId);
                //    }
                //}
                #endregion
                #region 处理工单
                if (flag == 1)
                {
                    model.F_State = wostate;
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;
                }
                else
                {
                    model.F_State = wostate;
                    model.F_State2 = wostate;
                }
                workOrder.Update(model);
                #endregion
                #region 推送消息
                #region 向上一级操作人员推送消息
                //if (!string.IsNullOrWhiteSpace(touser) && touser != nowUser.F_UserCode)
                //{//排除上一级指派人是自己
                //    sendsysmsg(model, nowUser, touser, (int)itemid, opt);
                //    var lastUser = sysUserAccountBll.GetModel(touser);
                //    //if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                //    //   sendwxmsg(model, lastUser.F_WxOpenId, nowUser, opt);
                //}
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }

        /// <summary>
        /// 回访工单
        /// </summary>
        public bool Retu(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont, string reason, string F_VisitRemarks, string call, int isOver = 0, int sms = 0)
        {
            #region 工单处理



            string sid = "";
            var opt = "回访";
            string smscont = "您好，您的反馈公司已安排人员给予解决，请您对我们的服务进行评价，满意请回复1，一般请回复2，不满意请回复3。谢谢！";
            int optbut = (int)EnumItemOpt.visit;
            int wostate = (int)EnumWorkOrderState.evaluate;
            if (isOver == 0)
            {
                wostate = (int)EnumWorkOrderState.finish;
            }
            else
            {
                if (sms != 0)
                {
                    if (!string.IsNullOrEmpty(model.F_CusPhone.Trim()))
                    {
                        string msg = "【心连心客服中心】您好，您的反馈公司已安排人员给予解决，请您对我们的服务进行评价，满意请回复1，一般请回复2，不满意请回复3。谢谢！";
                        SmsSingleSenderResult result = new SMSController().SMSSingleshot(model.F_CusPhone.Trim(), msg);
                        bool n = new SMSController().AddSmS(model.F_CusPhone, smscont, nowUser.F_UserId);
                        if (result != null)
                        {
                            sid = result.sid.Trim();
                        }
                    }
                }
            }
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单:回访结果：" + cont + " , " + "工单:呼叫结果：" + call;

            var touser = "";
            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
            if (itemlast != null)
                touser = itemlast.F_CreateUser;
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.evaluate, optbut, touser, 0, nowUser, model.F_limit, sms);
            if (itemid > 0)
            {
                #region 处理工单
                model.F_State = wostate;
                model.F_State2 = wostate;
                model.F_VisitOn = DateTime.Now;
                model.F_VisitResult = cont;
                model.F_VisitBy = nowUser.F_UserCode;
                model.F_VisitReason = reason;
                model.F_Callresults = call;
                model.F_Sid = sid;
                model.F_VisitRemarks = F_VisitRemarks;
                workOrder.Update(model);
                #endregion
                #region 推送消息
                #region 向上一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser) && touser != nowUser.F_UserCode)
                {//排除上一级指派人是自己
                    sendsysmsg(model, nowUser, touser, (int)itemid, opt);
                    var lastUser = sysUserAccountBll.GetModel(touser);
                    //if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                    //    sendwxmsg(model, lastUser.F_WxOpenId, nowUser, opt);
                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        /// <summary>
        /// 完结工单
        /// </summary>
        public bool Overorder(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, int isOver = 0, int flag = 3)
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.visit + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            var opt = "完结";
            int optbut = (int)EnumItemOpt.end;
            int wostate = (int)EnumWorkOrderState.evaluate;
            if (isOver == 0)
            {
                wostate = (int)EnumWorkOrderState.finish;
            }

            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "完结工单";

            var touser = "";
           
            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
            if (itemlast != null)
                touser = itemlast.F_CreateUser;
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, touser, 0, nowUser, model.F_limit, sms);
            if (itemid > 0)
            {
                #region 处理工单
                model.F_VisitOn = DateTime.Now;
                model.F_State = wostate;
                model.F_State2 = wostate;
                workOrder.Update(model);
                #endregion
                #region 推送消息
                #region 向上一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser) && touser != nowUser.F_UserCode)
                {//排除上一级指派人是自己
                    sendsysmsg(model, nowUser, touser, (int)itemid, opt);
                    // var lastUser = sysUserAccountBll.GetModel(touser);
                    //if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                    //    sendwxmsg(model, lastUser.F_WxOpenId, nowUser, opt);
                }
                //   if (!string.IsNullOrEmpty(model.F_WxOpenId))
                //    sendwxmsg(model, model.F_WxOpenId, nowUser, model.F_DealContent );
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        /// <summary>
        /// 处理工单
        /// </summary>
        public bool DealWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, WorkOrderNewInput input, string cont, string F_Files, int isover = 0, string uncont = "", int flag = 1,string eventreason="")
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {

                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            var opt = "处理";
            int optbut = (int)EnumItemOpt.deal;
            int wostate = (int)EnumWorkOrderState.receive;
            string nextuser = "";
            int nextdept = 0;

            if (isover == 1)
            {
                model.F_DealResult = "已处理";//处理结果
                opt = "处理完结";
                optbut = (int)EnumItemOpt.deal;
                wostate = (int)EnumWorkOrderState.finish;
                model.F_DealBy = nowUser.F_UserCode;
                model.F_DealTime = DateTime.Now;
            }
            else
            {
                model.F_DealResult = "未处理";//处理结果
                model.F_DealReasons = uncont;//未处理原因
                nextuser = nowUser.F_UserCode;
                nextdept = nowUser.F_DeptId;
            }
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var optcont = "";
            if (!string.IsNullOrEmpty(cont))
                optcont = "，处理内容：" + cont;
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单" + optcont;
            var itemid = AddLog(model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, nextuser, nextdept, nowUser, model.F_limit, sms, "", 0, flag);
            if (itemid > 0)
            {
                #region 处理工单
                if (flag == 1)
                {
                    model.F_State = wostate;
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;
                }
                //处理内容
                if (!string.IsNullOrEmpty(F_Files))
                {
                    if (!string.IsNullOrEmpty(model.F_Files))
                        model.F_Files = model.F_Files + "," + F_Files;
                    else
                        model.F_Files = F_Files;
                }

                if (!string.IsNullOrEmpty(cont))
                {
                    if (model.F_Source == "3")
                    {
                        if (flag == 2)
                        {
                            model.F_DealContent2 = cont;
                        }
                        else
                        {
                            model.F_DealContent = cont;
                       
                        }
                    }
                    else
                    {
                        if (flag == 2)
                        {
                            model.F_DealContent2 += cont + "；";
                        }
                        else
                        {
                            model.F_DealContent += cont + "；";
                        }

                    }
                    if (flag == 1 && model.F_Flag != 2)
                    {
                        model.F_SuperiorOpinion = cont;
                    }
                    else if (flag == 2 && model.F_Flag != 1)
                    {
                        model.F_SuperiorOpinion2= cont;
                    }                 
                }
                if (!string.IsNullOrEmpty(eventreason))
                {
                    if (flag == 1 && model.F_Flag != 2)
                    {
                        model.F_EventReason = eventreason;
                    }
                    else if (flag == 2 && model.F_Flag != 1)
                    {
                        model.F_EventReason2 = eventreason;
                    }
                }

                model.F_DealTime = DateTime.Now;
                InToworkModel(model, input);
                workOrder.Update(model);
                #endregion
                #region 推送消息
                #region 推送消息给添加的坐席 -处理情况
                if (nowUser.F_UserCode != model.F_CreateBy)
                {
                    sendsysmsg(model, nowUser, model.F_CreateBy, (int)model.F_ID, opt);//推送系统消息
                    if (model.F_State == (int)EnumWorkOrderState.finish && model.F_State2 == (int)EnumWorkOrderState.finish)
                    {
                        var createmodel = sysUserAccountBll.GetModel(model.F_CreateBy);  //被指派人
                        if (createmodel != null)
                        {
                            if (!string.IsNullOrEmpty(createmodel.F_WxOpenId))
                            {
                                sendwxmsg(model, createmodel.F_WxOpenId, nowUser, "工单完结");
                            }
                        }
                    }
                    #region 财务审核后，填单人员可以收到到账提醒（短信到账提醒）20220217
                    if (nowUser.F_DeptId == 260)
                    {
                        string[] mag = { };
                        var noticlus = sysUserAccountBll.GetModel(model.F_CreateBy);
                        if (!string.IsNullOrEmpty(noticlus.F_Mobile))
                        {
                            //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, noticlus.F_Mobile.Trim());
                            //bool n = new SMSController().AddSmS(noticlus.F_Mobile.Trim(), "返款到账", nowUser.F_UserId);
                        }
                    }
                    #endregion
                }
                #endregion
                #region 向上一级操作人员推送消息
                var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
                if (itemlast != null)
                {
                    if (itemlast.F_CreateUser != model.F_CreateBy)
                    {
                        sendsysmsg(model, nowUser, itemlast.F_CreateUser, (int)itemid, opt);
                        //   var lastUser = sysUserAccountBll.GetModel(itemlast.F_CreateUser);
                        //   if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                        //       sendwxmsg(model, lastUser.F_WxOpenId, nowUser, opt);
                    }
                }
                #endregion
                #region 办理完结向客户发送消息
                if (model.F_State == (int)EnumWorkOrderState.finish && model.F_State2 == (int)EnumWorkOrderState.finish)
                {
                    if (!string.IsNullOrEmpty(model.F_CustomerID))
                    {

                        var cusmodel = cusbll.GetModel(model.F_CustomerID.Trim());
                        // if (cusmodel != null && !string.IsNullOrEmpty(cusmodel.F_WxOpenId))
                        //   {
                        //    sendwxmsg(model, cusmodel.F_WxOpenId, nowUser, opt);
                        // }
                    }
                    if (isover == 1)
                    {
                        //  if (!string.IsNullOrEmpty(model.F_WxOpenId))
                        //   sendwxmsg(model, model.F_WxOpenId, nowUser, model.F_DealContent);
                    }

                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        /// <summary>
        /// 接单
        /// </summary>
        public bool SureWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, int flag = 3)
        {
            int overtime = 0, sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        overtime = int.Parse(it.F_LimitTime);
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            #region 工单处理
            var opt = "处理接单";
            int optbut = (int)EnumItemOpt.receive;
            int wostate = (int)EnumWorkOrderState.receive;

            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt;
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, nowUser.F_UserCode, nowUser.F_DeptId, nowUser, overtime, sms, "", 0, flag);
            if (itemid > 0)
            {
                #region 处理工单
                if (flag == 1)
                {
                    model.F_State = wostate;//已接单待处理
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;//已接单待处理
                }
                model.F_DealBy = nowUser.F_UserCode;//已接单待处理
                workOrder.Update(model);
                #endregion
                #region 推送消息
                //读取上一级指派人员以及添加坐席并推送系统消息和微信消息
                #region 给添加坐席推送系统消息和微信消息
                sendsysmsg(model, nowUser, model.F_CreateBy, (int)itemid, "处理接单");
                //   var createUser = sysUserAccountBll.GetModel(model.F_CreateBy);
                //   if (createUser != null && !string.IsNullOrEmpty(createUser.F_WxOpenId))
                //   sendwxmsg(model, createUser.F_WxOpenId, nowUser, "接单");
                #endregion
                #region 读取上一级指派人员推送系统消息和微信消息
                var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
                if (itemlast != null)
                {
                    if (itemlast.F_CreateUser != model.F_CreateBy)
                    {
                        sendsysmsg(model, nowUser, itemlast.F_CreateUser, (int)itemid, "处理接单");
                        //     var lastUser = sysUserAccountBll.GetModel(itemlast.F_CreateUser);
                        //   if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                        //    sendwxmsg(model, lastUser.F_WxOpenId, nowUser, "接单");
                    }
                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        /// <summary>
        /// </summary>
        /// <param name="model"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private Model.T_Wo_WorkOrder InToworkModel(Model.T_Wo_WorkOrder model, WorkOrderNewInput input)

        {
            if (!string.IsNullOrEmpty(input.F_SC_ProductBase))
                model.F_SC_ProductBase = input.F_SC_ProductBase;//市场管理科-生产基地（新乡、新疆、九江、东北、贴牌、无法确定）
            if (!string.IsNullOrEmpty(input.F_SC_PreliminaryOpinion))
                model.F_SC_PreliminaryOpinion = input.F_SC_PreliminaryOpinion;// 市场管理科-初审意见:退货、换货、补偿、自行处理
            if (!string.IsNullOrEmpty(input.F_SC_QualityMonth))
                model.F_SC_QualityMonth = input.F_SC_QualityMonth;//市场管理科-超出质保期限（算法：工单创建日期-生产日期，生产日期根据生产批次号获取，单位：月）
            if (!string.IsNullOrEmpty(input.F_SC_CJ_SpotResult))
                model.F_SC_CJ_SpotResult = input.F_SC_CJ_SpotResult;/// 市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
            if (!string.IsNullOrEmpty(input.F_SC_CJ_SelfResult))
                model.F_SC_CJ_SelfResult = input.F_SC_CJ_SelfResult;//市场管理科-抽检-自检结果
            if (!string.IsNullOrEmpty(input.F_SC_CJ_ApprovalNo))
                model.F_SC_CJ_ApprovalNo = input.F_SC_CJ_ApprovalNo;// 市场管理科-抽检-对应审批工作流单号
            if (!string.IsNullOrEmpty(input.F_SC_CJ_ReturnAccount))
                model.F_SC_CJ_ReturnAccount = input.F_SC_CJ_ReturnAccount;//市场管理科-抽检-确认返账金额（元）
            if (!string.IsNullOrEmpty(input.F_ZL_QualityEventLevel))
                model.F_ZL_QualityEventLevel = input.F_ZL_QualityEventLevel;// 质量管理科-质量事件等级（未遂、一般、较大、重大）
            if (!string.IsNullOrEmpty(input.F_ZL_ClaimAmount))
                model.F_ZL_ClaimAmount = input.F_ZL_ClaimAmount;//质量管理科-索赔金额（单位元，对应责任单位）
            if (!string.IsNullOrEmpty(input.F_ZL_ResponsibleUnit))
                model.F_ZL_ResponsibleUnit =string.IsNullOrEmpty(model.F_ZL_ResponsibleUnit)? input.F_ZL_ResponsibleUnit: model.F_ZL_ResponsibleUnit+"；"+ input.F_ZL_ResponsibleUnit;//质量管理科-责任单位（需列出，可选多个）
            if (!string.IsNullOrEmpty(input.F_ZL_ApprovalOpinions))
                model.F_ZL_ApprovalOpinions = input.F_ZL_ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
            if (!string.IsNullOrEmpty(input.F_ZL_ApprovalDisagree))
                model.F_ZL_ApprovalDisagree = input.F_ZL_ApprovalDisagree;// 质量管理科-审批不同意意见
            if (!string.IsNullOrEmpty(input.F_ZL_CompensationMethod))
                model.F_ZL_CompensationMethod = input.F_ZL_CompensationMethod;//质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
            if (!string.IsNullOrEmpty(input.F_ZL_CompensationMoney))
                model.F_ZL_CompensationMoney = input.F_ZL_CompensationMoney;// 质量管理科-补偿钱款
            if (!string.IsNullOrEmpty(input.F_ZL_CResponsibleUnits))
                model.F_ZL_CResponsibleUnits = input.F_ZL_CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
            if (!string.IsNullOrEmpty(input.F_ZL_Fquantity))
                model.F_ZL_Fquantity = input.F_ZL_Fquantity;// 质量管理科-确认实收数量（吨）
            if (!string.IsNullOrEmpty(input.F_ZL_ImprovementRequirements))
                model.F_ZL_ImprovementRequirements = string.IsNullOrEmpty(model.F_ZL_ImprovementRequirements) ? input.F_ZL_ImprovementRequirements : model.F_ZL_ImprovementRequirements + "；" + input.F_ZL_ImprovementRequirements;//质量管理科-改进要求
            if (!string.IsNullOrEmpty(input.F_ZL_CApprovalNo))
                model.F_ZL_CApprovalNo = input.F_ZL_CApprovalNo;//质量管理科-对应审批工作流单号
            if (!string.IsNullOrEmpty(input.F_ZL_CJ_IsRecord))
                model.F_ZL_CJ_IsRecord = input.F_ZL_CJ_IsRecord;//质量管理科-抽检-未备案、已备案
            if (input.F_IsVisit != null)
            {
                try
                {
                    model.F_IsVisit = int.Parse(input.F_IsVisit);
                }
                catch
                {
                    model.F_IsVisit = 1;
                }

            }
            //if (input.MaterialItems != null && input.MaterialItems.Count > 0)
            //{
            //    model.MaterialItems = input.MaterialItems; //多物料
            //}
            if (!string.IsNullOrEmpty(input.F_CarNumber))//返厂车牌号
                model.F_CarNumber = input.F_CarNumber;
            if (input.F_LoadingFee > 0)//装车费
                model.F_LoadingFee = input.F_LoadingFee;
            if (input.F_UnLoadingFee > 0) //卸车费
                model.F_UnLoadingFee = input.F_UnLoadingFee;
            if (input.F_MaterialFee > 0) //返料费
                model.F_MaterialFee = input.F_MaterialFee;
            //if (!string.IsNullOrEmpty(input.F_EventReason))
            //    model.F_EventReason = input.F_EventReason;//质量管理科-事件原因
            if (!string.IsNullOrEmpty(input.F_DrivePhone))
                model.F_DrivePhone = input.F_DrivePhone;//电话号码
            if (!string.IsNullOrEmpty(input.F_WorkmanShip))
                model.F_WorkmanShip = input.F_WorkmanShip;//质量管理科-工艺
            if (!string.IsNullOrEmpty(input.F_Manufacturers))
                model.F_Manufacturers = input.F_Manufacturers;//质量管理科-原料及厂家
            if (input.F_ProductionNum > 0)
                model.F_ProductionNum = input.F_ProductionNum;//质量管理科-该批次生产数量

            return model;
        }
        public bool SendSms(string type, string F_Mobile, int userid)
        {
            string smscont = "";
            if (type == "1")
            {
                smscont = "咨询";
            }
            else if (type == "2")
            {
                smscont = "投诉";
            }
            else if (type == "3")
            {
                smscont = "抽检";
            }
            else if (type == "5")
            {
                smscont = "业务协办";
            }
            else
            {
                smscont = "建议";
            }
            string[] mag = { smscont };
            string smsmsg = "您好，您有一条新的" + smscont + "工单，请及时接单处理！";
            SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, F_Mobile.Trim());
            bool n = new SMSController().AddSmS(F_Mobile.Trim(), smsmsg, userid);
            return n;

        }
        /// <summary>
        /// 转派工单
        /// </summary>
        public bool AssignWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, WorkOrderNewInput input, string cont, string F_Files, int clbm = 0, int clid = 0, int overtime = 0, int sms = 0, int isApprovalp = 0, int hclbm = 0, int hclid = 0, string creat = "", int isbl = 0, int flag = 1)
        {
            #region 系统升级派单时限可修改2021/12/24
            //if (model.F_limit > 0)
            //    overtime = model.F_limit;
            #endregion
            string smscont = "";
            if (model.F_Type == "1")
            {
                smscont = "咨询";
            }
            else if (model.F_Type == "2")
            {
                smscont = "投诉";
            }
            else if (model.F_Type == "3")
            {
                smscont = "抽检";
            }
            else if (model.F_Type == "5")
            {
                smscont = "业务协办";
            }
            else
            {
                smscont = "建议";
            }
            string[] mag = { smscont };
            string smsmsg = "您好，您有一条新的" + smscont + "工单，请及时接单处理！";

            string touser = ""; string tousername = "";

            int deptid = 0;
            #region 获取接收人
            if (clid != 0)
            {
                Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(clid);

                deptid = clus.F_DeptId;
                clbm = clus.F_DeptId;
                if (clus != null)
                {
                    touser = clus.F_UserCode;
                    tousername = clus.F_UserName + "(" + clus.F_WorkNumber + ")";
                    if (sms != 0)
                    {
                        if (!string.IsNullOrEmpty(clus.F_Mobile))
                        {
                            SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, clus.F_Mobile.Trim());
                            bool n = new SMSController().AddSmS(clus.F_Mobile.Trim(), smsmsg, nowUser.F_UserId);
                        }

                    }
                }

            }
            else
            {
                string users = string.Empty;
                deptid = clbm;
                string sql = "";
                if (isbl > 0)
                {
                    sql = "and F_RoleId in(select F_RoleId from T_Sys_RoleInfo where  F_RoleCode='BLRY')";
                }
                var list = sysUserAccountBll.GetModelList(" F_DeptId='" + clbm + "' and F_DeleteFlag=0 " + sql);
                foreach (var l in list)
                {
                    if (string.IsNullOrEmpty(users))
                    {
                        users = l.F_UserCode;
                        tousername = l.F_UserName + "(" + l.F_WorkNumber + ")";
                    }
                    else
                    {
                        users = users + "," + l.F_UserCode;
                        tousername = tousername + "," + l.F_UserName + "(" + l.F_WorkNumber + ")";
                    }
                    if (sms != 0)
                    {
                        if (!string.IsNullOrEmpty(l.F_Mobile.Trim()))
                        {
                            SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, l.F_Mobile.Trim());
                            bool n = new SMSController().AddSmS(l.F_Mobile.Trim(), smsmsg, nowUser.F_UserId);
                        }

                    }
                }
                touser = users;
            }
            string htouser = "", htousername = "";
            if (isApprovalp != 0 && nowUser.F_DeptId == 37)
            {
                if (hclid != 0)
                {
                    Model.T_Sys_UserAccount clus = sysUserAccountBll.GetModel(hclid);
                    if (clus != null)
                    {
                        if (string.IsNullOrEmpty(htouser))
                        {
                            htouser = clus.F_UserCode;
                            htousername = clus.F_UserName + "(" + clus.F_WorkNumber + ")";
                        }
                    }
                }
                else
                {
                    var list = sysUserAccountBll.GetModelList(" F_DeptId='" + hclbm + "'");
                    foreach (var l in list)
                    {
                        if (string.IsNullOrEmpty(htouser))
                        {
                            htouser = l.F_UserCode;
                            htousername = l.F_UserName + "(" + l.F_WorkNumber + ")";
                        }
                        else
                        {
                            htouser = htouser + "," + l.F_UserCode;
                            htousername = htousername + "," + l.F_UserName + "(" + l.F_WorkNumber + ")";
                        }
                    }
                }
              AddLog(model.F_ID, (int)EnumWorkOrderState.assign, htousername + "高层待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, htouser, hclbm, nowUser, overtime, sms, creat, 2);
            }

            #region 财务审核后，填单人员可以收到到账提醒（短信到账提醒）20220217
            if (nowUser.F_DeptId == 260)
            {
                var noticlus = sysUserAccountBll.GetModel(model.F_CreateBy);
                if (!string.IsNullOrEmpty(noticlus.F_Mobile))
                {
                    //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, noticlus.F_Mobile.Trim());
                    //bool n = new SMSController().AddSmS(noticlus.F_Mobile.Trim(), "返款已到账", nowUser.F_UserId);
                }
            }
            #endregion
            #endregion
            #region 工单处理
            var opt = "指派";
            int optbut = (int)EnumItemOpt.assign;
            int wostate = (int)EnumWorkOrderState.assign;//已指派待接单
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var optcont = "";
            if (!string.IsNullOrEmpty(cont))
                optcont = "，说明：" + cont;
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单给 " + tousername + optcont;
            var itemid = AddLog(model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, touser, clbm, nowUser, overtime, sms, creat, 0, flag);
            if (itemid > 0)
            {
                #region 处理工单
                //工单完结要更新工单的状态
                //   model.F_DealBy = touser;
                if (flag == 1)
                {
                    model.F_State = wostate;
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;
                }
                if (model.F_limit == 0)
                    model.F_limit = overtime;
                //处理内容
                if (!string.IsNullOrEmpty(cont))
                    if (flag == 2)
                    {
                        model.F_DealContent2 += cont + "；";
                    }
                    else
                    {
                        model.F_DealContent += cont + "；";
                    }
                InToworkModel(model, input);

                if (!string.IsNullOrEmpty(F_Files))
                {
                    if (!string.IsNullOrEmpty(model.F_Files))
                        model.F_Files = model.F_Files + "," + F_Files;
                    else
                        model.F_Files = F_Files;
                }
                workOrder.Update(model);
                #region 添加物料信息
                if (model.MaterialItems != null && model.MaterialItems.Count > 0)
                {
                    //var delmodels=new BLL.T_Wo_MaterialItems().GetModelList($" F_WoID ={ model.F_ID}");
                    //if (delmodels != null && delmodels.Count>0)
                    //{
                    //    string delids =string.Join(",", delmodels.Select(p => p.F_Id).ToArray());
                    //    new BLL.T_Wo_MaterialItems().DeleteList(delids);
                    //}
                    foreach (var item in model.MaterialItems)
                    {
                        if (item.F_Id > 0)
                        {
                            new BLL.T_Wo_MaterialItems().Update(item);
                        }
                        else
                        {
                            new BLL.T_Wo_MaterialItems().Add(item);
                        }
                    }
                }
                #endregion
                #endregion
                #region 推送消息
                #region 推送消息给添加的坐席 -转派和处理
                if (nowUser.F_UserCode != model.F_CreateBy)
                {
                    sendsysmsg(model, nowUser, model.F_CreateBy, (int)model.F_ID, opt);//推送系统消息
                    var createmodel = sysUserAccountBll.GetModel(model.F_CreateBy);  //被指派人
                                                                                     //    if (createmodel != null)
                                                                                     //  {
                                                                                     //   if (!string.IsNullOrEmpty(createmodel.F_WxOpenId))
                                                                                     //  {
                                                                                     //    sendwxmsg(model, createmodel.F_WxOpenId, nowUser, opt);
                                                                                     //   }
                                                                                     //  }
                }
                #endregion
                #region 向下一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser))
                {
                    sendsysmsg(model, nowUser, touser, (int)model.F_ID, opt);//推送系统消息
                    var modelUser2 = sysUserAccountBll.GetModel(touser);  //被指派人
                                                                          //  if (modelUser2 != null)
                                                                          // {
                                                                          //  if (!string.IsNullOrEmpty(modelUser2.F_WxOpenId))
                                                                          // {
                                                                          //     sendwxmsg(model, modelUser2.F_WxOpenId, nowUser, "指派");
                                                                          //   }
                                                                          //  }
                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        //推送系统提醒
        public void sendsysmsg(Model.T_Wo_WorkOrder womodel, Model.T_Sys_UserAccount nowUser, string touser, int toid, string opt)
        {
            #region 消息提醒
            string strmsg = string.Empty;
            strmsg = nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + "操作" + opt + "工单";
            Model.T_Msg_List msg = new Model.T_Msg_List();
            msg.Type = (int)Model.MSGType.Handle;//处理
            msg.ToUser = touser;
            msg.ToID = toid;
            msg.Detail = strmsg;
            msg.State = 0;
            msg.IsDel = 0;
            msg.CreateUser = nowUser.F_UserCode;
            msg.CreateDate = DateTime.Now;

            new BLL.T_Msg_List().Add(msg);
            #endregion
        }


        //推送微信消息
        public void sendwxmsg(Model.T_Wo_WorkOrder womodel, string openid, Model.T_Sys_UserAccount nowUser, string opt)
        {
            #region 推送微信
            try
            {
                if (!string.IsNullOrEmpty(openid))
                {
                    var dicv = dicvalueBll.GetModel(int.Parse(womodel.F_Type));
                    string content = string.Empty;
                    var wotype = "";
                    if (dicv != null)
                    {
                        wotype = dicv.F_Name;
                    }
                    content = opt;
                    var msg = WxHelper.SendWechatMsg1(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "你的工单已处理", wotype, womodel.F_State.ToString(), content, womodel.F_ID.ToString(), openid, "");
                    Error("推送微信::::::" + msg.ToString());
                }
            }
            catch { }
            #endregion
        }

    }



    public class WorkOrdeDeptment
    {
        /// <summary>
        /// 市场管理科-生产基地（新乡、新疆、九江、东北、贴牌、无法确定）
        /// </summary>
        public string ProductBase
        {
            get; set;
        }
        /// <summary>
        /// 市场管理科-初审意见:退货、换货、补偿、自行处理
        /// </summary>
        public string PreliminaryOpinion
        {
            get; set;
        }
        /// <summary>
        /// 市场管理科-超出质保期限（算法：工单创建日期-生产日期，生产日期根据生产批次号获取，单位：月）
        /// </summary>
        public string QualityMonth
        {
            get; set;
        }
        /// <summary>
        /// 市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
        /// </summary>
        public string SpotResult
        {
            get; set;
        }
        /// <summary>
        /// 市场管理科-抽检-自检结果
        /// </summary>
        public string SelfResult
        {
            get; set;
        }
        /// <summary>
        /// 市场管理科-抽检-对应审批工作流单号
        /// </summary>
        public string ApprovalNo
        {
            get; set;
        }
        /// <summary>
        /// 市场管理科-抽检-确认返账金额（元）
        /// </summary>
        public string ReturnAccount
        {
            get; set;
        }
        /// <summary>
        /// 市场管理科-投诉-确认返账金额（元）
        /// </summary>
        public string ReturnAccount2
        {
            get; set;
        }
        public string ReturnAccount3
        {
            get; set;
        }
        
        /// <summary>
        /// 质量管理科-质量事件等级（未遂、一般、较大、重大）
        /// </summary>
        public string QualityEventLevel
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-索赔金额（单位元，对应责任单位）
        /// </summary>
        public string ClaimAmount
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-责任单位（需列出，可选多个）
        /// </summary>
        public string ResponsibleUnit
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
        /// </summary>
        public string ApprovalOpinions
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-审批不同意意见
        /// </summary>
        public string ApprovalDisagree
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
        /// </summary>
        public string CompensationMethod
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-补偿钱款
        /// </summary>
        public string CompensationMoney
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
        /// </summary>
        public string CResponsibleUnits
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-确认实收数量（吨）
        /// </summary>
        public string Fquantity
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-改进要求
        /// </summary>
        public string ImprovementRequirements
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-对应审批工作流单号
        /// </summary>
        public string CApprovalNo
        {
            get; set;
        }
        /// <summary>
        /// 质量管理科-抽检-未备案、已备案
        /// </summary>
        public string IsRecord
        {
            get; set;
        }
        /// <summary>
        /// 返厂车牌号
        /// </summary>
        public string CarNumber { get; set; }
        /// <summary>
        /// 装车费
        /// </summary>
        public decimal? LoadingFee { get; set; }
        /// <summary>
        /// 卸车费
        /// </summary>
        public decimal? UnLoadingFee { get; set; }
        /// <summary>
        /// 返料费
        /// </summary>
        public decimal? MaterialFee { get; set; }

        public string EventReason { get; set; }

        public string WorkmanShip { get; set; }
        /// <summary>
        /// 原料及厂家
        /// </summary>
        public string Manufacturers { get; set; }
        /// <summary>
        /// 该批次生产数量
        /// </summary>
        public int? ProductionNum { get; set; }

        public string DrivePhone { get; set; }
    }
    public class ItemListLog
    {
        public long F_ID
        {
            set;
            get;
        }
        /// <summary>
        /// 工单ID
        /// </summary>
        public string F_WoID
        {
            set;
            get;
        }
        /// <summary>
        /// 工单状态
        /// </summary>
        public int? F_WoState
        {
            set;
            get;
        }
        /// <summary>
        /// 记录类型 1工单处理，2工单催办
        /// </summary>
        public int? F_ItemType
        {
            set;
            get;
        }
        /// <summary>
        /// 操作类型
        /// </summary>
        public int? F_OptType
        {
            set;
            get;
        }
        /// <summary>
        /// 操作内容
        /// </summary>
        public string F_OptContent
        {
            set;
            get;
        }
        /// <summary>
        /// 下一步操作人
        /// </summary>
        public string F_NextUser
        {
            set;
            get;
        }
        /// <summary>
        /// 下一步操作部门
        /// </summary>
        public string F_NextDept
        {
            set;
            get;
        }
        /// <summary>
        /// 是否在用，0是 1否
        /// </summary>
        public int? F_IsUsed
        {
            set;
            get;
        }
        /// <summary>
        /// 时限
        /// </summary>
        public string F_LimitTime
        {
            set;
            get;
        }
        /// <summary>
        /// 是否短信提醒
        /// </summary>
        public int? F_IsSMS
        {
            set;
            get;
        }
        /// <summary>
        /// 短信提醒人
        /// </summary>
        public string F_SMSToUser
        {
            set;
            get;
        }
        /// <summary>
        /// 短信提醒电话
        /// </summary>
        public string F_SMSToPhone
        {
            set;
            get;
        }
        /// <summary>
        /// 短信提醒内容
        /// </summary>
        public string F_SMSContent
        {
            set;
            get;
        }
        /// <summary>
        /// 创建人
        /// </summary>
        public string F_CreateUser
        {
            set;
            get;
        }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime? F_CreateTime
        {
            set;
            get;
        }
        public DateTime? F_LastTime
        {
            set; get;
        }
        public string Timeout { set; get; }

        public string Timeuse { get; set; }

        public List<ItemListLog> loglist { get; set; }
    }

    /// <summary>
    /// 多物料
    /// </summary>
    public class Material
    {
        /// <summary>
        /// 主键id
        /// </summary>
        public string fid { get; set; }
        /// <summary>
        /// 物料编号
        /// </summary>
        public string materialcode { get; set; }

        /// <summary>
        /// 产品名称
        /// </summary>
        public string materialname { get; set; }

        /// <summary>
        /// 规格
        /// </summary>
        public string formula { get; set; }

        /// <summary>
        /// 返厂数量
        /// </summary>
        public int? returnum { get; set; }
        /// <summary>
        /// 规格
        /// </summary>
        public string specs { get; set; }
    }
    /// <summary>
    /// 抄送对象
    /// </summary>
    public class CopyMessage
    {
        public string deptid { get; set; }
        public List<string> ucodelist { get; set; }
    }
}