using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using LitJson;

public partial class Customs_Base_CheckUpCustom : System.Web.UI.Page
{
    public string UserArea = "Application";
    public string AppItem = eParameters.QueryString("AppItem");
    public string modelid = eParameters.QueryString("modelid");
    public string id = eParameters.QueryString("id");
    eUser user;
    eModel model;
    public DataRow _cur = null;
    public DataRow cur
    {
        get
        {
            if (_cur == null)
            {
                DataTable tb = eBase.a_eke_sysCheckUps.Clone();
                _cur = tb.NewRow();
            }
            return _cur;
        }
    }
    public string options = "";
    public int backCount = 0;//返回流程数量

    int height = 210;
    public string flowdef = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["UserArea"] != null) UserArea = Request.QueryString["UserArea"].ToString();

        user = new eUser(UserArea);
        user.Check();
        model = new eModel();
        model.Action = "checkup";
        eDataBase db = model.DataBase;
        string _pk = db.getPrimaryKey("a_eke_sysCheckupRecords");
        if (_pk.Length == 0) db = eConfig.DefaultDataBase;
        DataTable dt = model.eForm.readData;
        if (dt.Rows.Count == 0) eResult.Message(new { success = 1, errcode = "-1", message = "数据不存在!" });
        DataRow dr = dt.Rows[0];
        if (!dr.Table.Columns.Contains("CheckupCode")) eResult.Message(new { success = 1, errcode = "-1", message = "数据没设置审核流程!" });
        string CheckupCode = dr["CheckupCode"].ToString();
        if (CheckupCode.Length == 0) eResult.Message(new { success = 1, errcode = "-1", message = "当前编码为空!" });



        bool self = false;
        #region 填报人提交
        if (dr.Contains("CheckupCode") && dr["CheckupCode"].ToString().ToLower() == "edit")
        {
            if (dr.Contains("adduser") && user.ID == dr["adduser"].ToString())
            {
                self = true;
            }
            else
            {
                if (dr.Contains("UserID") && user.ID == dr["UserID"].ToString())
                {
                    self = true;
                }
            }
            if (self)
            {
                cur["showState"] = 0;
                cur["showIdea"] = 0;
                cur["CheckMC"] = "填报人提交";
                cur["Text"] = "提交";
                cur["CheckCode"] = "submit";
                flowdef = "1";
            }
        }
        #endregion
        if (!self && dr.Contains("checkupUserID") && dr["checkupUserID"].ToString().Length > 0)
        {
            string userid = dr["checkupUserID"].ToString();
            dynamic chkuser = new eViewObject();
            chkuser = eBase.DataBase.getValues("select XM,CheckUPName,checkupRole,checkupType from a_eke_sysUsers where UserID='" + userid + "'");
            if (chkuser.checkupRole.Length == 0) chkuser.checkupRole = chkuser.CheckUPName;
            if (chkuser.checkupRole.Length == 0) chkuser.checkupRole = chkuser.XM;
            if (chkuser.checkupType.Length == 0) chkuser.checkupType = "审核";

            cur["showState"] = 1;
            cur["showIdea"] = 1;
            cur["CheckMC"] = chkuser.checkupRole + chkuser.checkupType;
            cur["Text"] = chkuser.checkupType;
            cur["CheckCode"] = "checkup";

            string sql = "select userid,XM,CheckUPName,checkupRole from a_eke_sysUsers where UserID in(";
            sql += "select DISTINCT UserID from a_eke_sysCheckupRecords where CheckupContentId ='" + id + "' and UserID!='" + user.ID + "' and CheckupCode!='submit' and CheckupState=1";
            sql += ")";

            backCount = 1;
            DataTable _dt = eBase.DataBase.getDataTable(sql);
            options = "<option value=\"\" selected>请选择</option>\r\n";
            options += "<option value=\"" + dr["addUser"].ToString() +"\">填报人</option>\r\n";
            foreach (DataRow _dr in _dt.Rows)
            {
                string checkupRole = _dr["checkupRole"].ToString();
                if (checkupRole.Length == 0) checkupRole = _dr["CheckUPName"].ToString();
                if (checkupRole.Length == 0) checkupRole = _dr["XM"].ToString();
                options += "<option value=\"" + _dr["userid"].ToString() + "\">" + checkupRole + "</option>\r\n";
            }
        }

        #region 审批
        #region 作废
        if (Request.QueryString["act"] != null)
        {
            string state = eParameters.Form("f1");
            if (state == "3")
            {
                string idea = "无";
                if (eParameters.Form("f2").Length > 0) idea = eParameters.Form("f2");
                #region 审批记录
                eTable etb = new eTable("a_eke_sysCheckupRecords", user);
                etb.DataBase = db;// model.DataBase;
                if (user["siteid"].Length > 0) etb.Fields.Add("SiteID", user["siteid"]);
                etb.Fields.Add("UserID", user.ID);
                if (modelid.Length > 0) etb.Fields.Add("modelid", modelid);
                etb.Fields.Add("Checkuptype", model.ModelInfo["code"].ToString());
                etb.Fields.Add("CheckupContentId", id);
                etb.Fields.Add("CheckupCode", cur["CheckCode"].ToString());
                etb.Fields.Add("CheckupText", cur["CheckMC"].ToString());
                etb.Fields.Add("CheckupIdea", idea);
                etb.Fields.Add("CheckupState", state);
                etb.Add();
                #endregion
                #region 被审批信息
                etb = new eTable(model.ModelInfo["code"].ToString(), user);
                etb.DataBase = model.DataBase;
                etb.Fields.Add("CheckupCode", "Stop");
                etb.Fields.Add("CheckupText", "作废");
                etb.Where.Add(model.eForm.primaryKey + "='" + id + "'");
                etb.Update();
                #endregion
                eResult.Message(new { success = 1, errcode = "0", message = "作废成功!" });
            }
        }
        #endregion
        if (Request.QueryString["act"] != null && Request.QueryString["act"].ToString().ToLower() == "checkup")
        {
            #region 审批记录
            string idea = "无";
            string state = "1";
            if (eParameters.Form("f1").Length > 0) state = eParameters.Form("f1");
            if (eParameters.Form("f2").Length > 0) idea = eParameters.Form("f2");
            string SignFile = eParameters.Form("SignFile");
            eTable etb = new eTable("a_eke_sysCheckupRecords", user);
            etb.DataBase = db;// model.DataBase;
            if (user["siteid"].Length > 0) etb.Fields.Add("SiteID", user["siteid"]);
            etb.Fields.Add("UserID", user.ID);
            if (modelid.Length > 0) etb.Fields.Add("modelid", modelid);
            etb.Fields.Add("Checkuptype", model.ModelInfo["code"].ToString());
            etb.Fields.Add("CheckupContentId", id);
            etb.Fields.Add("CheckupCode", cur["CheckCode"].ToString());
            etb.Fields.Add("CheckupText", cur["CheckMC"].ToString());
            etb.Fields.Add("CheckupIdea", idea);
            etb.Fields.Add("CheckupState", state);
            if (SignFile.Length > 0) etb.Fields.Add("SignFile", SignFile);

            if (dr.Contains("CheckupLevel") && etb.ColumnCollection.ContainsKey("CheckupLevel"))
            {
                etb.Fields.Add("CheckupLevel", Convert.ToInt32(dr["CheckupLevel"]));
            }
            etb.Add();
            //eBase.AppendLog(etb.addSQL);
            #endregion

            #region 被审批信息
            etb = new eTable(model.ModelInfo["code"].ToString(), user);
            etb.DataBase = model.DataBase;
            if (state == "1") //通过
            {
                string flow = eParameters.Form("flow");//0，结束流程，1，继续提交
                if (flow == "0")
                {
                    etb.Fields.Add("checkupUserID", null);
                    etb.Fields.Add("CheckupCode", "Pass");
                    etb.Fields.Add("CheckupText", "审批通过");
                }
                else
                {
                    string userid = eParameters.Form("userid");
                    dynamic chkuser = new eViewObject();
                    chkuser = eBase.DataBase.getValues("select XM,CheckUPName,checkupRole,checkupType from a_eke_sysUsers where UserID='" + userid + "'");                   
                    if (chkuser.checkupRole.Length == 0) chkuser.checkupRole = chkuser.CheckUPName;
                    if (chkuser.checkupRole.Length == 0) chkuser.checkupRole = chkuser.XM;
                    if (chkuser.checkupType.Length == 0) chkuser.checkupType = "审核";


                    etb.Fields.Add("checkupUserID", userid);
                    etb.Fields.Add("CheckupCode", "WaitCheckup");
                    etb.Fields.Add("CheckupText", "等待" + chkuser.checkupRole + chkuser.checkupType);
                }
                if (dr.Contains("CheckupLevel")) etb.Fields.Add("CheckupLevel", Convert.ToInt32(dr["CheckupLevel"]) + 1);
                etb.Where.Add(model.eForm.primaryKey + "='" + id + "'");
                etb.Update();
            }
            else //不通过
            {
                string backPress = eParameters.Form("f3");
                if (backPress == dr["addUser"].ToString())
                {
                    etb.Fields.Add("checkupUserID", null);
                    etb.Fields.Add("CheckupCode", "Edit");
                    etb.Fields.Add("CheckupText", "返回填报人");
                }
                else
                {
                    string userid = eParameters.Form("userid");
                    dynamic chkuser = new eViewObject();
                    chkuser = eBase.DataBase.getValues("select XM,CheckUPName,checkupRole,checkupType from a_eke_sysUsers where UserID='" + userid + "'");
                    if (chkuser.checkupRole.Length == 0) chkuser.checkupRole = chkuser.CheckUPName;
                    if (chkuser.checkupRole.Length == 0) chkuser.checkupRole = chkuser.XM;
                    if (chkuser.checkupType.Length == 0) chkuser.checkupType = "审核";


                    etb.Fields.Add("checkupUserID", userid);
                    etb.Fields.Add("CheckupCode", "WaitCheckup");
                    etb.Fields.Add("CheckupText", "返回" + chkuser.checkupRole);
                }
                etb.Where.Add(model.eForm.primaryKey + "='" + id + "'");
                etb.Update();

               

            }

            if (dr.Contains("UserIDS"))
            {
                string _sql = "update " + model.ModelInfo["code"].ToString() + " set UserIDS=UserIDS + '," + user.ID + "' where " + model.eForm.primaryKey + "='" + id + "' and UserIDS not like '%" + user.ID + "%'";//
                eBase.DataBase.Execute(_sql);
                //eBase.AppendLog(_sql);
            }
            //eBase.AppendLog(etb.updateSql);

            HttpContext.Current.Items["ID"] = id;
            model.CheckUp_callBack();//审核回调-传递给自定义程序
            model.ExecuteAction("checkup", null, id);
            #endregion
            eResult.Message(new { success = 1, errcode = "0", message = "审核成功!" });
        }
        #endregion
       
    }
    protected override void Render(HtmlTextWriter writer)
    {
        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
        base.Render(htmlWriter);
        htmlWriter.Close();
        htmlWriter.Dispose();
        string content = stringWriter.ToString();
        stringWriter.Close();
        stringWriter.Dispose();
        #region 窗口高度计算
        if (cur["showState"].ToString() == "1") height += 30 + 30;
        if (cur["showIdea"].ToString() == "1") height += 100;
        if (cur["showIdea"].ToString() == "2") height += 180;
        #endregion

        JsonData json = new JsonData();
        json.Add("success", "1");
        json.Add("errcode", "0");
        json.Add("message", "加载成功");
        json.Add("title", cur["CheckMC"].ToString());
        json.Add("text", cur["Text"].ToString());

        json.Add("height", height.ToString());
        json.Add("html", eBase.encode(content));
        Response.Clear();
        Response.Write(json.ToJson());
        Response.End();
    }
}