using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using HySoft.DBUtility;
using HySoft.Workflow.WFEngine;
using WOSBusineSupporter;
using HySoft.Common;

namespace HySoft.BaseCallCenter.Web.workordermanage.workorder
{
    public partial class orderassign : BasePage
    {
        SimpleWFEngine engine;
        WOSBusineSupporter.WOSBusineSupporter wosBusineSupporter;
        string connStr = DBUtility.DbHelperSQL.connectionString;
        Model.T_Wo_WorkOrderTask taskobj;
        string assOpt = "";
        string instanceId = "";
        string userId = "0";
        string taskId = "";
        string workorderid = "0";
        DateTime time = DateTime.Now;

        string orderstate = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            workorderid = Request.QueryString["workorderid"];//工单编号
            this.GetModelValue(workorderid);
            BLL.T_Wo_WorkOrderTask bll_task = new BLL.T_Wo_WorkOrderTask();
            LoginUser p_LoginUser = new LoginUser(this.Context);
            userId = p_LoginUser.UserID.ToString();
            DataSet ds = bll_task.GetList(" F_INSTANCEID='" + instanceId + "'and F_LoseFlag='0'" + " and F_OwnerId='" + userId + "'");
            if (ds.Tables[0].Rows.Count > 0)
            {
                taskId = ds.Tables[0].Rows[0]["F_TASKID"].ToString();
                taskobj = GetObj(Convert.ToInt32(taskId));
                orderstate = ds.Tables[0].Rows[0]["F_WORKORDERSTATEID"].ToString();
                if (taskobj != null)
                {
                    InitEngine(taskobj.F_OPTBTN);
                }
            }
            //InitEngine(taskobj.F_OPTBTN);

            AddCancelBtn();
        }

        #region 初始化任务信息

        private Model.T_Wo_WorkOrderTask GetObj(int taskid)
        {
            Model.T_Wo_WorkOrderTask obj = new Model.T_Wo_WorkOrderTask();

            DataTable dt = new DataTable();
            try
            {
                dt = new BLL.T_Wo_WorkOrderTask().GetList("F_TASKID=" + taskid.ToString() + "").Tables[0];
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["F_AssignParticipator"].ToString() != "null")
                    {
                        assOpt = dt.Rows[0]["F_AssignParticipator"].ToString();
                    }

                    if (dt.Rows[0]["F_WORKORDERSTATEID"] != null && dt.Rows[0]["F_WORKORDERSTATEID"].ToString() != "")
                    {
                        obj.F_WORKORDERSTATEID = int.Parse(dt.Rows[0]["F_WORKORDERSTATEID"].ToString());
                        txtF_WORKORDERSTATEID.Value = dt.Rows[0]["F_WORKORDERSTATEID"].ToString();
                    }

                    if (dt.Rows[0]["F_OPTBTN"] != null)
                    {
                        obj.F_OPTBTN = dt.Rows[0]["F_OPTBTN"].ToString();
                    }
                    if (dt.Rows[0]["F_TASKFLAG"] != null)
                    {
                        obj.F_TASKFLAG = int.Parse(dt.Rows[0]["F_TASKFLAG"].ToString());
                    }
                    if (dt.Rows[0]["f_planfinishtime"] != null && dt.Rows[0]["f_planfinishtime"].ToString() != "")
                    {
                        time = Convert.ToDateTime(dt.Rows[0]["f_planfinishtime"].ToString());
                    }
                    if (dt.Rows[0]["F_OWNERID"] != null && dt.Rows[0]["F_OWNERID"].ToString() != "")
                    {
                        obj.F_OWNERID = int.Parse(dt.Rows[0]["F_OWNERID"].ToString());
                    }
                    if (dt.Rows[0]["F_INSTANCEID"] != null)
                    {
                        obj.F_INSTANCEID = int.Parse(dt.Rows[0]["F_INSTANCEID"].ToString());

                        txtF_INSTANCEID.Value = dt.Rows[0]["F_INSTANCEID"].ToString();

                    }
                }
            }
            catch
            { }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }

            return obj;
        }

        #endregion
        #region 添加取消按钮

        private void AddCancelBtn()
        {
            System.Web.UI.HtmlControls.HtmlGenericControl btncancel = new System.Web.UI.HtmlControls.HtmlGenericControl("a");
            btncancel.ID = "btncancel";
            btncancel.Attributes.Add("class", "btnSearch");

            btncancel.Attributes.Add("onclick", "parent.CloseThis()");
            btncancel.InnerText = "取消";

            tdbtn.Controls.Add(btncancel);
        }

        #endregion

        #region 初始化工作流引擎

        private void InitEngine(string optbtn)
        {
            wosBusineSupporter = new WOSBusineSupporter.WOSBusineSupporter();
            wosBusineSupporter.ConnectionString = connStr;
            /**/
            //Oracle数据库存储方式
            MSSQLDBWorkflowInstanceFactory instanceFactory = new MSSQLDBWorkflowInstanceFactory();
            instanceFactory.ConnectionString = connStr;
            MSSQLDBPersistentServer persistenServer = new MSSQLDBPersistentServer();
            persistenServer.ConnectionString = connStr;
            engine = new SimpleWFEngine(wosBusineSupporter, persistenServer, instanceFactory);
            MSSQLDBWorkflowTypeInfoSupporter sup = new MSSQLDBWorkflowTypeInfoSupporter();
            sup.ConnectionString = connStr;
            #region 顺序操作

            if (optbtn != "")
            {
                optbtn += "#@!";
                optbtn = optbtn.Replace(",#@!", "").Replace("#@!", "");
                DataTable dt = new DataTable();
                try
                {
                    dt = new BLL.T_Wo_WorkOrderButton().GetList(" F_BUTTONID in (" + optbtn + ") ").Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        int idcount = 0;
                        foreach (DataRow dr in dt.Rows)
                        {
                            LinkButton runSavebtn = new LinkButton();
                            runSavebtn.ID = "runSavebtn" + idcount.ToString();
                            runSavebtn.Attributes.Add("class", "btnSearch");
                            if (dr["F_Name"].ToString().Trim() != "结单" && dr["F_BUTTONID"].ToString() != "12")
                            {
                                runSavebtn.OnClientClick = "return checkUserDataAddOther();";
                            }
                            else
                            {
                                runSavebtn.OnClientClick = "return Confirm('"+idcount.ToString()+"');";
                            }
                            runSavebtn.Text = dr["F_Name"].ToString().Trim();
                            runSavebtn.CommandArgument = dr["F_ButtonId"].ToString();
                            runSavebtn.Click+=new EventHandler(runSavebtn_Click);

                            tdbtn.Controls.Add(runSavebtn);

                            //添加空格间距
                            System.Web.UI.HtmlControls.HtmlGenericControl spannull = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
                            spannull.ID = "btnnull" + idcount.ToString();
                            spannull.InnerHtml = "&nbsp;&nbsp;";
                            tdbtn.Controls.Add(spannull);
                            idcount++;
                        }
                    }
                }
                catch
                {
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }

            }

            #endregion
        }

        #endregion
        protected void runSavebtn_Click(object sender, EventArgs e)
        {
            Common.LoginUser user = new Common.LoginUser(this.Context);
            LinkButton btn = (LinkButton)sender;
            try 
            {
                string pandaun = "zhipai";
                if (btn.CommandArgument == "12" || btn.Text == "结单")
                {
                    pandaun = "jiedan";
                }
                //保存表单信息
                bool rbl = SaveForm(pandaun);
                if (rbl)
                {
                    //顺序操作事件(未能指派)
                    string errinfo = "";
                    string dealContent = "";//
                    WorkflowOprErr bl;
                    int optOwnerId = taskobj.F_OWNERID;
                    if (btn.CommandArgument == "12" || btn.Text == "结单")
                    {
                        dealContent = "(" + user.UserName + ")执行了" + btn.Text.Trim() + "操作,描述:" + F_CONTENT.Text + "。";
                        bl = engine.RunOpr(txtF_INSTANCEID.Value, optOwnerId.ToString(), txtF_WORKORDERSTATEID.Value, btn.CommandArgument, null, dealContent, out errinfo);
                    }
                    //else if (btn.CommandArgument == "19" || btn.Text == "流转指派")
                    //{
                    //    dealContent = "(" + user.UserName + ")流转指派为:" + hfSQDXName.Value + ",指派描述:" + F_CONTENT.Text;
                    //    if (orderstate == "4")
                    //    {
                    //        bl = engine.RunOpr(txtF_INSTANCEID.Value, optOwnerId.ToString(), txtF_WORKORDERSTATEID.Value, btn.CommandArgument, GetAssignParticipatorList("13"), dealContent, out errinfo);
                    //    }
                    //    else
                    //    {
                    //        bl = engine.RunOpr(txtF_INSTANCEID.Value, optOwnerId.ToString(), txtF_WORKORDERSTATEID.Value, btn.CommandArgument, GetAssignParticipatorList("4"), dealContent, out errinfo);
                    //    }
                    //    if (bl.ToString() == "OK")
                    //    {
                    //        SaveHistoryInfo();
                    //    }
                    //}
                    else
                    {
                        dealContent = "(" + user.UserName + ")指派人员为:" + hfSQDXName.Value + ",指派描述:" + F_CONTENT.Text;
                        bl = engine.RunOpr(txtF_INSTANCEID.Value, optOwnerId.ToString(), txtF_WORKORDERSTATEID.Value, btn.CommandArgument, GetAssignParticipatorList(), dealContent, out errinfo);
                        if (bl.ToString() == "OK")
                        {
                            SaveHistoryInfo();
                        }
                    }
                    if (bl.ToString() == "OK")
                    {
                        InsertOptLogs(0, 0, "操作成功！orderassign.aspx页面" + dealContent, 0);
                        MessageBoxToWindow("保存成功", "保存提示！", "success");
                    }
                    else
                    {
                        InsertOptLogs(0, 0, "操作失败！orderassign.aspx页面" + "(" + user.UserName + ")执行了" + btn.Text.Trim() + "操作,描述:" + F_CONTENT.Text + "。", 1);
                        MessageBoxToWindow("保存失败", "保存提示！", "error");
                    }
                }
            }
            catch (Exception e1)
            {
                InsertOptLogs(0, 0, "操作异常！orderassign.aspx页面" + "(" + user.UserName + ")执行了" + btn.Text.Trim() + "操作,描述:" + F_CONTENT.Text + "。异常信息:" + e1.ToString(), 2);
                MessageBoxToWindow("保存失败", "保存提示！", "error");
            }
        }

        private AssignParticipator[] GetAssignParticipatorList()
        {

            if (assOpt != "")
            {
                AssignParticipator[] asslist = new Web.tools.ParseWorkFlowTask().ParseAssignParticipatorOpr(assOpt);
                foreach (AssignParticipator ass in asslist)
                {

                    ParticipatorInfo partinfo = new ParticipatorInfo();
                    List<Model.T_Sys_UserAccount> list = new List<Model.T_Sys_UserAccount>();
                    list = (new BLL.T_Sys_UserAccount()).GetModelList(" F_UserId=" + hfChecked.Value + "");
                    UserInfo[] userlist = new UserInfo[list.Count];
                    for (int i = 0; i < userlist.Length; i++)
                    {
                        UserInfo user = new UserInfo();
                        user.ID = list[i].F_UserId.ToString();
                        user.Name = list[i].F_UserName;
                        userlist[i] = user;
                    }

                    partinfo.UserList = userlist;

                    ass.ParticipatorInfo = new AssembleWorkFlowTask().AssembleParticipator(partinfo).InnerXml;

                }
                return asslist;
            }
            else
            {
                return null;
            }
        }

        private AssignParticipator[] GetAssignParticipatorList(string btn)
        {

            if (assOpt != "")
            {
                AssignParticipator[] ass1 = new AssignParticipator[1];
                AssignParticipator[] asslist = new Web.tools.ParseWorkFlowTask().ParseAssignParticipatorOpr(assOpt);
                foreach (AssignParticipator ass in asslist)
                {
                    if (ass.NodeID == btn)
                    {
                        ParticipatorInfo partinfo = new ParticipatorInfo();
                        List<Model.T_Sys_UserAccount> list = new List<Model.T_Sys_UserAccount>();
                        //list = (new BLL.T_Sys_UserAccount()).GetModelList(" F_UserId in('" + hfSQDX.Value.Replace(",", "','") + "')");
                        list = (new BLL.T_Sys_UserAccount()).GetModelList(" F_UserId=" + hfChecked.Value + "");
                        UserInfo[] userlist = new UserInfo[list.Count];
                        for (int i = 0; i < userlist.Length; i++)
                        {
                            UserInfo user = new UserInfo();
                            user.ID = list[i].F_UserId.ToString();
                            user.Name = list[i].F_UserName;
                            userlist[i] = user;
                        }

                        partinfo.UserList = userlist;

                        ass.ParticipatorInfo = new AssembleWorkFlowTask().AssembleParticipator(partinfo).InnerXml;
                        ass1[0] = ass;
                    }
                }
                return ass1;
            }
            else
            {
                return null;
            }
        }
        private bool SaveForm(string pandaun)
        {
            Common.LoginUser user = new Common.LoginUser(this.Context);
            bool bl = false;
            if (pandaun == "zhipai")
            {
                Model.T_Wo_WorkOrderConstructor modelConstructor = new Model.T_Wo_WorkOrderConstructor();
                BLL.T_Wo_WorkOrderConstructor bll_Constructoradd = new BLL.T_Wo_WorkOrderConstructor();
                bll_Constructoradd.DeleteOrderId(Convert.ToInt32(workorderid));
                modelConstructor.F_WORKORDERID = Convert.ToInt32(workorderid);//工单ID
                if (hfSQDX.Value.Contains(","))
                {
                    string[] str = hfSQDX.Value.Split(',');
                    for (int i = 0; i < str.Length; i++)
                    {
                        modelConstructor.F_USERID = Convert.ToInt32(str[i]);
                        if (str[i] == hfChecked.Value)
                        {
                            modelConstructor.F_ISMAIN = 1;
                        }
                        else
                        {
                            modelConstructor.F_ISMAIN = 0;
                        }
                        bll_Constructoradd.Add(modelConstructor);
                        SetSMS(str[i]);
                    }
                }
                else
                {
                    modelConstructor.F_USERID = Convert.ToInt32(hfChecked.Value);
                    modelConstructor.F_ISMAIN = 1;
                    bll_Constructoradd.Add(modelConstructor);
                    SetSMS(hfChecked.Value);
                }
            }

            Model.T_Wo_WorkOrderTaskInfo model = new Model.T_Wo_WorkOrderTaskInfo();
            if (taskId != "")
            {
                model.F_TASKID = Convert.ToInt32(taskId);//任务ID
            }
            else { model.F_TASKID = 0; }
            model.F_WORKORDERID = Convert.ToInt32(workorderid);//工单ID
            model.F_OPTBY = user.UserID;//操作人ID
            model.F_ARRASSIGNUSER = hfSQDX.Value;//指派人员
            model.F_ASSIGNTYPE =  1;//指派类型
            model.F_ASSIGNDES = F_CONTENT.Text;//指派描述
            model.F_OPTDATE = DateTime.Now;
            BLL.T_Wo_WorkOrderTaskInfo bll_add = new BLL.T_Wo_WorkOrderTaskInfo();
            if (bll_add.Add(model) > 0)
            { bl = true; }
            else { return false; }

            return bl;
        }

        private void SaveHistoryInfo()
        {
            try
            {
                Common.LoginUser user = new Common.LoginUser(this.Context);
                Model.T_Wo_WorkOrderHistoryInfo modelHistoryInfo = new Model.T_Wo_WorkOrderHistoryInfo();
                string sql = "select * from T_Wo_WorkOrderHistory where F_INSTANCEID=" + txtF_INSTANCEID.Value + " and F_OPTUSERID=" + user.UserID + " order by F_HISTORYID desc";
                DataTable dt = DbHelperSQL.Query(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    modelHistoryInfo.F_HISTORYID = Convert.ToInt32(dt.Rows[0]["F_HISTORYID"]);
                }
                modelHistoryInfo.F_OPTUSERID = user.UserID;
                modelHistoryInfo.F_REMARK = F_CONTENT.Text.Trim();
                modelHistoryInfo.F_INSTANCEID = Convert.ToInt32(txtF_INSTANCEID.Value);
                modelHistoryInfo.F_OPTDATE = DateTime.Now;
                modelHistoryInfo.F_ESTIMATED = F_ESTIMATED.Text.Trim();
                if (RadioButton1.Checked == true)
                {
                    modelHistoryInfo.F_KNOWLEDGE = 0;
                }
                else
                { modelHistoryInfo.F_KNOWLEDGE = 1; }
                BLL.T_Wo_WorkOrderHistoryInfo bll_addHistory = new BLL.T_Wo_WorkOrderHistoryInfo();
                bll_addHistory.Add(modelHistoryInfo);
            }
            catch { }

        }
        /// <summary>
        /// 绑定初始值
        /// </summary>
        public void GetModelValue(string workorderid)
        {
            Common.LoginUser user = new Common.LoginUser(this.Context);
            F_USERNAME.InnerHtml = user.UserName;
            string sql = "select * from V_WorkOrderBase where F_WORKORDERID=" + workorderid + "";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            System.Collections.Generic.List<Model.T_Wo_WorkOrderBase> baseModel = new BLL.T_Wo_WorkOrderBase().DataTableToList(dt);
            if (baseModel.Count > 0)
            {
                if (baseModel[0].F_INSTANCEID != null)
                {
                    instanceId = baseModel[0].F_INSTANCEID.ToString();
                }
                if (baseModel[0].F_Name != null)
                {
                    F_Name.InnerHtml = baseModel[0].F_Name.ToString();
                }
                if (baseModel[0].F_TypeName != null)
                {
                    F_TypeName.InnerHtml = baseModel[0].F_TypeName.ToString();
                }
                if (baseModel[0].F_UserAccountName != null)
                {
                    F_UserAccountName.InnerHtml = baseModel[0].F_UserAccountName.ToString();
                }
                string sql1 = "select * from T_Wo_WorkOrderHistoryInfo where F_INSTANCEID=" + instanceId + " and F_KNOWLEDGE is not null order by ID desc";
                DataTable dt1 = DbHelperSQL.Query(sql1).Tables[0];
                System.Collections.Generic.List<Model.T_Wo_WorkOrderHistoryInfo> Model = new BLL.T_Wo_WorkOrderHistoryInfo().DataTableToList(dt1);
                if (Model.Count > 0)
                {
                    if (Model[0].F_KNOWLEDGE != null)
                    {
                        if (Model[0].F_KNOWLEDGE.ToString() == "0")
                        {
                            RadioButton1.Checked = true;
                            RadioButton2.Checked = false;
                        }
                        else
                        {
                            RadioButton1.Checked = false;
                            RadioButton2.Checked = true;
                        }
                    }
                }
            }
        }

        #region 发送短信
        public void SetSMS(string userid)
        {
            try
            {
                Model.T_SMS_SendSMSTask model = new Model.T_SMS_SendSMSTask();
                BLL.T_SMS_SendSMSTask bll = new BLL.T_SMS_SendSMSTask();
                DataTable dt1 = new BLL.T_Sys_UserAccount().GetList(" F_UserId=" + userid + "").Tables[0];
                if (dt1.Rows.Count > 0)
                {
                    model.TelNum = dt1.Rows[0]["F_Mobile"].ToString();
                    model.F_Name = dt1.Rows[0]["F_UserName"].ToString();
                }
                string sql = "select * from V_WorkOrderBase where F_WORKORDERID=" + workorderid + "";
                DataTable dt = DbHelperSQL.Query(sql).Tables[0];
                System.Collections.Generic.List<Model.T_Wo_WorkOrderBase> baseModel = new BLL.T_Wo_WorkOrderBase().DataTableToList(dt);
                if (baseModel.Count > 0)
                {
                    if (baseModel[0].F_CUSTOMERNAME != null)
                    {
                        model.Content = baseModel[0].F_CUSTOMERNAME.ToString();
                    }
                    else 
                    {
                        model.Content = "客户单位未知";
                    }
                    if (baseModel[0].F_REPAIRMANNAME != null)
                    {
                        model.Content += "，联系人：" + baseModel[0].F_REPAIRMANNAME.ToString();
                    }
                    else 
                    {
                        model.Content += "，联系人：未知" ;
                    }
                    if (baseModel[0].F_REPAIRMANPHONE != null)
                    {
                        model.Content += ",电话：" + baseModel[0].F_REPAIRMANPHONE.ToString();
                    }
                    else 
                    {
                        model.Content += ",电话：未知" ;
                    }
                    if (baseModel[0].F_CONTENT != null)
                    {
                        model.Content += ",来电内容：" + baseModel[0].F_CONTENT.ToString() + "。";
                    }
                    else
                    {
                        model.Content += ",来电内容：为空。";
                    }
                }
                model.SendTime = DateTime.Now;
                model.LastSentTime = DateTime.Now;
                model.CommitTime = DateTime.Now;
                DataTable dt2 = new BLL.T_Sys_UserAccount().GetList(" F_RoleId in (SELECT F_RoleId FROM T_Sys_RoleFunction   where F_FunctionId in(select F_FunctionId from T_Sys_ModuleFunctions where F_FunctionCode='jsdx')) and F_UserId=" + userid + "").Tables[0];
                if (dt2.Rows.Count > 0)
                {
                    bll.Add(model);
                    model.Content = "您的报修工单已经派单给:" + model.F_Name + ",手机:" + model.TelNum + "请需要时和其联系以便了解进度";
                    string phone = "0000";
                    if (baseModel[0].F_REPAIRMANPHONE != null)
                    {
                        phone = baseModel[0].F_REPAIRMANPHONE.ToString();
                        model.TelNum = phone;
                    }
                    if (baseModel[0].F_REPAIRMANNAME != null)
                    {
                        model.F_Name = baseModel[0].F_REPAIRMANNAME.ToString();
                    }
                    if (phone.Length > 10)
                    {
                        if (phone.Substring(0, 2) == "01" || phone.Substring(0, 1) == "1")
                        {
                            bll.Add(model);
                        }
                    }
                }
            }
            catch { }
        }
        #endregion

        #region 弹出对话框
        /// <summary>
        /// 弹出对话框
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        public void MessageBoxToWindow(string title, string content, string type)
        {
            string script = "";
            switch (type)
            {
                case "error"://失败
                    type = "error";
                    script = "<script type='text/javascript'>  parent.$.ligerDialog.alert('" + title + "','" + content + "','" + type + "');</script>";
                    break;
                case "success"://成功
                    type = "info";
                    script = "<script type='text/javascript'> parent.$.ligerDialog.alert('" + title + "','" + content + "','" + type + "',parent.Close);</script>";
                    break;
                case "catch"://异常
                    type = "warning";
                    script = "<script type='text/javascript'>  parent.$.ligerDialog.alert('" + title + "','" + content + "','" + type + "');</script>";
                    break;
                default:
                    type = "question";
                    break;
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", script);
        }
        #endregion
    }
}