using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CitySunlight;

namespace CitySunlight.Product
{
    public partial class ProductEdit : System.Web.UI.Page
    {
        public String msg;
        public String username;
        public String type;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.Redirect("/Account/Login.aspx");
            else
                username = Session["username"].ToString();
            type = HttpUtils.getQueryString("type");
            switch (type)
            {
                case "success":
                    msg = HttpUtils.getQueryString("msg");
                    this.submit.Visible = false;
                    break;
                case "delete":
                    if (isExist(HttpUtils.getQueryString("id").ToInt()) != 0)
                    {
                        msg = "你确定要删除这个产品?";
                        this.submit.Text = "确定";
                    }
                    break;
            }
        }

        public String CreateEditForm()
        {
            int id = HttpUtils.getQueryString("id").ToInt();
            switch (type)
            {
                case "edit":
                    if (isExist(id) != 0)
                    {
                        this.submit.Text = "修改";
                        return GetEditForm(id);
                    }
                    return "";
                case "create":
                    this.submit.Text = "添加";
                    return GetEditForm(id);
            }
            return "";
        }
        public int isExist(int id)
        {
            if (id == 0 || !ProductManager.isExist(id))
            {
                this.submit.Visible = false;
                msg = "您所操作的产品不存在!";
                id = 0;
            }
            return id;
        }

        protected String GetEditForm(int id)
        {
            String name = "";
            String url = "empty.jpg";
            String picurl = String.Format("<img src=\"../Picture/{0}\"alt=\"\" width=\"64\" height=\"64\"/>", url);
            String price = "";
            String amount = "";
            String classid = "";
            if (id != 0)
            {
                name = ProductManager.GetProductInfo(id, ProductManager.Info.ItemName);
                url = ProductManager.GetProductInfo(id, ProductManager.Info.PicUrl);
                picurl = String.Format("<img src=\"../Picture/{0}\"alt=\"\" width=\"64\" height=\"64\"/>", url);
                price = ProductManager.GetProductInfo(id, ProductManager.Info.Price);
                amount = ProductManager.GetProductInfo(id, ProductManager.Info.Amount);
                classid = ProductManager.GetProductInfo(id, ProductManager.Info.Class);
                if (username != ProductManager.GetProductInfo(id, ProductManager.Info.UserName))
                {
                    this.submit.Visible = false;
                    return "<h1 align=\"center\" style=\"color: red\">你没有修改此商品的权限!</h1>";
                }


            }
            String html = "";
            html += "<table align=\"center\">";
            html += "<tr>" + addTdc("<h1>商品编辑</h1>", 3) + "</tr>";
            html += "<tr>" + addTd("商品名称") + addTdc(addText("Name", name), 2) + addTd("<input type=\"hidden\" name=\"iid\" value=\"" + id + "\"/>") + "</tr>";
            html += "<tr>" + addTd("商品分类") + addTd(ProductClassManager.getOptionString("Class", classid)) + addTd(addA("编辑", "ProductClassEdit.aspx")) + "</tr>";
            html += "<tr>" + addTdr("商品图片", 2) + addTdc(picurl, 2) + "</tr>";
            html += "<tr>" + addTdc(addFile("Picture"), 2) + "</tr>";
            html += "<tr>" + addTd("商品价格") + addTdc(addText("Price", price), 2) + "</tr>";
            html += "<tr>" + addTd("库存数量") + addTdc(addText("Amount", amount), 2) + "</tr>";
            html += "</table>";
            return html;
        }
        protected String addA(String Text, String Url)
        {
            return String.Format("<a href=\"{0}\">{1}</a>", Url, Text);
        }
        protected String addTd(String value)
        {
            return String.Format("<td align=\"center\">{0}</td>", value);
        }
        protected String addTdc(String value, int colspan)
        {
            return String.Format("<td colspan=\"{0}\" align=\"center\">{1}</td>", colspan, value);
        }
        protected String addTdr(String value, int rowspan)
        {
            return String.Format("<td rowspan=\"{0}\" align=\"center\">{1}</td>", rowspan, value);
        }
        protected String addText(String name, String value)
        {
            return String.Format("<input type=\"text\" name=\"{0}\" value=\"{1}\" />", name, value);
        }
        protected String addImg(String picname)
        {
            return String.Format("<img alt=\"\" src=\"../Picture/{0}\" />", picname);
        }
        protected String addFile(String name)
        {
            return String.Format("<input type=\"file\" name=\"{0}\" style=\"width:150px\" value=\"请选择文件...\" />", name);
        }
        protected void submit_Click(object sender, EventArgs e)
        {
            int id = HttpUtils.getQueryString("id").ToInt();
            String picurl = "";
            switch (type)
            {
                case "delete":
                    if (ProductManager.DeleteProduct(id))
                    {
                        msg = "产品删除成功!";
                        Response.Redirect("/Product/ProductEdit.aspx?type=success&msg=" + msg);
                    }
                    return;
                case "edit":
                    if (id == 0)
                    {
                        msg = "您所操作的产品不存在!";
                        return;
                    }
                    picurl = ProductManager.GetProductInfo(id, ProductManager.Info.PicUrl);
                    break;
            }
            String floder = "/Picture/";
            String user = Session["username"].ToString();
            String name = HttpUtils.getElementsbyName("Name");
            HttpPostedFile file = HttpUtils.getFilebyName("Picture");
            decimal price = HttpUtils.getElementsbyName("Price").Todecimal();
            int amount = HttpUtils.getElementsbyName("Amount").ToInt();
            int classid = int.Parse(HttpUtils.getElementsbyName("Class"));
            //检查名称
            if (name.Length == 0)
            {
                msg = "请填写名称!";
                GoBack();
                return;
            }
            //检查价格
            if (price == 0)
            {
                msg = "请输入价格且必须为数字!";
                GoBack();
                return;
            }
            //检查库存
            if (amount == 0)
            {
                msg = "请输入库存且必须为数字!";
                GoBack();
                return;
            }
            //检查图片(图片文件为空,且不存在原有图片)
            if (file == null && picurl == "")
            {
                msg = "请上传产品图片!";
                Response.Write("<scrip>windows.history.go(-1);</scrip>");
                return;
            }
            if (file != null)
            {
                String fileExtension = Path.GetExtension(file.FileName).ToLower();
                //验证上传文件是否图片格式
                if (!IsImage(fileExtension))
                {
                    msg = "请上传类型为 jpg | gif | bmp | png 图片!";
                    GoBack();
                    return;
                }
                //生成图片名称
                picurl = HttpUtils.currentTimeMillis() + "_" + user + fileExtension;
                //转换为系统路径
                String filepath = Server.MapPath(floder + picurl);
                //保存图片
                file.SaveAs(filepath);
            }
            bool upload = false;
            switch (type)
            {
                case "edit":
                    upload = ProductManager.EditProduct(id, user, name, classid, picurl, price, amount);
                    break;
                case "create":
                    upload = ProductManager.AddProduct(user, name, classid, picurl, price, amount);
                    break;
            }
            if (upload)
            {
                msg = "产品发布成功!";
                Response.Redirect("/Product/ProductEdit.aspx?type=success&msg=" + msg);
            }
            else
            {
                msg = "产品发布失败!";
                GoBack();
            }


        }


        public void GoBack()
        {
            Response.Write("<scrip>windows.history.go(-1);</scrip>");
        }
        /// <summary>
        /// 验证是否指定的图片格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool IsImage(string str)
        {
            bool isimage = false;
            string thestr = str.ToLower();
            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png" };
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (thestr == allowExtension[i])
                {
                    isimage = true;
                    break;
                }
            }
            return isimage;
        }
    }
}