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 orderhuifu : BasePage
    {
        SimpleWFEngine engine;
        WOSBusineSupporter.WOSBusineSupporter wosBusineSupporter;
        string connStr = DBUtility.DbHelperSQL.connectionString;
        Model.T_Wo_WorkOrderTask taskobj;
        string assOpt = "";
        string instanceId = "";
        string userId = "0";
        int creatUser = 0;
        string taskId = "";
        string workorderid = "0";
        DateTime time = DateTime.Now;
        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));
                if (taskobj != null)
                {
                    InitEngine(taskobj.F_OPTBTN);
                }
            }
            #region 初始化工作流



            #endregion
            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
        /// <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_CREATEBY != null)
                {
                    creatUser = Convert.ToInt32(baseModel[0].F_CREATEBY);
                }
                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();
                }

            }
        }
        #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")
                            {

                            }
                            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
            {
                //保存表单信息
                bool rbl = SaveForm();
                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 == "13" || btn.Text == "重新指派")
                    {
                        dealContent = "(" + user.UserName + ")重新指派,指派描述:" + F_CONTENT.Text;//
                        bl = engine.RunOpr(txtF_INSTANCEID.Value, optOwnerId.ToString(), txtF_WORKORDERSTATEID.Value, btn.CommandArgument, GetAssignParticipatorListCXZP(), dealContent, out errinfo);
                    }
                    else
                    {
                        dealContent = "(" + user.UserName + ")回复内容:" + F_CONTENT.Text;
                        bl = engine.RunOpr(txtF_INSTANCEID.Value, optOwnerId.ToString(), txtF_WORKORDERSTATEID.Value, btn.CommandArgument, null, dealContent, out errinfo);
                    }
                    if (bl.ToString() == "OK")
                    {
                        SaveHistoryInfo();
                        InsertOptLogs(0, 0, "操作成功！orderhuifu.aspx页面" + dealContent, 0);
                        MessageBoxToWindow("保存成功", "保存提示！", "success");
                    }
                    else
                    {
                        InsertOptLogs(0, 0, "操作失败！orderhuifu.aspx页面" + "(" + user.UserName + ")执行了" + btn.Text.Trim() + "操作,描述:" + F_CONTENT.Text + "。", 1);
                        MessageBoxToWindow("保存失败", "保存提示！", "error");
                    }
                }
            }
            catch (Exception e1)
            {
                InsertOptLogs(0, 0, "操作异常！orderhuifu.aspx页面" + "(" + user.UserName + ")执行了" + btn.Text.Trim() + "操作,描述:" + F_CONTENT.Text + "。异常信息:" + e1.ToString(), 2);
                MessageBoxToWindow("保存失败", "保存提示！", "error");
            }
        }
        private AssignParticipator[] GetAssignParticipatorListCXZP()
        {
            AssignParticipator[] arr = new AssignParticipator[1];
            arr[0] = new AssignParticipator();
            arr[0].NodeID = "4";
            arr[0].NodeName = "待指派";
            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=(SELECT top 1 F_OPTUSERID FROM T_Wo_WorkOrderHistory where F_WORKORDERSTATEID in(13,4) and F_INSTANCEID=" + txtF_INSTANCEID.Value + "  order by F_HISTORYID desc)");
            if (list.Count == 0)
            {
                list = (new BLL.T_Sys_UserAccount()).GetModelList(" F_UserId=" + creatUser + " ");
            }
            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;

            arr[0].ParticipatorInfo = new AssembleWorkFlowTask().AssembleParticipator(partinfo).InnerXml;

            return arr;

        }
        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_CUSTOMERSCORE = F_CUSTOMERSCORE.Text.Trim();
                modelHistoryInfo.F_CUSTOMEROPINION = F_CUSTOMEROPINION.Text.Trim();
                modelHistoryInfo.F_VISITTYPE = F_VISITTYPE.Text.Trim();
                modelHistoryInfo.F_SOLVE = F_SOLVE.Text.Trim();
                BLL.T_Wo_WorkOrderHistoryInfo bll_addHistory = new BLL.T_Wo_WorkOrderHistoryInfo();
                bll_addHistory.Add(modelHistoryInfo);
            }
            catch { }

        }
        private bool SaveForm()
        {
            Common.LoginUser user = new Common.LoginUser(this.Context);
            bool bl = true;
            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_REPLYINFO = 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 { bl = false; }

            return bl;
        }
        #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
    }
}