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.Common;
using HySoft.Workflow.WFEngine;
using WOSBusineSupporter;
using HySoft.BaseCallCenter.Web.workordermanage.workorder;
using HySoft.DBUtility;

namespace HySoft.BaseCallCenter.Web.telmanage
{
    public partial class callinopt : System.Web.UI.Page
    {
        string phone = "";
        string callid = "";
        string zxflowid = "7";
        string bxflowid = "6";
        string tsflowid = "5";
        string assOpt = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 生成流程操作

            InitEngine();

            #endregion
            if (!IsPostBack)
            {
                #region 获取用户信息
                try
                {
                    LoginUser p_LoginUser = new LoginUser(this.Context);
                    hfUserId.Value = p_LoginUser.UserID.ToString();
                }
                catch { }

                #endregion
                #region 参数获取
                if (!string.IsNullOrEmpty(Request.QueryString["phone"]))
                {
                    phone = Request.QueryString["phone"].ToString().Trim();//来电电话 
                    string oldphone = phone;//2015-4-10  张高炯
                    phone = DealPhone(phone);
                    txtLaiDian.InnerHtml = phone;
                    hfPhone.Value = oldphone;

                    txtTsPhone.Text = phone;

                    #region 来电归属地查询

                    string location = "";
                    //来电归属地查询
                    if (phone.Trim().Length == 11 && phone.Substring(0, 1) != "0")
                    {
                        location = GetPhoneLocation(phone, true);
                    }
                    else
                    {
                        location = GetPhoneLocation(phone, false);
                    }
                    txtLaiDian.InnerText = phone + " " + location;

                    #endregion

                    #region 根据电话获取客户信息

                    getCustomerInfoByPhone(phone);

                    #endregion
                }
                if (!string.IsNullOrEmpty(Request.QueryString["callid"]))
                {
                    callid = Request.QueryString["callid"].ToString().Trim();//呼入Id 
                    hfCallId.Value = callid;
                    GetTelRecord(callid);
                }
                #endregion
            }
        }

        #region 初始化工作流引擎

        private void InitEngine()
        {
            wosBusineSupporter = new WOSBusineSupporter.WOSBusineSupporter();
            wosBusineSupporter.ConnectionString = connStr;
            /**/
            //SQL数据库存储方式
            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;

            runOprs = null;
            sup.GetWorkflowTypeInfo(tsflowid,
                out nodeID, out nodeType, out nodeName, out formInfo, out enablcRepeal, out enablcRepealLock, out runOprs, out rollBackOprs, out assignParticipatorArray);

            #region 投诉操作

            if (runOprs != null)
            {

                int idcount = 0;
                foreach (BusineOpr runopr in runOprs)
                {
                    //zxoptid = runopr.ID;
                    LinkButton runSavebtn = new LinkButton();
                    runSavebtn.ID = "runSavebtnts" + idcount.ToString();
                    runSavebtn.Attributes.Add("class", "btnSubmit");
                    runSavebtn.OnClientClick = "return validate('" + runopr.ID.Trim() + "')";
                    runSavebtn.Text = runopr.Name.Trim();
                    runSavebtn.CommandArgument = runopr.ID + "_" + nodeID;
                    runSavebtn.Height = 23;
                    runSavebtn.Click += new EventHandler(btnSubmit_Click);

                    divOpt0.Controls.Add(runSavebtn);

                    //添加空格间距
                    System.Web.UI.HtmlControls.HtmlGenericControl spannull = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
                    spannull.ID = "btnnullts" + idcount.ToString();
                    spannull.InnerText = "  ";
                    divOpt0.Controls.Add(spannull);
                    idcount++;
                }

            }

            #endregion
        }

        #endregion

        #region 来电归属地查询
        public string GetPhoneLocation(string phoneNumber, bool isPhone)
        {
            string location = "未知";
            try
            {
                //如果是手机号码
                if (isPhone)
                {
                    BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                    Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModel(phoneNumber.Substring(0, 7));
                    return mobileModel != null ? (mobileModel.F_CityDes + mobileModel.F_CardDes) : location;
                }
                else//如果是电话号码 
                {
                    BLL.T_Sys_TelTitleData numbBll = new BLL.T_Sys_TelTitleData();
                    List<Model.T_Sys_TelTitleData> mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + phoneNumber.Substring(0, 4) + "'");
                    if (mobileModel == null || mobileModel.Count <= 0)
                        mobileModel = numbBll.GetModelList(" 1=1 and F_KeyPhoneNum='" + phoneNumber.Substring(0, 3) + "'");
                    return mobileModel.Count > 0 ? mobileModel[0].F_TitleName : location;
                }
            }
            catch (System.Exception ex)
            {
                return location;
            }


        }
        #endregion

        #region 获取通话记录信息

        private string GetTelRecord(string callid)
        {
            string res = "0";
            try
            {
                Model.T_Call_CallRecords model = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                if (model != null)
                {
                    res = model.CallRecordsId.ToString();
                    hfBusinessType.Value = model.BusinessType.ToString().Trim();
                }
            }
            catch
            {
            }
            return res;
        }

        #endregion

        #region 根据来电号码获取客户信息

        private string getCustomerInfoByPhone(string tel)
        {
            string res = "";
            DataTable dt = new DataTable();
            DataTable dtc = new DataTable();
            try
            {
                if (tel != "")
                {
                    //先查联系人表存在联系人记录
                    dt = new BLL.T_Cus_ContactPerson().GetList(" F_Telephone like '%" + tel + "%' or F_Mobile like '%" + tel + "%' ").Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        res = getCustomerInfoById(dt.Rows[0]["F_CustomerId"].ToString().Trim());

                        //投诉
                        txtTsName.Text = dt.Rows[0]["F_Name"].ToString().Trim();
                    }
                    else
                    {
                        dtc = new BLL.T_Cus_CustomerBase().GetList(" F_Telephone like '%" + tel + "%' or F_Mobile like '%" + tel + "%' or F_ChargeTelephone like '%" + tel + "%' ").Tables[0];

                        if (dtc.Rows.Count > 0)
                        {
                            res = getCustomerInfoById(dtc.Rows[0]["F_CustomerId"].ToString().Trim());
                        }
                        else 
                        {
                            getUserAccount(tel);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                res = "";
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
                dtc.Clear();
                dtc.Dispose();
            }
            return res;
        }

        private string getCustomerInfoById(string id)
        {
            string res = "";
            Model.T_Cus_CustomerBase model = new BLL.T_Cus_CustomerBase().GetModel(Convert.ToInt32(id));
            if (model != null)
            {
                hiddCustomerId.Value = model.F_CustomerId.ToString();
                txtCustomerName.Text = model.F_CustomerName;
                divCustomerCode.InnerHtml = "<a href=\"javascript:void(null)\" target=\"_self\" onclick=\"ShowCustomer('" + model.F_CustomerId.ToString() + "');\">" + model.F_CustomerCode + "</a>";
                hiddSeriveDeptId.Value = model.F_ServiceDeptID.ToString();
                hiddProvinceId.Value = model.F_RegionId.ToString();
                hiddCityId.Value = model.F_CityID.ToString();

                hiddTelephone.Value = model.F_Telephone;
                hiddMobile.Value = model.F_Mobile;
                hiddChargeTelephone.Value = model.F_ChargeTelephone;

                drpServiceDept.Text = model.F_ServiceDept;
                drpProvince.Text = model.F_Province;
                drpCity.Text = model.F_City;


                drpTelephone.Text = model.F_Telephone;
                drpMobile.Text = model.F_Mobile;
                drpChargeTelephone.Text = model.F_ChargeTelephone;

                //投诉
                txtTsName.Text = model.F_CustomerName;
                txtTsPhone.Text = phone;

            }
            return res;
        }

        #endregion

        #region 根据来电号码获取系统用户信息
        private void getUserAccount(string tel)
        {
            try 
            {
                DataTable dtUser = new BLL.T_Sys_UserAccount().GetListView(" F_Telephone like '%" + tel + "%' or F_Mobile like '%" + tel + "%' or F_HomePhone like '%" + tel + "%' ").Tables[0];
                if (dtUser.Rows.Count > 0)
                {
                    //投诉
                    txtTsName.Text = dtUser.Rows[0]["F_UserName"].ToString().Trim();
                    txtLaiDian.InnerText = tel + " " + dtUser.Rows[0]["F_DeptName"].ToString().Trim();
                }
            }
            catch { }
        }
        #endregion

        SimpleWFEngine engine;
        WOSBusineSupporter.WOSBusineSupporter wosBusineSupporter;
        string connStr = DBUtility.DbHelperSQL.connectionString;
        string instanceID = "0";
        string nodeID = "0";
        BusineTaskType nodeType;
        string nodeName = "";
        string formInfo = "";
        bool enablcRepeal;
        bool enablcRepealLock;
        BusineOpr[] runOprs = null;
        BusineOpr[] rollBackOprs;
        AssignParticipator[] assignParticipatorArray;
        static string typeid = "0";
        static string formid = "0";
        static string flowid = "0";

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            #region 设置黑名单

            try
            {
                if (cbBlack.Checked && !string.IsNullOrEmpty(txtBlackTime.Text.Trim()))
                {
                    string blackTime = txtBlackTime.Text.Trim();
                    AddBlackPhone(hfPhone.Value, hfCallId.Value, blackTime);
                }
            }
            catch (Exception ex)
            {
            }

            #endregion

            #region 保存客户信息

            try
            {
                if (hiddCustomerId.Value == "" || hiddCustomerId.Value == "0")
                {
                    if (txtCustomerName.Text.Trim() != "")
                    {
                        //添加客户
                        int id = new BLL.T_Cus_CustomerBase().Add(GetCustomerModel());
                        if (id > 0)
                        {
                            hiddCustomerId.Value = id.ToString();
                        }
                    }
                }
                else
                {
                    //修改客户
                    new BLL.T_Cus_CustomerBase().Update(GetCustomerModel());
                }
            }
            catch (Exception ex)
            {
            }

            #endregion

            #region 保存工单

            string errorInfo = "";
            try
            {
                flowid = tsflowid;
                typeid = "3";

                WorkflowOprErr errbl = engine.CreateWorkflowInstance(flowid, hfUserId.Value.Trim(), out instanceID, out errorInfo);
                if (errbl == WorkflowOprErr.OK)
                {
                    //提交保存工单
                    int f_instanceid = Convert.ToInt32(instanceID);
                    int workorderid=0;
                    bool bl = SubmitOSubmit(f_instanceid, flowid, hfTab.Value.Trim(),out workorderid);
                    try
                    {
                        Model.T_Call_WorkOrder modelorder = new Model.T_Call_WorkOrder();
                        modelorder.CallId = callid;
                        modelorder.F_WORKORDERID = workorderid;
                        modelorder.F_WORKORDERSTATEID = 12;
                        new BLL.T_Call_WorkOrder().Add(modelorder);
                    }
                    catch { }

                    if (bl)
                    {
                        LinkButton btn = (LinkButton)sender;
                        string arrid = btn.CommandArgument;
                        string optid = "6";
                        if (arrid != "")
                        {
                            nodeID = arrid.Split('_')[1];
                            optid = arrid.Split('_')[0];
                        }
                        //判断操作
                        if (optid == "18" || optid == "19")
                        {
                            string optnodeid = "";
                            string optnodename = "";
                            if (optid == "18")
                            {
                                optnodeid = "6";
                                optnodename = "待接单";
                                SaveConsInfo(workorderid.ToString(), hiddJDUser.Value);
                            }
                            if (optid == "19")
                            {
                                optnodeid = "4";
                                optnodename = "待指派";
                            }
                            WorkflowOprErr bRet = engine.RunOpr(instanceID, hfUserId.Value.Trim(), nodeID, optid, GetAssignParticipatorList(hiddJDUser.Value, instanceID), "工单操作：" + btn.Text, out errorInfo);
                            //WorkflowOprErr bRet = engine.RunOpr(instanceID, hfUserId.Value.Trim(), nodeID, optid, GetAssignParticipatorList(hiddJDUser.Value, optnodeid, optnodename), "工单操作：" + btn.Text, out errorInfo);
                            if (bRet.ToString() == "OK")
                            {
                                SaveHistoryInfo();
                            }
                        }
                        else
                        {
                            WorkflowOprErr bRet = engine.RunOpr(instanceID, hfUserId.Value.Trim(), nodeID, optid, null, "工单操作：" + btn.Text, out errorInfo);
                            SaveHistoryInfo();
                        }

                        MessageBoxToWindow("保存提示", "保存成功！", "success");
                        //ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script type='text/javascript'>TabCloseById('callin_" + callid + phone + "');</script>");
                    }
                    else
                    {
                        //InsertOptLogs("", "添加工单失败!", 1);
                        MessageBoxToWindow("保存提示", "新增失败！", "error");
                    }
                }
                else
                {
                    MessageBoxToWindow("保存提示", "创建工作流实例失败" + errbl.ToString(), "error");
                }
            }
            catch (Exception ex)
            {
                //保存工单失败
                MessageBoxToWindow("提示", "异常提示！" + ex.Message, "catch");
            }
            #endregion
        }

        private AssignParticipator[] GetAssignParticipatorList(string userid, string instanceID)
        {
            Model.T_Wo_WorkOrderTask obj = new Model.T_Wo_WorkOrderTask();

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

            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=" + userid.Trim() + "");
                    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 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=" + instanceID + " 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_INSTANCEID = Convert.ToInt32(instanceID);
                modelHistoryInfo.F_OPTDATE = DateTime.Now;
                modelHistoryInfo.F_EXAMINETYPE = F_EXAMINETYPE.Text.Trim();

                BLL.T_Wo_WorkOrderHistoryInfo bll_addHistory = new BLL.T_Wo_WorkOrderHistoryInfo();
                bll_addHistory.Add(modelHistoryInfo);
            }
            catch { }

        }
        /// <summary>
        /// 添加施工人员
        /// </summary>
        /// <returns></returns>
        private string SaveConsInfo(string workorderid, string userid)
        {
            string res = "error";
            try
            {
                Model.T_Wo_WorkOrderConstructor modelConstructor = new Model.T_Wo_WorkOrderConstructor();
                BLL.T_Wo_WorkOrderConstructor bll_Constructoradd = new BLL.T_Wo_WorkOrderConstructor();
                modelConstructor.F_WORKORDERID = Convert.ToInt32(workorderid);//工单ID
                modelConstructor.F_USERID = Convert.ToInt32(userid);
                modelConstructor.F_ISMAIN = 1;
                int i = bll_Constructoradd.Add(modelConstructor);
                if (i > 0)
                {
                    res = "success";
                }
            }
            catch (Exception ex)
            {
            }

            return res;

        }

        /// <summary>
        /// 指派人员
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="optnodeid"></param>
        /// <param name="optnodename"></param>
        /// <returns></returns>
        private AssignParticipator[] GetAssignParticipatorList(string userid,string optnodeid,string optnodename)
        {
            AssignParticipator[] arr = new AssignParticipator[1];
            arr[0] = new AssignParticipator();
            arr[0].NodeID = optnodeid;
            arr[0].NodeName = optnodename;
            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=" + userid.Trim() + "");
            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;
        }

        public bool SubmitOSubmit(int instanceID, string _flowid, string tab,out int workorderid)
        {
            bool bl = false;
            workorderid = 0;
            try
            {
                Model.T_Wo_WorkOrderBase model = new Model.T_Wo_WorkOrderBase();

                #region 工单信息

                model.F_WORKORDERTYPEID = Convert.ToInt32(typeid);//类型ID
                model.F_WORKORDERSTATEID = Convert.ToInt32(nodeID);//状态ID
                model.F_CODE = DateTime.Now.ToString("yyyyMMddHHmmssms");//工单编号
                model.F_WORKORDERNAME = txtCustomerName.Text.Trim() + "报修工单";//工单名称
                model.F_NUMBER = model.F_CODE;
                model.F_CUSTOMERNAME = txtCustomerName.Text.Trim();//客户姓名
                model.F_CUSTOMERTELEPHONE = this.txtTsPhone.Text.Trim();//客户电话
                model.F_LINKMAN = this.txtTsName.Text.Trim();//联系人姓名
                model.F_LINKMANTELEPHONE = this.txtTsPhone.Text.Trim();//联系人电话
                model.F_ADSLACCOUNT = hfCallId.Value.Trim();
                model.F_BANDWIDTH = "";
                //model.F_STANDARDADDRESS = F_STANDARDADDRESS;
                //model.F_INSTALLADDRESS = F_INSTALLADDRESS;
                model.F_KSHADDRESSCODE = "";
                model.F_PROVINCE = drpProvince.Text.Trim();
                model.F_CITY = drpCity.Text.Trim();
                model.F_AREA = "";
                model.F_ROAD = "";
                model.F_HOUSING = "";
                model.F_WORKORDERFROM = "400来电";
                //model.F_WORKORDERLEVELID = F_WORKORDERLEVELID;
                model.F_FILEFLAG = 0;

                model.F_CONTENT = txtTsContent.Value;
                model.F_REPAIRREQUEST = txtTsContent.Value;
                model.F_REPAIRMANID = 0;
                model.F_REPAIRMANNAME = txtTsName.Text;
                model.F_REPAIRMANPHONE = txtTsPhone.Text;
                if (hiddTsType.Value != "")
                {
                    model.F_WORKORDERLEVELID = Convert.ToInt32(hiddTsType.Value);
                }

                LoginUser p_LoginUser = new LoginUser(this.Context);
                if (p_LoginUser.UserID != 0)
                {
                    model.F_USERNAME = Server.UrlDecode(p_LoginUser.UserName);
                    model.F_DEPTCODE = p_LoginUser.DeptId.ToString();
                    model.F_EMPCODE = p_LoginUser.UserCode;
                    model.F_DEPTID = p_LoginUser.DeptId;
                    model.F_USERID = p_LoginUser.UserID;
                }
                model.F_CREATEBY = Convert.ToInt32(hfUserId.Value.Trim());
                model.F_CREATEDATE = DateTime.Now;
                model.F_RETURNVISITFLAG = 0;
                model.F_RETURNVISITSTATE = 0;
                model.F_RETURNVISITRESULT = 0;
                model.F_RETURNVISITCONTENT = "";
                model.F_DELETEFLAG = 0;
                model.F_ALLUSETIMES = 0;
                model.F_STARTTIME = DateTime.Now;

                model.F_OVERTIMES = 0;
                model.F_FORMID = 0;
                model.F_HASTENCOUNTS = 0;
                model.F_RANGEID = Convert.ToInt32(_flowid);
                model.F_RANGEX = 0;
                model.F_RANGEY = 0;
                model.F_INSTANCEID = Convert.ToInt32(instanceID);
                model.F_CUSTOMERID = Convert.ToInt32(hiddCustomerId.Value.Trim());
                model.F_REPAIRCLOSEMANID = 0;
                model.F_REPAIRCLOSEMANNAME = "";
                model.F_REPAIRCLOSEREASONS = "";
                model.F_REPAIRCLOSEREPTID = 0;
                model.F_REPAIRCLOSEREPT = "";


                #endregion

                #region 关于超时时间
                SetWorkOrderBaseOverTime(typeid, model);
                #endregion
                int resorderbase = new BLL.T_Wo_WorkOrderBase().Add(model);//添加基本信息  
                workorderid = resorderbase;
                if (resorderbase > 0)
                {
                    bl = true;
                }
                else
                {
                    bl = false;
                }

            }
            catch (Exception ex)
            {
                //InsertOptLogs("", "添加工单失败,错误信息:" + ex.Message, 2);
                MessageBoxToWindow("保存提示", "保存失败！" + ex.Message, "error");
            }
            return bl;
        }

        #region 获取超时时间

        /// <summary>
        /// 设置基本工单信息 超时时间,告警时间
        /// </summary>
        /// <param name="typeid">工单类型ID</param>
        /// <param name="model_orderbase">工单基本表Model</param>
        public void SetWorkOrderBaseOverTime(string typeid, Model.T_Wo_WorkOrderBase model_orderbase)
        {
            BLL.T_Wo_TypeAlarmDate bll_ala = new BLL.T_Wo_TypeAlarmDate();
            List<Model.T_Wo_TypeAlarmDate> list_ala = bll_ala.GetModelList(" F_WorkOrderTypeId='" + typeid
                + "' and F_DeleteFlag=0 ");
            if (list_ala != null && list_ala.Count > 0)
            {
                Model.T_Wo_TypeAlarmDate model_time = null;
                for (int i = 0; i < list_ala.Count; i++)
                {   //如果有当前类型就取当前
                    if (list_ala.Count > 1)
                    {
                        if (list_ala[i].F_IsMain == 1)
                        {
                            continue;
                        }
                    }
                    model_time = list_ala[i];
                    if (model_time != null)
                    {
                        int day = 0;
                        int hour = 0;
                        int minute = 0;
                        switch (model_time.F_Cunit)
                        {
                            case 0://分钟
                                minute = model_time.F_Ccount == null ? 0 : int.Parse(model_time.F_Ccount.ToString());
                                break;
                            case 1://小时
                                hour = model_time.F_Ccount == null ? 0 : int.Parse(model_time.F_Ccount.ToString());
                                break;
                            case 2://天
                                day = model_time.F_Ccount == null ? 0 : int.Parse(model_time.F_Ccount.ToString());
                                break;
                            default:
                                break;
                        }
                        if (day == 0 && hour == 0 && minute == 0)
                            model_orderbase.F_ASKFINISHTIME = null;
                        else
                            model_orderbase.F_ASKFINISHTIME = GetNoramlWorkTime(DateTime.Now, day, hour, minute);
                        day = 0; hour = 0; minute = 0;//清值操作

                        switch (model_time.F_Gunit)
                        {
                            case 0://分钟
                                minute = model_time.F_Gcount == null ? 0 : int.Parse(model_time.F_Gcount.ToString());
                                break;
                            case 1://小时
                                hour = model_time.F_Gcount == null ? 0 : int.Parse(model_time.F_Gcount.ToString());
                                break;
                            case 2://天
                                day = model_time.F_Gcount == null ? 0 : int.Parse(model_time.F_Gcount.ToString());
                                break;
                            default:
                                break;
                        }
                        if (day == 0 && hour == 0 && minute == 0)
                            model_orderbase.F_REMAINDERTIME = null;
                        else
                            model_orderbase.F_REMAINDERTIME = GetNoramlWorkTime(DateTime.Now, day, hour, minute);

                    }
                }
            }
        }

        /// <summary>
        /// 当前时间,换算成正常工作时间,并且Add 天时分
        /// </summary>
        /// <param name="timeStart">初始时间</param>
        /// <param name="days">增加的天数</param>
        /// <param name="hours">增加的小时</param>
        /// <param name="minutes">增加的分钟</param>
        /// <returns></returns>
        public DateTime GetNoramlWorkTime(DateTime timeStart, int days, int hours, int minutes)
        {
            timeStart = timeStart.AddDays(days);
            timeStart = timeStart.AddHours(hours);
            timeStart = timeStart.AddMinutes(minutes);
            return timeStart;
        }

        #endregion

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

        #region 设置黑名单
        /// <summary>
        /// 设置黑名单
        /// </summary>
        /// <param name="page"></param>
        public void AddBlackPhone(string InPhoneNum, string CallRecId, string txtTime)
        {
            Model.T_Call_Blacklist model_T_Call_Blacklist = new Model.T_Call_Blacklist();
            try
            {
                LoginUser p_LoginUser = new LoginUser(this.Context);
                model_T_Call_Blacklist.F_BlackType = 0;//加入黑名单类型
                model_T_Call_Blacklist.F_CallId = CallRecId;//呼叫编号
                model_T_Call_Blacklist.F_IsDelete = false;//是否删除
                model_T_Call_Blacklist.F_SetTime = DateTime.Now;//设置时间
                model_T_Call_Blacklist.F_TelPhone = InPhoneNum;//电话号码
                model_T_Call_Blacklist.F_UserId = p_LoginUser.UserID;//添加人id
                if (rdTimesType0.Checked)
                {
                    model_T_Call_Blacklist.F_RemoveTime = DateTime.Now.AddMinutes(Convert.ToInt32(txtTime));//超时时间
                }
                if (rdTimesType1.Checked)
                {
                    model_T_Call_Blacklist.F_RemoveTime = DateTime.Now.AddHours(Convert.ToInt32(txtTime));//超时时间
                }
                if (rdTimesType2.Checked)
                {
                    model_T_Call_Blacklist.F_RemoveTime = DateTime.Now.AddDays(Convert.ToInt32(txtTime));//超时时间
                }
                new BLL.T_Call_Blacklist().Add(model_T_Call_Blacklist);
            }
            catch (Exception ex)
            {
                //AddOperateLog(1, 15, 0, "设置黑名单：号码:" + InPhoneNum + ",ID：" + CallRecId + ",错误原因：" + ex.ToString() + "！");
            }
        }
        #endregion

        #region 客户信息

        private Model.T_Cus_CustomerBase GetCustomerModel()
        {
            Model.T_Cus_CustomerBase _model = new Model.T_Cus_CustomerBase();
            try
            {
                if (hiddCustomerId.Value != "" && hiddCustomerId.Value != "0")
                {
                    _model.F_CustomerId = Convert.ToInt32(hiddCustomerId.Value);
                    _model = new BLL.T_Cus_CustomerBase().GetModel(Convert.ToInt32(hiddCustomerId.Value));
                }
                else
                {
                    _model.F_CustomerCode = "KHBH" + DateTime.Now.ToString("yyyyMMddHHmmss");// txtCustomerCode.Text.Trim();
                }
                _model.F_CustomerName = txtCustomerName.Text.Trim();
                if (hiddSeriveDeptId.Value != "")
                {
                    _model.F_ServiceDeptID = Convert.ToInt32(hiddSeriveDeptId.Value);
                }
                _model.F_ServiceDept = drpServiceDept.Text;
                if (hiddProvinceId.Value != "")
                {
                    _model.F_RegionId = Convert.ToInt32(hiddProvinceId.Value);
                }
                _model.F_Province = drpProvince.Text;
                if (hiddCityId.Value != "")
                {
                    _model.F_CityID = Convert.ToInt32(hiddCityId.Value);
                }
                _model.F_City = drpCity.Text;
   

                _model.F_Telephone = drpTelephone.Text;
                _model.F_Mobile = drpMobile.Text;
                _model.F_ChargeTelephone = drpChargeTelephone.Text;

                return _model;
            }
            catch
            {
                return null;
            }
        }

        #endregion


        #region 处理来电电话号码 2015-03-27 张高炯
        private string DealPhone(string phone)
        {
            if (phone.Length > 10)
            {
                if (phone.Length == 12)
                {
                    return phone;
                }
                else
                {
                    if (phone.Substring(0, 2) == "04")
                    {
                        phone = phone.Substring(2, phone.Length - 2);
                    }
                }
            }
            return phone;
        }
        #endregion
    }
}