using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.TestRun.DriverSub
{
    public partial class DriverSubContactorIn : PageBase
    {
        public string ContractId
        {
            get
            {
                return (string)ViewState["ContractId"];
            }
            set
            {
                ViewState["ContractId"] = value;
            }
        }
        #region 定义项
        /// 
        ///     上传预设的虚拟路径
        /// 
        private readonly string initPath = Const.ExcelUrl; //"File\\Excel\\DataIn\\";
        /// 
        ///     错误集合
        /// 
        public static string errorInfos = string.Empty;
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ContractId = Request.Params["ContractId"];
            }
        }
        protected void btnImport_Click(object sender, EventArgs e)
        {  
            errorInfos = string.Empty;
            if (fuAttachUrl.HasFile == false)
            {
                ShowNotify("请选择Excel文件!", MessageBoxIcon.Warning);
                return;
            }
            var IsXls = Path.GetExtension(fuAttachUrl.FileName).Trim().ToLower();
            if (IsXls != ".xlsx")
            {
                ShowNotify("只能选择Excel文件!", MessageBoxIcon.Warning);
                return;
            }
            if (!string.IsNullOrEmpty(errorInfos)) errorInfos = string.Empty;
            var rootPath = Server.MapPath("~/");
            var initFullPath = rootPath + initPath;
            if (!Directory.Exists(initFullPath)) Directory.CreateDirectory(initFullPath);
            //指定上传文件名称
            hdFileName.Text = Funs.GetNewFileName() + IsXls;
            //上传文件路径
            var filePath = initFullPath + hdFileName.Text;
            //文件上传服务器
            fuAttachUrl.PostedFile.SaveAs(filePath);
            //文件上传服务器后的名称
            var fileName = rootPath + initPath + hdFileName.Text;
            //读取Excel
            DataSet ds = NPOIHelper.ExcelToDataSet(fileName, out string message, false);
            File.Delete(fileName);
            //将ds数据转换成 List
            var list = new List();
           
            if (ds == null)
            {
                this.fuAttachUrl.Reset();
                ShowNotify("模板错误,请从系统下载正确的模板!", MessageBoxIcon.Warning);
                return;
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                ShowNotify(message, MessageBoxIcon.Warning);
                return;
            }
            if (ds.Tables[0].Rows.Count > 1)
            {
                var fileVerify = VerifyFile(ds);
                if (!fileVerify)
                {
                    this.fuAttachUrl.Reset();
                    ShowNotify("请获取正确模板!", MessageBoxIcon.Warning);
                    return;
                }
                
                for (var i = 1; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (string.IsNullOrEmpty(ds.Tables[0].Rows[i][1].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][2].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][3].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][4].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][5].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][6].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][7].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][8].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][9].ToString()) ||
                        string.IsNullOrEmpty(ds.Tables[0].Rows[i][10].ToString()) )
                    {
                        errorInfos += "第" + (i + 1) + "行数据不完整,请检查!";
                        continue;  
                    }
                    var model = new Model.DriverSub_DriverSubContractors();
                    model.DriverSubContractorsId = Guid.NewGuid().ToString();
                    model.SubUnitName = ds.Tables[0].Rows[i][1].ToString();
                    model.EnterpriseNature = ds.Tables[0].Rows[i][2].ToString();
                    model.SubcontractingType = ds.Tables[0].Rows[i][3].ToString();
                    model.CollCropCode = ds.Tables[0].Rows[i][4].ToString();
                    model.SafetyProductionLicense = ds.Tables[0].Rows[i][5].ToString();
                    model.QualificationCertificateNumber = ds.Tables[0].Rows[i][6].ToString();
                    model.QualificationType = ds.Tables[0].Rows[i][7].ToString();
                    model.QualificationLevel = ds.Tables[0].Rows[i][8].ToString();
                    model.Province = ds.Tables[0].Rows[i][9].ToString();
                    model.City = ds.Tables[0].Rows[i][10].ToString();
                    model.IsUse = true;
                    var subcontractingType = model.SubcontractingType; 
                    var subcontractingTypeList = BLL.DropListService.drpDriverSubNameList();
                    var typemodel=  subcontractingTypeList.Where(x => x.Text == subcontractingType).FirstOrDefault();
                    if (typemodel==null)
                    {
                        errorInfos += "第" + (i + 1) + "行分包类别不存在,请检查!";
                    }
                    else
                    {
                        model.SubcontractingType= typemodel.Value;
                    }
                     
                    list.Add(model);
                }
                if (string.IsNullOrEmpty(errorInfos))
                {
                    DriversubcontractorsService.UpdateDriverSub_DriverSubContractorsIsUse();
                    AddOrUpdate(list);
                    PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                }
                else
                {
                    ShowNotify(errorInfos, MessageBoxIcon.Warning);
                }
            }
        }
        /// 
        /// 插入或更新数据
        /// 
        /// 
        private void AddOrUpdate(List list)
        {
            foreach (var item in list)
            {
                var model = BLL.DriversubcontractorsService.GetDriverSubContractorsByCollCropCode(item.CollCropCode);
                if (model != null)
                {
                    model.SubUnitName = item.SubUnitName;
                    model.EnterpriseNature = item.EnterpriseNature;
                    model.SubcontractingType = item.SubcontractingType;
                    model.CollCropCode = item.CollCropCode;
                    model.SafetyProductionLicense = item.SafetyProductionLicense;
                    model.QualificationCertificateNumber = item.QualificationCertificateNumber;
                    model.QualificationType = item.QualificationType;
                    model.QualificationLevel = item.QualificationLevel;
                    model.Province = item.Province;
                    model.City = item.City;
                    model.IsUse = item.IsUse;
                    BLL.DriversubcontractorsService.UpdateDriverSub_DriverSubContractors(model);
                }
                else
                {
                    BLL.DriversubcontractorsService.AddDriverSub_DriverSubContractors(item);
                }
            }
        }
        private bool VerifyFile(DataSet ds)
        {
            var result = true;
            if (ds.Tables[0].Rows[1][0].ToString().Contains("序号")) result = false;
            if (ds.Tables[0].Rows[1][1].ToString().Contains("企业名称")) result = false;
            if (ds.Tables[0].Rows[1][2].ToString().Contains("企业性质")) result = false;
            if (ds.Tables[0].Rows[1][3].ToString().Contains("分包类别")) result = false;
            if (ds.Tables[0].Rows[1][4].ToString().Contains("统一社会信用代码")) result = false;
            if (ds.Tables[0].Rows[1][5].ToString().Contains("安全生产许可证")) result = false;
            if (ds.Tables[0].Rows[1][6].ToString().Contains("资质证书编号")) result = false;
            if (ds.Tables[0].Rows[1][7].ToString().Contains("资质类别")) result = false;
            if (ds.Tables[0].Rows[1][8].ToString().Contains("资质等级")) result = false;
            if (ds.Tables[0].Rows[1][9].ToString().Contains("省份")) result = false;
            if (ds.Tables[0].Rows[1][10].ToString().Contains("城市")) result = false;
            return result;
        }
        #region 模板下载
        /// 
        ///     模板下载
        /// 
        /// 
        /// 
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Confirm.GetShowReference("确定要下载模板吗?", string.Empty,
                MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"),
                PageManager1.GetCustomEventReference("Confirm_Cancel")));
        }
        /// 
        ///     下载导入模板
        /// 
        /// 
        /// 
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                var rootPath = Server.MapPath("~/");
                var uploadfilepath = rootPath + Const.DriverSubContactTemplateUrl;
                var filePath = Const.DriverSubContactTemplateUrl;
                var fileName = Path.GetFileName(filePath);
                var info = new FileInfo(uploadfilepath);
                var fileSize = info.Length;
                Response.ClearContent();
                Response.AddHeader("Content-Disposition",
                    "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
                Response.ContentType = "excel/plain";
                Response.ContentEncoding = Encoding.UTF8;
                Response.AddHeader("Content-Length", fileSize.ToString().Trim());
                Response.TransmitFile(uploadfilepath, 0, fileSize);
                Response.End();
            }
        }
        #endregion
    }
}