using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class TaskList : System.Web.UI.UserControl
{
    private string filepath = @"~/upfile/task/";
    static string userid = "0";
    static string TaksAccAtt;
    static int TaksAccNum;
    static long TaksAccMaxSize;
    static double TaksMinMoney=100;

    static string TaskAddPlanFile="TaskAddPlan.aspx";
    static string TaskAddPlanPath = @"~/china/";
    static string PlanViewUrl = @"/china/PlanView.Aspx";
    public string OpenTaskAddPlanFile
    {
        set
        {
            TaskAddPlanFile = value.ToString().Trim();
        }
    }
    public string OpenTaskAddPlanPath
    {
        set
        {
            TaskAddPlanPath = value.ToString().Trim();
        }
    }

    public string OpenPlanViewUrl
    {
        set
        {
            PlanViewUrl = value.ToString().Trim();
        }
    }

    protected string PlanViewOpen(string id)
    {
        return PlanViewUrl + "?PlanID=" + id;
    }
    protected string SelectOKView(string selectOK)
    {
        if (selectOK == "true")
        {
            return "[已中标]";
        }
        else
        {
            return "";
        }
    }


    protected string FilePath(string file)//读附近件路径
    {
        Task.FUNC f = new Task.FUNC();
        return f.filepath + file;
    }

    protected void readfilelist(string tid)  //读取被编辑任务附件列表
    {
        object RD = CDatabase.DBSelect("select * from TaksAcc where linkID=" + tid + " and type='Taks' order by sort");
        EGridView1.DataSource = RD;
        EGridView1.DataBind();
        CDatabase.CloseConn();

    }
    protected void TaskDBList()
    {
        /*
        object RD2;
        string wherestr1 = "";
        string wherestr2 = "";
        string wherestr = "1=1";
        if (Session["TaskListFinish"].ToString() != "all")
        {
            wherestr1 = "finish='" + Session["TaskListFinish"].ToString() + "'";
        }
        if (Session["TaskCategoryID"].ToString() != "0")
        {
            SqlConnection SQLconn = CDatabase.wtoconn();
            SqlDataReader RD;
            SQLconn.Open();
            SqlCommand scd = new SqlCommand("select id from taksCategory where pid=" + Session["TaskCategoryID"].ToString(), SQLconn);
            RD = scd.ExecuteReader();
            string re;
            if (RD.Read())
            {
                wherestr2 = "cid="+Convert.ToString(RD[0]);
                while (RD.Read())
                {
                    wherestr2 += " or cid=" + Convert.ToString(RD[0]);
                }
            }
            SQLconn.Close();
        }

        if (wherestr1 != "" && wherestr2 != "")
        {
            wherestr = wherestr1 + " and (" + wherestr2+")";
        }
        else
        {
            if (wherestr1 != "") wherestr = wherestr1;
            else if(wherestr2!="") wherestr = wherestr2;
        }

        RD2 = CDatabase.DBFillSelect("select * from TaksInfo where " + wherestr + " and subject like '%"+Session["TaskListKeyword"].ToString()+"%'" + Session["TaskListOrderBy"].ToString());
        TaskGridView2.DataSource = RD2;
        TaskGridView2.DataBind();
        CDatabase.CloseConn();
        TaskListTextBox1.Text = Session["TaskListKeyword"].ToString();
        //Message.Text = "select * from TaksInfo where " + wherestr + " " + Session["TaskListOrderBy"].ToString() + "  " + Session["TaskCategoryID"].ToString();
         */
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = CDatabase.wtoconn();
        conn.Open();
        SqlCommand smd = new SqlCommand("select finish from TaksInfo where id=" + Request.QueryString["taskid"].ToString().Trim(), conn);
        string idy =Convert.ToString(smd.ExecuteScalar());
        if (idy == "true")
        {
            TaskViewLinkButton1.Enabled = false;
            TaskViewLinkButton1.Text = "此任务完成";
            LinkButton1.Enabled = false;
            LinkButton1.Text = "此任务完成";
        }
        else
        {
            TaskViewLinkButton1.Enabled = true;
            LinkButton1.Enabled = true;
        }
        if (IsPostBack)
        {
        }
        else
        {
            //*******获取选择参数
            /*
            if (Request["finish"] != null)
            {
                Session["TaskListFinish"] = Request["finish"].ToString();
            }
            else
            {
                if (Session["TaskListFinish"] == null)
                {
                    Session["TaskListFinish"] = "all";
                }
            }
            if (Request["CategoryID"] != null)
            {
                Session["TaskCategoryID"] = Request["CategoryID"].ToString();
            }
            else
            {
                if (Session["TaskCategoryID"] == null)
                {
                    Session["TaskCategoryID"] = "0";
                }
            }

            if (Session["TaskListOrderBy"] == null)
            {
                Session["TaskListOrderBy"] = " order by sdt desc";
            }
            if (Session["TaskListKeyword"] == null)
            {
                Session["TaskListKeyword"] = "";
            }
             */

            if (Request["taskid"] != null)
            {
                Session["TaskViewID"]=Request["taskid"].ToString();
            }
            else
            {
                Session["TaskViewID"] = "0";
            }




            string[] tv=new string[11];
            tv = CDatabase.DBReader("select subject,userid,cid,money,sdt,edt,money,finish,callnum,info,isopen from TaksInfo where id="+Session["TaskViewID"].ToString()+"",11);
            TaskViewLabe1.Text = tv[0];
            int st=0;

            //编辑许可要求：会员，对应的任务，任务是在禁用状态
            if (Session["Wtouser"] != null && Session["Wtouser"] != "")
            {
                if (Session["id"].ToString() == tv[1] && tv[10] == "false")
                {
                    st = 1;
                }else
                {
                    st = 0;
                }
                //this.TaskViewLinkButton1.Enabled = false;
                //LinkButton1.Enabled = false;
                //this.TaskViewLinkButton1.Text = "自身任务";
                //LinkButton1.Text = "自身任务";
            }
            if (st == 1)
            {
                
                TaskViewPanel1.Visible = false;
                TaskEditPanel1.Visible = true;
                ESubject.Text = tv[0];
                EID.Text = Session["TaskViewID"].ToString();
                EUID.Text = tv[1];
                EMoney.Text = tv[3];
                EEDT.Text = tv[5];
                    //Convert.ToDateTime(tv[5]);
                    
                Content.Text = tv[9];

                readfilelist(Session["TaskViewID"].ToString());

                string[] bi = new string[5];
                bi = CDatabase.DBReader("select taksaccatt,taksaccnum,taksaccmaxsize from systembasicinformation", 3);
                TaksAccAtt = bi[0];
                TaksAccNum = Convert.ToInt16(bi[1]);
                TaksAccMaxSize = Convert.ToInt64(bi[2]);

                //TaksMinMoney = Convert.ToDouble(CDatabase.DBReadData("select minmoney from takscategory where id=" + AddTaksCategoryID.Text));
                //TaksMinMoneyText.Text = "最低金额为" + TaksMinMoney.ToString() + "元";
                UploadMaxFileText.Text = "最多可上传" + TaksAccNum.ToString() + "个文件";

                //如果文件数量超出就不显示上传
                if (Convert.ToUInt16(CDatabase.DBReadData("select count(*) from taksacc where linkid=" + EID.Text + " and type='Taks'")) >= TaksAccNum)
                {
                    UploadFilePanel.Visible = false;
                }

            }else
            {
                
                TaskViewLabe3.Text = tv[3];
                TaskViewLabe4.Text = Convert.ToDateTime(tv[4]).ToShortDateString() + "~" + Convert.ToDateTime(tv[5]).ToShortDateString();
                Task.FUNC su = new Task.FUNC();

                TaskViewLabe5.Text = su.SurplusDateTime(tv[4], tv[5]);
                TaskViewLabe6.Text = tv[3];
                TaskViewLabe7.Text = (Convert.ToUInt32(tv[3]) * 0.8).ToString();
                TaskViewLabe8.Text = tv[8];
                TaskViewLabel9.Text = tv[9];



                CDatabase.CloseConn();
                //**作品数
                TaskViewLabe9.Text = CDatabase.DBReadData("select Count(*) as c from TaksPlan where tid=" + Session["TaskViewID"].ToString());
            }  


            
            string[] tc =new string[2];
            tc = CDatabase.DBReader("select pid,category from taksCategory where id=" + tv[2], 2);
            if (tc[0] == "0")
            {
                TaskViewLabel2.Text = tc[1];
                ECategory.Text = tc[1];
            }
            else
            {
                TaskViewLabel2.Text= CDatabase.DBReadData("select category from takscategory where id=" + tc[0])+ "-" +tc[1];
                ECategory.Text = TaskViewLabel2.Text;
            }

            Task.FUNC cn=new Task.FUNC();

            cn.TaskViewCallNum(Session["TaskViewID"].ToString());
            

            //=============显示作品

            object RD2 = CDatabase.DBFillSelect("select * from TaksPlan where tid=" + Session["TaskViewID"].ToString() + " order by sdt desc");
            TaskViewDataList1.DataSource = RD2;
            TaskViewDataList1.DataBind();
            CDatabase.CloseConn();
        }
    }


    protected string SUBJECT(string id,string subject,string sdt,string edt)
    {

        return "第" + id + "号任务" + ":" + subject + " |  " + (Convert.ToDateTime(sdt)).ToShortDateString() + " ～ " + (Convert.ToDateTime(edt)).ToShortDateString();
    }

    protected string PLANNUM(string id)
    {
        return CDatabase.DBReadData("select count(*) as c from TaksPlan where tid=" + id);
    }

    protected string STATE(string f)
    {
        if (f == "true")
        {
            return "完成";
        }
        else
        {
            return "进行中";
        }
    }
    protected string CATEGORY(string CID)
    {
        return CDatabase.DBReadData("select category from takscategory where id="+CID);
    }


    //========================================
    protected string DESIGNER(string userid)
    {
        string user = CDatabase.DBReadData("select vipname from MemberVIP where id=" + userid);
        if (user != "-1")
        {
            return user;
        }
        else
        {
            return "临时";
        }
    }
    protected string VIEWIMG(string id)
    {
        return filepath+CDatabase.DBReadData("select filename from taksacc where linkid=" + id + " and type='Plan'");
    }
    //==============================================

    protected string MONEY(string money)
    {
        return "￥" + money;
    }

    protected string SURPLUS(string sdt, string edt)
    {
        DateTime t1 = Convert.ToDateTime(sdt);
        DateTime t2=Convert.ToDateTime(edt);
        if (t1.CompareTo(t2) >0)
        {
            return "-";
        }else{
           return DateDiff(Convert.ToDateTime(edt), Convert.ToDateTime(sdt));
        }
    }

    private string DateDiff(DateTime DateTime1, DateTime DateTime2)
    {
        string dateDiff = null; 
        try { TimeSpan ts1 = new TimeSpan(DateTime1.Ticks); TimeSpan ts2 = new TimeSpan(DateTime2.Ticks); TimeSpan ts = ts1.Subtract(ts2).Duration(); dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒"; }
        catch
        {
        } return dateDiff;
    }



    protected string Link(string c, string i)
    {
        return Request.ServerVariables["URL"].ToString()+"?category=" + c + "&categoryid=" + i;

    }

    protected void TaskListDropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }


    protected void TaskViewLinkButton1_Click(object sender, EventArgs e)
    {

        Response.Redirect(TaskAddPlanPath + TaskAddPlanFile + "?taskid="+Request["taskid"].ToString());

    }
    protected void UploadFileKey_Click(object sender, EventArgs e)
    {
        string size = "0";
        UploadTaksAccMessage.Visible = true;

        if (!TaksFileUpload1.HasFile)
        {
            UploadTaksAccMessage.Text = "请选择上传[" + TaksAccAtt + "]类型的文件．dv" + TaksFileUpload1.FileName;
        }
        else
        {
            try
            {
                string ext = (System.IO.Path.GetExtension(TaksFileUpload1.FileName).ToLower()).Replace(".", "");
                if (TaksAccAtt.IndexOf(ext) < 0 && TaksFileUpload1.HasFile)
                {
                    UploadTaksAccMessage.Text = "文类型不许可，请上传[" + TaksAccAtt + "]类型的文件．";

                }
                else
                {
                    size = TaksFileUpload1.PostedFile.ContentLength.ToString();

                    if (Convert.ToInt64(size) > TaksAccMaxSize)
                    {

                        UploadTaksAccMessage.Text = "文件超过" + TaksAccMaxSize.ToString() + "b字节,请进行文件压缩．";
                    }
                    else
                    {
                        UploadTaksAccMessage.Visible = false;


                        DateTime dt = DateTime.Now;
                        string filename = dt.Ticks.ToString();//用公元以来的100毫秒为记录.

                        Task.FUNC f = new Task.FUNC();
                        string savepath = Server.MapPath(f.filepath + filename + "." + ext);
                        TaksFileUpload1.SaveAs(savepath);
                        CDatabase.DBUpdate("insert into TaksAcc (linkid,UserID,sort,type,filename,fileAtt,filesize)values(" + EID.Text + "," + EUID.Text + ",0,'Taks','" + filename + "." + ext + "','" + ext + "'," + size + ")");
                        string nownum;
                        nownum = CDatabase.DBReadData("select Count(*) as c from taksacc where linkid=" + EID.Text + " and type='Taks'");
                        if (Convert.ToInt16(nownum) >= TaksAccNum)
                        {
                            UploadFilePanel.Visible = false;
                        }
                        readfilelist(EID.Text);
                    }
                }
            }
            catch
            {
                UploadTaksAccMessage.Text = "文类上传失败，请上传[" + TaksAccAtt + "]类型的文件,并且大小不超过" + TaksAccMaxSize + "b．";
            }
        }
    }

    protected void EditCategoryKey_Click(object sender, EventArgs e)
    {

    }
    protected void EGridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
        {

            e.Row.Cells[0].Visible = false;
            e.Row.Cells[1].Visible = false;

        } 
    }
    protected void EGridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Task.FUNC f = new Task.FUNC();
        string id = EGridView1.Rows[e.RowIndex].Cells[0].Text;
        string file = Server.MapPath(f.filepath + EGridView1.Rows[e.RowIndex].Cells[1].Text);

        if (File.Exists(file))
        {
            File.Delete(file);
        }


        CDatabase.DBUpdate("delete from taksacc where id=" + id);

        //UploadTaksAccMessage.Visible = true;
        //UploadTaksAccMessage.Text = file;
        UploadTaksAccMessage.Visible = false;
        readfilelist(EID.Text);
        UploadFilePanel.Visible = true;
    }
}
