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

namespace HySoft.BaseCallCenter.Web.customermanage
{
    public partial class customermodify : System.Web.UI.Page
    {
        private int count = 2;
        private string eid = "0";
        private string fid = "2";
        private string table = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;
            try
            {
                Model.T_Form_FormInfo model = new BLL.T_Form_FormInfo().GetModel(2);
                if (model != null)
                {
                    count = Convert.ToInt32(model.F_ColumnCount.ToString());
                    eid = model.F_EntityId.ToString();
                    table = model.F_DBTableName.Trim();
                }
            }
            catch
            { }
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["customerId"]))
                {
                    hiddCustomerId.Value = Request.QueryString["customerId"];
                    Initialize(Request.QueryString["customerId"]);
                }
                //InitHtml();
            }
        }

        private void InitHtml()
        {
            StringBuilder res = new StringBuilder();
            res.Append("<table class=\"form_table\" style=\"width:100%;\">");
            DataTable dt = new DataTable();
            DataTable dtdic = new DataTable();
            DataTable dtInfo = new DataTable();
            try
            {
                string customerid = "0";
                string value = "";
                if (!string.IsNullOrEmpty(Request.QueryString["customerId"]))
                {
                    customerid = Request.QueryString["customerId"];
                    //获取
                    dt = new BLL.T_Form_EntityAttribute().GetList("F_EntityId=" + eid + " and F_IsCustomField=1 ").Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        dtInfo = DBUtility.DbHelperSQL.Query("select * from " + table + " where " + dt.Rows[0]["F_DBFieldlName"].ToString().Trim() + "=" + customerid).Tables[0];
                    }
                    dt.Clear();
                }
                dt = new BLL.T_Form_EntityAttribute().GetList("F_EntityId=" + eid + " and F_VisibleToPlatform=1 ").Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        res.Append("<tr>");
                    }
                    else
                    {
                        if (i % count == 0)
                        {
                            res.Append("</tr><tr>");
                        }
                    }
                    res.Append("<th style='width:95px;'><span id='span_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' name='span_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "'>" + dt.Rows[i]["F_Name"].ToString().Trim() + "：</span></th>");
                    if (dt.Rows[i]["F_IsLookup"].ToString().Trim().ToLower() == "true")
                    {
                        dtdic = new BLL.T_Sys_DictionaryValue().GetList("F_DictionaryFlag='" + dt.Rows[i]["F_LookupKey"].ToString().Trim() + "'").Tables[0];
                        string listhtml = "<option value=\"\">请选择" + dt.Rows[i]["F_Name"].ToString().Trim() + "</option>";
                        foreach (DataRow drdic in dtdic.Rows)
                        {
                            string check = "";
                            if (dtInfo.Rows.Count > 0)
                            {
                                //dtInfo.Rows[0][dt.Rows[i]["F_DBFieldlName"].ToString().Trim()].ToString();
                                if (dtInfo.Select(" " + dt.Rows[i]["F_DBFieldlName"].ToString().Trim() + "=" + drdic["F_DictionaryValueId"].ToString().Trim() + " ").Length > 0)
                                {
                                    check = "selected";
                                }
                            }
                            listhtml += "<option value=\"" + drdic["F_DictionaryValueId"].ToString().Trim() + "\" " + check + " >" + drdic["F_Name"].ToString().Trim() + "</option>";
                        }
                        res.Append("<td><select id='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' name='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' value='" + dt.Rows[i]["F_DBFieldlName"].ToString().Trim() + "' class='selectBox'>" + listhtml + "</select></td>");
                    }
                    else
                    {
                        switch (dt.Rows[i]["F_DBTypeName"].ToString().Trim().ToLower())
                        {
                            case "int":
                                res.Append("<td><input type='text' id='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' name='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' value='' class='txtInput' onKeyUp=\"this.value=this.value.replace(/[^\\d]/g,'');\" /></td>");
                                break;
                            case "decimal":
                                res.Append("<td><input type='text' id='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' name='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' value='' class='txtInput' onKeyUp=\"this.value=this.value.replace(/[^\\.\\d]/g,'');if(this.value.split('.').length>2){this.value=this.value.split('.')[0]+'.'+this.value.split('.')[1]}\" /></td>");
                                break;
                            case "datetime":
                                res.Append("<td><input type='text' id='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' name='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' value=''  onfocus=\"WdatePicker({skin:'whyGreen'})\" class='txtInput' /></td>");
                                break;
                            default:
                                res.Append("<td><input type='text' id='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' name='txt_arr_" + dt.Rows[i]["F_AttributeId"].ToString().Trim() + "' value='' class='txtInput' /></td>");
                                break;
                        }
                    }
                    if (i == (dt.Rows.Count - 1))
                    {
                        int tdcount = 0;
                        if ((dt.Rows.Count % count) != 0)
                        {
                            tdcount = count - (dt.Rows.Count % count);
                        }
                        for (int m = 0; m < tdcount; m++)
                        {
                            res.Append("<th>&nbsp;</th><td>&nbsp;</td>");
                        }

                        res.Append("</tr>");
                    }
                }
            }
            catch
            { }
            finally
            {
                dt.Dispose();
                dt.Clear();
            }

            res.Append("</table>");

            divForm.InnerHtml = res.ToString();
        }

        private string GetFieldValue(DataRow dr,int customerid)
        {
            string value = "";
            try
            {
                if (dr["F_IsCustomField"].ToString().Trim().ToLower() == "true")
                {
                    value = customerid.ToString();
                }
                else
                {
                    if (dr["F_IsLookup"].ToString().Trim().ToLower() == "true")
                    {
                        if (Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()] != null)
                        {
                            value = Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()].ToString();
                        }
                        else
                        {
                            value = "0";
                        }
                    }
                    else
                    {
                        switch (dr["F_DBTypeName"].ToString().Trim().ToLower())
                        {
                            case "int":
                                if (Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()] != null)
                                {
                                    value = Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()].ToString();
                                }
                                else
                                {
                                    value = "0";
                                }
                                break;
                            case "decimal":
                                if (Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()] != null)
                                {
                                    value = Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()].ToString();
                                }
                                else
                                {
                                    value = "0";
                                }
                                break;
                            case "datetime":
                                if (Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()] != null)
                                {
                                    value = "'" + Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()].ToString() + "'";
                                }
                                else
                                {
                                    value = "null";
                                }
                                break;
                            default:
                                if (Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()] != null)
                                {
                                    value = "'" + Request.Form["txt_arr_" + dr["F_AttributeId"].ToString().Trim()].ToString() + "'";
                                }
                                else
                                {
                                    value = "''";
                                }
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return value;
        }

        private bool InsertForm(int customerid)
        {
            DataTable dt = new DataTable();
            try
            {
                StringBuilder fieldsql = new StringBuilder();
                StringBuilder valuesql = new StringBuilder();
                dt = new BLL.T_Form_EntityAttribute().GetList("F_EntityId=" + eid + " and (F_VisibleToPlatform=1 or F_IsCustomField=1) ").Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        fieldsql.Append(" insert into " + dt.Rows[i]["F_DBTableName"].ToString().Trim() + " ([" + dt.Rows[i]["F_DBFieldlName"].ToString().Trim() + "]");
                        valuesql.Append(" values ( " + GetFieldValue(dt.Rows[i], customerid));
                    }
                    else
                    {
                        fieldsql.Append(",[" + dt.Rows[i]["F_DBFieldlName"].ToString().Trim() + "]");
                        valuesql.Append("," + GetFieldValue(dt.Rows[i], customerid));
                        if (i == (dt.Rows.Count - 1))
                        {
                            fieldsql.Append(") ");
                            valuesql.Append(") ");
                        }
                    }
                }
                string sql = fieldsql.ToString() + valuesql.ToString();
                DBUtility.DbHelperSQL.ExecuteSql(sql);

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

            return false;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SaveInfo();
        }
        private void SaveInfo()
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(Request.QueryString["actionFlag"].Trim()))
                {
                    string actionFlag = Request.QueryString["actionFlag"].Trim();
                    if (actionFlag == "add")
                    {
                        int b1 = new BLL.T_Cus_CustomerBase().Add(T_Cus_CustomerBase);
                        hiddCustomerId.Value = b1.ToString();
                        List<Model.T_Cus_ContactPerson> tcclist = new BLL.T_Cus_ContactPerson().GetModelList("F_CustomerId IS NULL or F_CustomerId<=0");
                        foreach (Model.T_Cus_ContactPerson tcc in tcclist)
                        {
                            tcc.F_CustomerId = Convert.ToInt32(hiddCustomerId.Value);
                            new BLL.T_Cus_ContactPerson().Update(tcc);
                        }

                        if (b1 > 0)
                        {

                            #region 保存扩展信息

                            InsertForm(b1);

                            #endregion


                            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>SaveInfo('success')</script>");
                        }
                        else
                        {
                            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>SaveInfo('warn')</script>");
                        }
                    }
                    if (actionFlag == "edit")
                    {
                        bool b2 = new BLL.T_Cus_CustomerBase().Update(T_Cus_CustomerBase);
                        List<Model.T_Cus_ContactPerson> tcclist = new BLL.T_Cus_ContactPerson().GetModelList("F_CustomerId IS NULL or F_CustomerId<=0");
                        foreach (Model.T_Cus_ContactPerson tcc in tcclist)
                        {
                            tcc.F_CustomerId = T_Cus_CustomerBase.F_CustomerId;
                            new BLL.T_Cus_ContactPerson().Update(tcc);
                        }
                        if (b2)
                        {
                            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>SaveInfo('success')</script>");
                        }
                        else
                        {
                            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>SaveInfo('warn')</script>");
                        }
                    }
                }
            }
            catch
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>SaveInfo('error')</script>");
            }
        }
        #region 信息初始化

        private void Initialize(string id)
        {
            T_Cus_CustomerBase = new BLL.T_Cus_CustomerBase().GetModel(Convert.ToInt32(id));
        }
        #endregion
        #region 公共属性
        private Model.T_Cus_CustomerBase T_Cus_CustomerBase
        {
            get
            {
                Model.T_Cus_CustomerBase _model = new Model.T_Cus_CustomerBase();
                if (hiddCustomerId.Value != "" || hiddCustomerId.Value == "0")
                    _model.F_CustomerId = Convert.ToInt32(hiddCustomerId.Value);
                _model.F_CustomerName = txtCustomerName.Text.Trim();
                _model.F_CustomerCode = txtCustomerCode.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;
                //if (hiddProductLineId.Value != "")
                //    _model.F_ProductLineID = Convert.ToInt32(hiddProductLineId.Value);
                //_model.F_ProductLine = drpProductLine.Text;
                //if (hiddCustomerNatureId.Value != "")
                //    _model.F_CustomerNatureID = Convert.ToInt32(hiddCustomerNatureId.Value);
                //_model.F_CustomerNature = drpCustomerNature.Text;
                //if (hiddCustomerClassId.Value != "")
                //    _model.F_CustomerClassID = Convert.ToInt32(hiddCustomerClassId.Value);
                //_model.F_CustomerClass = drpCustomerClass.Text;
                //if (hiddCustomerIndustryId.Value != "")
                //    _model.F_IndustryId = Convert.ToInt32(hiddCustomerIndustryId.Value);
                //_model.F_CustomerIndustry = drpCustomerIndustry.Text;
                //if (hiddRelationShipClassId.Value != "")
                //    _model.F_RelationShipClassID = Convert.ToInt32(hiddRelationShipClassId.Value);
                //_model.F_RelationShipClass = drpRelationShipClass.Text;
                //if (hiddAfterSaleNameID.Value != "")
                //    _model.F_AfterSaleNameID = Convert.ToInt32(hiddAfterSaleNameID.Value);
                //_model.F_AfterSaleName = drpAfterSaleName.Text;
                //基本信息部分
                //_model.F_Fax = txtFax.Text.Trim();
                //_model.F_Email = txtEmail.Text.Trim();
                _model.F_Telephone = drpTelephone.Text.Trim();
                _model.F_Mobile = drpMobile.Text.Trim();
                _model.F_ChargeTelephone = drpChargeTelephone.Text.Trim();
                //_model.F_Address = txtAddress.Text.Trim();
                //_model.F_PostCode = txtPostCode.Text.Trim();
                //_model.F_CurrentVersion = txtCurrentVersion.Text.Trim();
                //if (txtSystemStartTime.Text.Trim() != "")
                //{
                //    DateTime dt = new DateTime();
                //    if (DateTime.TryParse(txtSystemStartTime.Text.Trim(), out dt))
                //        _model.F_SystemStartTime = Convert.ToDateTime(txtSystemStartTime.Text.Trim());
                //}
                //if (txtQualityGuaranteeEndTime.Text.Trim() != "")
                //{
                //    DateTime dt = new DateTime();
                //    if (DateTime.TryParse(txtSystemStartTime.Text.Trim(), out dt))
                //        _model.F_QualityGuaranteeEndTime = Convert.ToDateTime(txtQualityGuaranteeEndTime.Text.Trim());
                //}
                //_model.F_SystemType = txtSystemType.Text.Trim();
                //_model.F_CustomerStatus = txtCustomerStatus.Text.Trim();
                //if (txtDeviceCount.Text.Trim() != "")
                //{
                //    int count = 0;
                //    if (int.TryParse(txtDeviceCount.Text.Trim(), out count))
                //        _model.F_DeviceCount = Convert.ToInt32(txtDeviceCount.Text.Trim());
                //}
                ////备注信息部分
                //_model.F_TrackInfo = txtTrackInfo.Value;
                _model.F_Notes = txtNotes.Value;
                //扩展信息部分
                //todo...
                return _model;
            }
            set
            {
                if (value != null)
                {
                    hiddCustomerId.Value = value.F_CustomerId.ToString();
                    txtCustomerName.Text = value.F_CustomerName;
                    txtCustomerCode.Text = value.F_CustomerCode;
                    hiddSeriveDeptId.Value = value.F_ServiceDeptID.ToString();
                    hiddProvinceId.Value = value.F_RegionId.ToString();
                    hiddCityId.Value = value.F_CityID.ToString();
                    hiddTelephone.Value = value.F_Telephone;
                    hiddMobile.Value = value.F_Mobile;
                    hiddChargeTelephone.Value = value.F_ChargeTelephone;
                    //hiddProductLineId.Value = value.F_ProductLineID.ToString();
                    //hiddCustomerNatureId.Value = value.F_CustomerNatureID.ToString();
                    //hiddCustomerClassId.Value = value.F_CustomerClassID.ToString();
                    //hiddCustomerIndustryId.Value = value.F_IndustryId.ToString();
                    //hiddRelationShipClassId.Value = value.F_RelationShipClassID.ToString();
                    //hiddAfterSaleNameID.Value = value.F_AfterSaleNameID.ToString();
                    drpServiceDept.Text = value.F_ServiceDept;
                    drpProvince.Text = value.F_Province;
                    drpCity.Text = value.F_City;
                    drpTelephone.Text = value.F_Telephone;
                    drpMobile.Text = value.F_Mobile;
                    drpChargeTelephone.Text = value.F_ChargeTelephone;
                    //drpProductLine.Text = value.F_ProductLine;
                    //drpCustomerNature.Text = value.F_CustomerNature;
                    //drpCustomerClass.Text = value.F_CustomerClass;
                    //drpCustomerIndustry.Text = value.F_CustomerIndustry;
                    //drpRelationShipClass.Text = value.F_RelationShipClass;
                    //drpAfterSaleName.Text = value.F_AfterSaleName;
                    ////基本信息部分
                    //txtFax.Text = value.F_Fax;
                    //txtEmail.Text = value.F_Email;
                    //txtTelephone.Text = value.F_Telephone;
                    //txtAddress.Text = value.F_Address;
                    //txtPostCode.Text = value.F_PostCode;
                    //txtCurrentVersion.Text = value.F_CurrentVersion;
                    //txtSystemStartTime.Text = value.F_SystemStartTime.ToString();
                    //txtQualityGuaranteeEndTime.Text = value.F_QualityGuaranteeEndTime.ToString();
                    //txtSystemType.Text = value.F_SystemType;
                    //txtCustomerStatus.Text = value.F_CustomerStatus;
                    //txtDeviceCount.Text = value.F_DeviceCount.ToString();
                    ////备注信息部分
                    //txtTrackInfo.Value = value.F_TrackInfo;
                    txtNotes.Value = value.F_Notes;
                    //扩展信息部分
                    //todo...
                }
            }
        }
        #endregion
    }
}