using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace 身份证号校验
{
    public partial class Form1 : Form
    {
        private ConnectionStringSettings conn;
        private Soubu.DbHelper.DbHelper db;
        private string userId = null;
        private string logPath;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.conn = ConfigurationManager.ConnectionStrings["ConnStr"];
            this.db = new Soubu.DbHelper.DbHelper(conn, 60);
            this.logPath = Path.Combine(Application.StartupPath, "idCardNumError.txt");
        }
        #region button1_Click连接数据库，加载当前用户所有表
        /// <summary>
        /// 连接数据库，加载当前用户所有表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string[] arrConnStr = this.conn.ConnectionString.Split(';');
            string sql = string.Empty;
            DbParameter[] dbParams = new DbParameter[1];
            if ("System.Data.SqlClient".ToUpper() == conn.ProviderName.ToUpper())
            {
                DbParameter p1 = db.DbProvider.CreateParameter();
                p1.Value = string.Empty;
                p1.ParameterName = string.Empty;
                dbParams[0] = p1;
                sql = "Select Table_Name From INFORMATION_SCHEMA.TABLES Order by Table_Name";
            }
            else if ("Oracle.ManagedDataAccess.Client".ToUpper() == conn.ProviderName.ToUpper())
            {
                this.userId = arrConnStr.Where(a => a.ToUpper().StartsWith("USER ID".Replace(" ", " "))).FirstOrDefault().Split('=')[1].Trim();
                sql = "Select Table_Name From ALL_Tables where Owner= :oracleUserName Order by Table_Name";
                DbParameter p1 = db.DbProvider.CreateParameter();
                p1.Value = this.userId.ToUpper();
                p1.ParameterName = ":oracleUserName";
                dbParams[0] = p1;
            }
            foreach (DataRow item in db.QueryDataTable(sql, dbParams).Rows)
            {
                cboTabName.Items.Add(item[0]);
            }
            cboTabName.SelectedIndex = 0; //默认选中第1行
        }
        #endregion
        #region cboTabName_SelectedIndexChanged表名改变时，加载表对应的字段
        /// <summary>
        /// 表名改变时，加载表对应的字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboTabName_SelectedIndexChanged(object sender, EventArgs e)
        {
            cboShenFeZH.Items.Clear(); //先清除下拉框中的值
            cboQiTaZD.Items.Clear();
            string sql = string.Empty;

            DbParameter pTabName = db.DbProvider.CreateParameter();
            pTabName.Value = cboTabName.Text;
            pTabName.ParameterName = this.db.ParamPrefix + "tableName";
            DbParameter[] dbParams = new DbParameter[2];
            dbParams[0] = pTabName;
            if ("System.Data.SqlClient".ToUpper() == conn.ProviderName.ToUpper())
            {
                sql = "Select Column_Name From INFORMATION_SCHEMA.COLUMNS where Table_Name = @tableName";
                DbParameter p1 = this.db.DbProvider.CreateParameter();
                p1.Value = string.Empty;
                p1.ParameterName = string.Empty;
                dbParams[1] = p1;
            }
            else if ("Oracle.ManagedDataAccess.Client".ToUpper() == conn.ProviderName.ToUpper())
            {
                sql = "Select Column_Name From All_Tab_Columns where Table_Name = :tableName And Owner= :oracleUserName";
                DbParameter p1 = this.db.DbProvider.CreateParameter();
                p1.Value = this.userId.ToUpper();
                p1.ParameterName = ":oracleUserName";
                dbParams[1] = p1;
            }
            foreach (DataRow item in this.db.QueryDataTable(sql, dbParams).Rows)
            {
                cboShenFeZH.Items.Add(item[0]);
                cboQiTaZD.Items.Add(item[0]);
            }
            cboShenFeZH.SelectedIndex = 0; //默认选中
            cboQiTaZD.SelectedIndex = 0; //默认选中
        } 
        #endregion
        #region cbDataBase_Click从数据库校验
        /// <summary>
        /// 从数据库校验
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbDataBase_Click(object sender, EventArgs e)
        {
            cbInput.Checked = false;
            cbDataBase.Checked = true;
            btnCreate.Enabled = true;
        } 
        #endregion
        #region cbInput_Click直接输入校验
        /// <summary>
        /// 直接输入校验
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbInput_Click(object sender, EventArgs e)
        {
            cbInput.Checked = true;
            cbDataBase.Checked = false;
            btnCreate.Enabled = true;
        } 
        #endregion
        #region btnCreate_Click开始校验身份证号
        /// <summary>
        /// 开始校验身份证号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            System.IO.File.WriteAllText(this.logPath, string.Empty); //初始化日志文件内容
            if (cbInput.Checked)
            {
                VIdText();
            }
            if (cbDataBase.Checked)
            {
                VIdDataBase();
            }
            Process.Start("notepad.exe", this.logPath); //用notepad.exe打开配置文件
        } 
        #endregion
        #region VIdText校验文本框内的身份证号
        /// <summary>
        /// 校验文本框内的身份证号
        /// </summary>
        private void VIdText()
        {
            Soubu.Helper.SoubuHelper sh = new Soubu.Helper.SoubuHelper();
            string sfzh = tboInput.Text;
            if (!string.IsNullOrWhiteSpace(sfzh))
            {
                bool flag = true;
                foreach (string item in sfzh.Split('\r'))
                {
                    if (string.IsNullOrWhiteSpace(item.Replace("\n", string.Empty))) continue;
                    string result;
                    if (!sh.VIdCardNo(item.Replace("\n", string.Empty).Trim(), out result))
                    {
                        flag = false;
                        System.IO.File.AppendAllText(this.logPath, string.Format("{0}\t{1}\t{2}\r\n", item, string.Empty, result)); //追加文件内容
                    }
                }
                if (flag) System.IO.File.AppendAllText(this.logPath, string.Format("{0}\t{1}\t{2}\r\n", string.Empty, string.Empty, "校验完成，全部校验通过")); //追加文件内容
            }
        } 
        #endregion
        #region VIdDataBase校验数据库中的身份证号
        /// <summary>
        /// 校验数据库中的身份证号
        /// </summary>
        private void VIdDataBase()
        {
            string sql = string.Format("select {0},{1} from {2}", this.cboShenFeZH.Text, cboQiTaZD.Text, cboTabName.Text);
            Soubu.Helper.SoubuHelper sh = new Soubu.Helper.SoubuHelper();
            foreach (DataRow item in this.db.QueryDataTable(sql).Rows)
            {
                if (item[0] == DBNull.Value || item[0] == null)
                {
                    System.IO.File.AppendAllText(this.logPath, string.Format("{0}\t{1}\t{2}\r\n", string.Empty, (item[1] == DBNull.Value || item[1] == null) ? string.Empty : item[1].ToString(), "身份证号为空")); //追加文件内容
                }
                else
                {
                    string result;
                    if (!sh.VIdCardNo(item[0].ToString().Replace("\n", string.Empty).Trim(), out result))
                    {
                        System.IO.File.AppendAllText(this.logPath, string.Format("{0}\t{1}\t{2}\r\n", item[0], (item[1] == DBNull.Value || item[1] == null) ? string.Empty : item[1].ToString(), result)); //追加文件内容
                    }
                }
            }
        } 
        #endregion
        #region tboInput_KeyPress文本框全选
        /// <summary>
        /// 文本框全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tboInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\x1')
            {
                ((TextBox)sender).SelectAll();
                e.Handled = true;
            }
        } 
        #endregion
    }
}
