using RMYY_CallCenter_Api.Controllers.CarManage;
using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Model;
using RMYY_CallCenter_Api.Models.Dto;
using RMYY_CallCenter_Api.Models.Enum;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers.WorkOrder
{
    public class WorkCommonController : BaseController
    {
        private BLL.T_Wo_CommonBase basebll = new BLL.T_Wo_CommonBase();
        private Bll.T_Sys_GongDan gdbll = new Bll.T_Sys_GongDan();
        private Bll.AddLogBll logbll = new Bll.AddLogBll();
        private Bll.T_Con_WorkOrder conbll = new Bll.T_Con_WorkOrder();

        private BLL.T_FaultRepair_Base frbll = new BLL.T_FaultRepair_Base();
        private BLL.T_IntegratedScheduling_Base isbll = new BLL.T_IntegratedScheduling_Base();

        private static InternalMessagesController msg = new InternalMessagesController();

        /// <summary>
        /// 我的提交
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult GetSubmitList(string starttime = "", string endtime = "", string keyword = "", int pageindex = 1, int pagesize = 10, int state = -1, int type = 0, int loweltype = 0, string wocode = "")
        {
            if (User != null)
            {
                int recordCount = 0;
                string sql = " and F_IsDelete = 0";
                // 部门主管
                //  判断当前登录人是不是部门主管角色 
                
                if (User.F_RoleCode== "BMZG")
                {
                    sql += $" and ((F_ProposerDept in(select F_DeptId from [dbo].[GetDeptid] ({User .F_DeptId })) and F_Type!=1000) or (F_DealDept in(select F_DeptId from [dbo].[GetDeptid] ({User.F_DeptId })) and F_Type=1000)  )";
                }
                else {
                    //申请人等于我并且类型不是业务咨询，或者 处理人是我 工单类型是业务咨询
                    sql += $" and ((F_Proposer='{User.F_UserCode}' and F_Type!=1000) or (F_DealUser='{User.F_UserCode}' and F_Type=1000 ))";
                }

                

                //sql = $" and ((F_ProposerDept='{User.F_DeptId}' and F_Type!=1000) or (F_Type=1000 and F_DealDept='{User.F_DeptId}' ) ) and F_IsDelete = 0";
                if (!string.IsNullOrEmpty(wocode))
                {
                    sql += $" and  F_WoCode like'%{wocode}%'";
                }
                if (type > 0)
                {
                    sql += $" and  F_Type={type}";
                }
                if (loweltype > 0)
                {
                    sql += $" and  F_SonType={loweltype}";
                }
                if (state >= 0)
                {
                    sql += $" and  F_IsDone={state}";
                }
                if (!string.IsNullOrEmpty(starttime))
                {
                    sql += $" and F_CreateTime>='{starttime}'";
                }
                if (!string.IsNullOrEmpty(endtime))
                {
                    sql += $" and F_CreateTime<'{endtime}'";
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql += $" and F_Content like '%{keyword}%'";
                }

                DataTable datatable = Bll.PagerBll.GetListPager
                                           ("T_Wo_CommonBase ",
                                             "F_WoCode",
                                             "*,[dbo].[GetUserName](F_Proposer) F_ProposerName,[dbo].[GetUserName](F_DealUser) F_DealUserName",
                                             sql,
                                             "order by F_CreateTime desc",
                                             pagesize,
                                             pageindex,
                                             true,
                                             out recordCount
                                           );

                datatable = WorkOrderBase.SetOtherField(datatable, MENUENUM.我的提交,User.F_UserCode, User.F_RoleId);

                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = datatable,
                    total = recordCount

                };
                return Content(obj.ToJson());
            }
            return Error("无操作权限！");
        }


        /// <summary>
        /// 综合查询
        /// </summary>
        /// <param name="tab">0 是调度中心待完成 状态等于0； 1 是已完成 状态>0 2 状态>=0是全部 </param>
        /// <param name="keyword"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult GetComList(int? myd, string starttime = "",string phone="", string endtime = "", string keyword = "", int pageindex = 1, int pagesize = 10, int state = -1, int type = 0, int loweltype = 0, string wocode = "", int isdc = 0,int tab=0)
        {
            if (User != null)
            {
                int recordCount = 0;
                string sql = $" and F_IsDelete = 0  ";
                if (!string.IsNullOrEmpty(wocode))
                {
                    sql += $" and  F_WoCode like'%{wocode}%'";
                }

                switch (tab)
                {
                    case 0:
                        sql +=$" and  F_Status=0";
                        break;
                    case 1:
                        sql += $" and  F_Status>0";
                        break;
                    case 2:
                        sql += $" and  F_Status>=0";
                        break;
         
                        

                }


                if (type > 0)
                {
                    sql += $" and  F_Type={type}";
                }
                if (myd != null)
                {
                    sql += $" and  MYD={myd}";
                }
                sql += "and F_Type !=4000";
                if (loweltype > 0)
                {
                    sql += $" and  F_SonType={loweltype}";
                }
                if (state >= 0)
                {
                    sql += $" and  F_IsDone={state}";
                }
                if (!string.IsNullOrEmpty(starttime))
                {
                    sql += $" and F_CreateTime>='{starttime}'";
                }
                if (!string.IsNullOrEmpty(endtime))
                {
                    sql += $" and F_CreateTime<'{endtime}'";
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql += $" and F_Content like '%{keyword}%'";
                }
                if (!string.IsNullOrEmpty(phone))
                {
                    sql += $" and F_Phone = '{phone}'";
                }

                if (isdc > 0)
                {
                    var dtdc = DbHelperSQL.Query(" select  F_WoCode 工单编号,[dbo].[GetUserName](F_Proposer)  姓名,  dbo.GetGongDanNameByID(F_SonType) 工单类别, F_Content 工单内容, F_Status 工单状态,  (case when MYD =0 then '满意' when  MYD =1 then '基本满意' when  MYD =2 then '不满意' else '' end ) MYD, F_CreateTime 创建时间 from T_Wo_CommonBase "

                       + "   WITH(NOLOCK)  where 1=1 " + sql + "ORDER BY F_CreateTime desc").Tables[0];
                    var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                    if (msg == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }



                DataTable datatable = Bll.PagerBll.GetListPager
                                           ("T_Wo_CommonBase ",
                                             "F_WoCode",
                                             "*,[dbo].[GetUserName](F_Proposer) F_ProposerName,[dbo].[GetUserName](F_DealUser) F_DealUserName, (case when MYD =0 then '满意' when  MYD =1 then '基本满意' when  MYD =2 then '不满意' else '' end )  MYD ",
                                             sql,
                                             "order by F_CreateTime desc",
                                             pagesize,
                                             pageindex,
                                             true,
                                             out recordCount
                                           );

                datatable = WorkOrderBase.SetOtherField(datatable, MENUENUM.工单列表,User.F_UserCode, User.F_RoleId);
              
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = datatable,
                    total = recordCount

                };
                return Content(obj.ToJson());
            }
            return Error("无操作权限！");
        }

       //工单列表导出
        public ActionResult ExportGetComList(int? myd, string starttime = "", string phone = "", string endtime = "", string keyword = "", int pageindex = 1, int pagesize = 10, int state = -1, int type = 0, int loweltype = 0, string wocode = "", int isdc = 0)
        {
            if (User != null)
            {
                int recordCount = 0;
                string sql = $" and F_IsDelete = 0 and F_Status>=0 ";
                if (!string.IsNullOrEmpty(wocode))
                {
                    sql += $" and  F_WoCode like'%{wocode}%'";
                }
                if (type > 0)
                {
                    sql += $" and  F_Type={type}";
                }
                if (myd != null)
                {
                    sql += $" and  MYD={myd}";
                }
                sql += "and F_Type !=4000";
                if (loweltype > 0)
                {
                    sql += $" and  F_SonType={loweltype}";
                }
                if (state >= 0)
                {
                    sql += $" and  F_IsDone={state}";
                }
                if (!string.IsNullOrEmpty(starttime))
                {
                    sql += $" and F_CreateTime>='{starttime}'";
                }
                if (!string.IsNullOrEmpty(endtime))
                {
                    sql += $" and F_CreateTime<'{endtime}'";
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql += $" and F_Content like '%{keyword}%'";
                }
                if (!string.IsNullOrEmpty(phone))
                {
                    sql += $" and F_Phone = '{phone}'";
                }

                


                DataTable datatable = Bll.PagerBll.GetListPager
                                           ("T_Wo_CommonBase ",
                                             "F_WoCode",
                                             "*,[dbo].[GetUserName](F_Proposer) F_ProposerName,[dbo].[GetUserName](F_DealUser) F_DealUserName, (case when MYD =0 then '满意' when  MYD =1 then '基本满意' when  MYD =2 then '不满意' else '' end )  MYDName, dbo.GetGongDanNameByID(F_SonType) gdtype ",
                                             sql,
                                             "order by F_CreateTime desc",
                                             100000,
                                             pageindex,
                                             true,
                                             out recordCount
                                           );

                datatable = WorkOrderBase.SetOtherField(datatable, MENUENUM.工单列表, User.F_UserCode, User.F_RoleId);
               
                DataTable newTable = datatable.DefaultView.ToTable(false, new string[]{ "F_WoCode", "F_ProposerName", "gdtype", "F_Content" , "StateName", "MYDName" , "F_CreateTime" });


         
                
               var msg = new NPOIHelper().ExportToExcel("工单列表", newTable, new string[] { "工单编号", "姓名", "工单类别", "工单内容", "工单状态", "满意度", "创建时间"});
                    if (msg == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
               
 
            }
            return Error("无操作权限！");
        }



        //催单按钮  urge 类型 1是调度员催单 2 是申请人催单
        //        申请人：提交完工单只要工单未完成都可催单
        //调度人：已派单，没有完成状态能催单；   催单按钮在添加的时候 汉字写  催单
        public ActionResult UrgeWorkOrder(string workordercode,string reason, int urgetype = 0)
        {

            if (urgetype ==0)
            {
                return Error("需要传urgetype参数");
            }

            Model.T_Wo_CommonBase ordermodel=  basebll.GetModel(workordercode);

            //工单类型上增加可催办次数字段，=0不允许催办，=-1不限制催办次数，
            //其他的 =几就是可以催办几次
            
            Model.T_Sys_GongDan gdmodel = gdbll.GetModel(ordermodel.F_SonType);

            if (gdmodel.F_CanUrgeCount == 0)
            {
                return Error("该工单类型不允许催办");
            }
            int nowcount = ordermodel.F_UrgeCount + 1;
            if (gdmodel.F_CanUrgeCount != -1 && nowcount > gdmodel.F_CanUrgeCount)
            {
                return Error("催办次数已经用光了");
            }

            ordermodel.F_UrgeCount = nowcount;
            ordermodel.F_UpdateTime = DateTime.Now;
            basebll.Update(ordermodel);
            string content = "催办了工单,催单原因"+reason;
          //  string touser = "";
            EnumSmsType smytype = new EnumSmsType();
            List<string> touserlist = new List<string>();
            //获取调度中心值班人员       

            // 添加日志
            switch (ordermodel.F_Type)
            {
                case 1000:
                   // Bll.T_Con_WorkOrder conbll = new Bll.T_Con_WorkOrder();
                Model.T_Con_WorkOrder conmodel=    conbll.GetModelByCode(workordercode);
                    logbll.AddLog(conmodel.F_ID, conmodel.F_State.Value, (int)conmodel.F_type1, content, (int)EnumItemType.urge, 0, User.F_UserCode, 0, User.F_UserCode);
                    smytype = EnumSmsType.consulting;
                    break;
                case 2000:
                    SchedulingController sc = new SchedulingController();
                    sc.AddOperatorLogNew(content, (int)EnumOperatorType.urge, workordercode,User.F_UserCode);
                    smytype = EnumSmsType.comprehensive ;             
                    break;
                case 3000:
                    FaultRepairController cc = new FaultRepairController();
                    cc.AddOperatorLogNew(content, (int)EnumOperatorType.urge, workordercode,User.F_UserCode);                  
                    smytype = EnumSmsType.repair;
                    break;
                case 4000:
                    T_Car_WorkOrderController car = new T_Car_WorkOrderController();
                    car.AddOperation(content, User.F_UserCode, ordermodel.F_Status, workordercode, 0);
                    smytype = EnumSmsType.car;
                    break;
            }

            //发送消息
            //  点击催单给对应人发消息，如果单子在调度中心，调度中心当日值班人员都可收到消息

            if (urgetype == 1)
            {
                if (!string.IsNullOrEmpty (ordermodel.F_DealUser))
                {
                    touserlist.Add(ordermodel.F_DealUser);

                }
            }
            else if (urgetype == 2)
            {
                if (ordermodel.F_Status == 0)
                {
                    //调度中心当天的值班人员
                    var GroupClass = new Bll.T_Sys_GroupClass().GetModelList("F_IsDelete=0   and datediff(day , F_Date , getdate())= 0 " +
              "and F_DeptId= ( select F_DeptId from T_Sys_Department where F_deptcode='ZHDDZX')  order by F_Id asc");
                    touserlist = GroupClass.Select(x => x.F_UserCode).ToList();
                }
                else
                {
                    touserlist.Add(ordermodel.F_DealUser);
                }
            }
            if (touserlist != null && touserlist.Count > 0)
            {
                foreach (var item in touserlist)
                {
                    msg.AddInternalMessagesInfo("催单", "催单\n" + "工单编号:" + workordercode + "\n" + content, item, User.F_UserCode, smytype, 0, workordercode);
                }
            }
           

         
            return Success("成功催办");
        }


        //我的工单页面 所有类型工单撤回之后增加一个完成按钮，点击完成输入原因，提交之后工单变成已完成
        public ActionResult FinishWorkOrder(string workordercode, string reason, int type)
        {
            try
            {
                string content = "";
                if (!string.IsNullOrEmpty(reason))
                {
                    content = ",原因：" + reason;
                }
                switch (type)
                {
                    //业务咨询
                    case 1000:
                        Model.T_Con_WorkOrder conmodel = conbll.GetModelByCode(workordercode);
                        conmodel.F_State = (int)EnumWorkOrderState.finish; ;
                        conmodel.F_HandleTime = DateTime.Now;
                        conbll.Update(conmodel);
                        var itemid = logbll.AddLog(conmodel.F_ID, (int)EnumWorkOrderState.finish, (int)conmodel.F_type1, content,
                            (int)EnumItemType.deal, (int)EnumItemOpt.end, "", 0, User.F_UserCode);
                        break;
                    //综合调度
                    case 2000:
                        Model.T_IntegratedScheduling_Base ismodel = isbll.GetModel(workordercode);
                        ismodel.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.finish;
                        ismodel.F_Endtime = DateTime.Now;
                        isbll.Update(ismodel);
                        SchedulingController sc = new SchedulingController();
                        sc.AddOperatorLogNew("完结了工单" + content, (int)EnumOperatorType.finish, workordercode,User.F_UserCode);
                        break;
                    case 3000:
                        Model.T_FaultRepair_Base frmodel = frbll.GetModel(workordercode);
                        frmodel.F_Endtime = DateTime.Now;
                        frmodel.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.finish;
                        frbll.Update(frmodel);

                        FaultRepairController cc = new FaultRepairController();
                        cc.AddOperatorLogNew("完结了工单" + content, (int)EnumOperatorType.finish, workordercode, User.F_UserCode);
                        break;
                    //车辆
                    case 4000:
                        var carWorkOrder = new Bll.T_Car_WorkOrder().GetModelByCode(workordercode);
                        carWorkOrder.F_EndTime = DateTime.Now;
                        carWorkOrder.F_FinishTime = DateTime.Now;
                        carWorkOrder.F_State = (int)EnumWorkOrderState.finish;//待评价
                        new Bll.T_Car_WorkOrder().Update(carWorkOrder);
                        T_Car_WorkOrderController carcc = new T_Car_WorkOrderController();
                        carcc.AddOperation("完结了工单" + content, User.F_UserCode, (int)EnumOperatorType.finish, workordercode, 0);
                        var model = new BLL.T_Car_AssignWorkOrder().GetModelList($"F_WorkOrderID like '%{workordercode}%' and F_State!=10 and F_IsDelete=0");
                        if (model != null && model.Count > 0)
                        {
                            var carsql = $"select count(1) from T_Car_WorkOrder where F_WorkOrderCode in({string.Join(",", model.FirstOrDefault().F_WorkOrderID.Split(','))}) and F_State not in(7,10) and F_IsDel=0";
                            var car = DbHelperSQL.GetSingle(carsql).ToString();
                            if (int.Parse(car) <= 0)
                            {
                                var carmodel = new Bll.T_Car_Message().GetModel(model.FirstOrDefault().F_CarId.Value);
                                if (carmodel != null)
                                {
                                    carmodel.F_State = 0;
                                    new Bll.T_Car_Message().Update(carmodel);
                                }

                                model.FirstOrDefault().F_State = (int)EnumWorkOrderState.finish;
                                new BLL.T_Car_AssignWorkOrder().Update(model.FirstOrDefault());
                            }
                        }

                        break;

                }


            }
            catch (Exception e)
            {

                return Error("失败");
            }
      
         

            return Success("成功");
        }
    }
}