using System;
using System.Collections;
using System.Data;
using System.Text;
using Business.FileFlow.Entity;
using Business.FileFlow.Vo;
using Business.System.User.Vo;
using Common;
using LogisticsSystem.Control;
using LogisticsSystem.Control.Helper;

namespace LogisticsSystem.SysMain.FileFlow
{
    public partial class FlowListSrv : SrvBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var type = Request.QueryString["type"];

            if (!CheckUserLogin()) return;

            if (!CheckUserDo("用户执行--公文列表管理", type))
            {
                DataRow[] row = InitHelper.Ops.Select("code='" + type + "'");
                if (row.Length <= 0)
                {
                    Response.Write("用户没有权限操作");
                    return;
                }
                Response.Write("用户没有权限操作:" + row[0]["name"]);
                return;
            }

            //根据类型 执行相关操作
            switch (type)
            {
                case "flowListSave":        //提交公文申请
                    FlowListSave();
                    break;
                case "GetAllFlowList":      //获取我的申请列表
                    GetAllFlowList();
                    break;
                case "flowListUpdate":       //审批公文
                    FlowListUpdate();
                    break;
                case "FlowCont":            //获取公文详细信息
                    FlowCont();
                    break;
                case "MyFlowList":          //获取我的审批列表
                    MyFlowList();
                    break;
                default:
                    Response.Write("");
                    break;
            }
        }

        /// <summary>
        /// 获取公文列表表头
        /// </summary>
        /// <returns>公文列表表头</returns>
        private StringBuilder FlowListHead(string tableid)
        {
            var tableHead = new StringBuilder();
            tableHead.Append("<table class=\"standerTable\" id=\"" + tableid + "\"><thead><td></td>");
            tableHead.Append("<td>名称</td>");
            tableHead.Append("<td>流程名称</td>");
            tableHead.Append("<td>当前步骤</td>");
            tableHead.Append("<td>上次修改时间</td>");
            tableHead.Append("<td>提交人</td>");
            tableHead.Append("<td>是否通过</td>");
            tableHead.Append("<td>是否完成</td>");
            tableHead.Append("<td>附件</td></thead>");
            return tableHead;
        }


        private void GetAllFlowList()
        {
            //获取表头
            StringBuilder table = FlowListHead("flowListSTD");
            //获取公文列表数据
            DataTable data = new FlowListVo().AllFlowList(Request.QueryString["sT"], Session["Userid"].ToString());

            var hashtable = new Hashtable();
            hashtable["none"] = "actionIDs";

            //整合数据表
            VoCusTable(table, data, CusTableHash(data), "id", hashtable);
            //保存附件地址
            SAddr(data);
            //返回数据
            Response.Write(table.ToString());
        }

        /// <summary>
        /// 新增公文列表信息
        /// </summary>
        private void FlowListSave()
        {
            var flowList = new FlowListEty();
            InsertFlowListEty(flowList);
            var result = new FlowListVo().InsertFlowList(flowList);
            if (result.Equals(string.Empty))
            {
                Session["upload"] = new Hashtable();
                Response.Write("true");
            }
            else
            {
                Response.Write(result);
            }
        }

        /// <summary>
        /// 修改公文列表信息
        /// </summary>
        private void FlowListUpdate()
        {
            var flowList = new FlowListEty();
            UpdateFlowListEty(flowList);
            var result = new FlowListVo().UpdateFlowList(flowList);
            Response.Write(result.Equals(string.Empty) ? "true" : result);
        }

        /// <summary>
        /// 删除公文列表信息
        /// </summary>
        private void FlowListDel()
        {
            string id = "'";
            string[] ids = Request.QueryString["id"].Split(',');
            id += string.Join("','", ids) + "'";
            var result = new FlowListVo().DelFlowList(id);
            Response.Write(result.Equals(string.Empty) ? "true" : result);
        }


        /// <summary>
        /// 实体类FlowListEty 赋值
        /// </summary>
        /// <returns>bool</returns>
        private void InsertFlowListEty(FlowListEty flowList)
        {

            flowList.Name = Request.QueryString["name"];
            flowList.Fcontent = Request.QueryString["cont"];
            flowList.FlowId = Request.QueryString["fid"];
            flowList.Remark = "";
            flowList.Id = Com.NewGuid();
            flowList.AddTime = DateTime.Now;
            flowList.UpdateUserId = Session["Userid"].ToString();
            flowList.AddUserId = Session["Userid"].ToString();
            flowList.LastTime = DateTime.Now;
            flowList.DelFlag = false;
            flowList.IsEnd = false;
            flowList.IsPass = false;
            flowList.SAddr = GetUploadFiles();
            flowList.ActionId = 0;
        }

        /// <summary>
        /// 实体类FlowListEty 赋值 (更新)
        /// </summary>
        /// <returns>bool</returns>
        private void UpdateFlowListEty(FlowListEty flowList)
        {
            var flow = new FlowVo();
            flowList.Remark = Request.QueryString["remark"];
            flowList.Id = Request.QueryString["id"];
            flowList.UpdateUserId = Session["Userid"].ToString();
            flowList.LastTime = DateTime.Now;

            FlowListEty temp = new FlowListVo().GetFlowContById(flowList.Id);
            Hashtable action = flow.FlowAction(flow.GetAction(temp.FlowId));

            flowList.AddTime = temp.AddTime;
            flowList.Name = temp.Name;
            flowList.FlowId = temp.FlowId;
            flowList.ActionId = temp.ActionId;
            flowList.DelFlag = temp.DelFlag;
            flowList.AddUserId = temp.AddUserId;
            flowList.Fcontent = temp.Fcontent;
            flowList.SAddr = temp.SAddr;

            if (Request.QueryString["isPass"] == "pass")
            {
                if (temp.ActionId == action.Count - 1)
                {
                    //该公文 执行最后一步操作, 结束
                    flowList.IsPass = true;
                    flowList.IsEnd = true;
                    flowList.ActionId = temp.ActionId;
                }
                else
                {
                    //该公文 执行下一步操作, 未结束
                    flowList.IsPass = false;
                    flowList.IsEnd = false;
                    flowList.ActionId = temp.ActionId + 1;
                }
            }
            else
            {
                //该公文 不通过, 结束
                flowList.IsPass = false;
                flowList.IsEnd = true;
                flowList.ActionId = temp.ActionId;
            }
        }

        /// <summary>
        /// 获取上传的文件路径
        /// </summary>
        /// <returns></returns>
        private string GetUploadFiles()
        {
            var hash = (Hashtable)Session["upload"];
            string result = string.Empty;
            if (hash.Count <= 0)
            {
                return result;
            }
            foreach (string addr in hash.Values)
            {
                result += addr + ",";
            }
            return result.TrimEnd(',');
        }

        /// <summary>
        /// 保存流程列表的附件地址
        /// </summary>
        /// <param name="data">流程列表</param>
        /// <returns>流程列表ID关联附件地址的哈希表</returns>
        private void SAddr(DataTable data)
        {
            var hash = (Hashtable)Session["SAddr"];
            foreach (DataRow row in data.Rows)
            {
                if (hash.ContainsKey(row["id"].ToString())) continue;
                hash[row["id"].ToString()] = row["sAddr"];
            }
            Session["SAddr"] = hash;
        }

        /// <summary>
        /// 获取定制表的哈希表
        /// </summary>
        /// <param name="data">流程列表</param>
        /// <returns>定制表的哈希表</returns>
        private Hashtable CusTableHash(DataTable data)
        {
            var flowVo = new FlowVo();
            DataTable actions = new ActionVo().AllAction("");       //读取所有流程操作
            var hash = new Hashtable();
            hash["id"] = new Hashtable();
            hash["actionid"] = new Hashtable();
            hash["isPass"] = new Hashtable();
            hash["isEnd"] = new Hashtable();
            hash["sAddr"] = new Hashtable();
            foreach (DataRow row in data.Rows)
            {
                var tempid = (Hashtable)hash["id"];
                var tempactionid = (Hashtable)hash["actionid"];
                var tempisPass = (Hashtable)hash["isPass"];
                var tempisEnd = (Hashtable)hash["isEnd"];
                var tempsAddr = (Hashtable)hash["sAddr"];

                ActionEty actionEty = flowVo.NowActionId(row["actionIDs"].ToString(), actions,
                                                         row["actionid"].ToString());

                tempid[row["id"]] = "<input type=\"checkbox\" value=\"" + row["id"] + "\">";
                tempactionid[row["id"]] = actionEty.Name;
                tempisPass[row["id"]] = (bool)row["isPass"] ? "是" : "否";
                tempisEnd[row["id"]] = (bool)row["isEnd"] ? "是" : "否";
                tempsAddr[row["id"]] = "<input class=\"downfile\" type=\"button\" value=\"下载\">";

                hash["id"] = tempid;
                hash["actionid"] = tempactionid;
                hash["isPass"] = tempisPass;
                hash["isEnd"] = tempisEnd;
                hash["sAddr"] = tempsAddr;
            }
            return hash;
        }


        private void FlowCont()
        {
            var flow = new FlowVo();
            var userVo = new UserVo();

            DataTable actions = new ActionVo().AllAction("");       //读取所有流程操作

            FlowListEty listEty = new FlowListVo().GetFlowContById(Request.QueryString["fid"]);
            FlowEty flowEty = flow.GetFlowById(listEty.FlowId);

            var html = new StringBuilder();
            html.Append("<div style=\"height:550px; overflow:auto; \"><table style=\"width:100%\">");
            html.Append("<tr><td>标题:</td><td>" + listEty.Name + "</td></tr>");
            html.Append("<tr><td>流程:</td><td>" + flowEty.Name + "</td></tr>");
            html.Append("<tr><td>操作:</td><td>" + flow.ActionNString(flowEty.ActionIDs, actions, listEty.ActionId) + "</td></tr>");
            html.Append("<tr><td>提交人:</td><td>" + userVo.UserName(listEty.AddUserId) + "</td></tr>");
            html.Append("<tr><td>提交时间:</td><td>" + listEty.AddTime.ToString() + "</td></tr>");
            html.Append("<tr><td>最近审批时间:</td><td>" + listEty.LastTime.ToString() + "</td></tr>");
            html.Append("<tr><td>是否通过:</td><td>" + (listEty.IsPass ? "是" : "否") + "</td></tr>");
            html.Append("<tr><td>是否结束:</td><td>" + (listEty.IsEnd ? "是" : "否") + "</td></tr>");
            html.Append("<tr><td>内容:</td><td style=\"border:1px solid Highlight; width:80%;\"><div style=\"height:200px; overflow:auto;\">" + listEty.Fcontent + "</div></td></tr>");

            if (Request.QueryString["style"] == "apply")
            {
                html.Append("<tr><td>审批回复:</td><td style=\"border:1px solid Highlight\"><div style=\"height:100px; overflow:auto;\">" + listEty.Remark + "</div></td></tr>");
                html.Append("</table></div>");
            }
            else if (Request.QueryString["style"] == "approval")
            {
                html.Append("<tr><td>审批回复:</td><td style=\"border:1px solid Highlight\"><textarea style=\"width:98%\" id=\"approveRe\" rows=\"5\">" + listEty.Remark + "</textarea></td></tr></table>");
                html.Append("<div style=\" text-align: center; width:100%;\"><input style=\" margin:1% 5%;\" type=\"button\" id=\"pass\" value=\"通过\"/><input style=\" margin:1% 5%;\" type=\"button\" id=\"reject\" value=\"不通过\"/></div>");
                html.Append("</div>");
            }


            Response.Write(html.ToString());
        }


        private void MyFlowList()
        {
            var addr = (Hashtable)Session["SAddr"];
            var flow = new FlowVo();
            DataTable actions = new ActionVo().AllAction("");       //读取所有流程操作
            //获取表头
            StringBuilder table = FlowListHead("approvalSTD");
            //获取公文列表数据
            Hashtable mylist = new FlowListVo().MyList(Session["Userid"].ToString(), Request.QueryString["sT"]);

            foreach (FlowListEty flowList in mylist.Values)
            {
                table.Append("<tr><td><input type=\"checkbox\" value=\"" + flowList.Id + "\"></td>");
                table.Append("<td>" + flowList.Name + "</td>");
                table.Append("<td>" + flow.GetFlowNameById(flowList.FlowId) + "</td>");
                table.Append("<td>" + flow.NowActionId(flow.GetAction(flowList.FlowId), actions, flowList.ActionId.ToString()).Name + "</td>");
                table.Append("<td>" + flowList.LastTime + "</td>");
                table.Append("<td>" + flowList.AddUserId + "</td>");
                table.Append("<td>" + (flowList.IsPass ? "是" : "否") + "</td>");
                table.Append("<td>" + (flowList.IsEnd ? "是" : "否") + "</td>");
                table.Append("<td><input class=\"downfile\" type=\"button\" value=\"下载\"></td></tr>");
                if (addr.ContainsKey(flowList.Id)) continue;
                addr[flowList.Id] = flowList.SAddr;
            }
            table.Append("</table>");

            Session["SAddr"] = addr;

            //返回数据
            Response.Write(table.ToString());
        }
    }
}