using Sugar.Enties;
using SqlSugar;
using System;
using System.Collections.Generic;
using WebAPIBase.Utils;
using Newtonsoft.Json;
using System.Data;
public class WorkFlowProcedureManager : DbContext<WorkFlowProcedure>
{
    private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    //当前类已经继承了 DbContext增、删、查、改的方法

    //这里面写的代码不会给覆盖,如果要重新生成请删除 WorkFlowProcedureManager.cs
    /// <summary>
    /// 根据流程名，项目编号及是否活动获取可使用的工作流程审核列表
    /// </summary>
    /// <param name="procedureName"></param>
    /// <param name="projectCode"></param>
    /// <param name="activity"></param>
    public List<WorkFlowProcedure> GetWorkFlowProcedureList(string procedureName, string projectCode, int activity)
    {
        string sql = $"SELECT  * from WorkFlowProcedure WHERE ( ProcedureName='{procedureName}' AND (','+ProjectCode+',' LIKE '%,{projectCode},%' or projectcode ='' or projectcode is null) AND Activity={activity}) or ProcedureCode ='0'";
        var list = Db.Ado.SqlQuery<WorkFlowProcedure>(sql);
        return list;
    }
    /// <summary>
    /// 流程实例保存
    /// </summary>
    /// <returns></returns>
    public string WorkFlowSave(WorkFlowDTO dto)
    {
        logger.Info($"【WorkFlowSave】dto:{JsonConvert.SerializeObject(dto)}");
        string msg = "";           //返回信息
        string exist = "";        //是否存在
        var isAudit = false;      //是否可审批
        var isNew = true;       //因为是审批流程第一步，默认为新单据
        string sql = "";
        var operatorState = ModuleState.Operable;      //状态设置为可操作
        try
        {
            WorkFlowCase workFlowCase = new WorkFlowCase();
            WorkFlowAct workFlowAct = new WorkFlowAct();
            WorkFlowActUser workFlowActUser = new WorkFlowActUser();
            //流程路由
            var router = Db.Ado.SqlQuerySingle<WorkFlowRouter>($"SELECT TOP 1 * FROM dbo.WorkFlowRouter WHERE ProcedureCode='{dto.ProcedureCode}' ORDER BY RouterCode");
            var procedurePropertyList = Db.Ado.SqlQuery<WorkFlowProcedureProperty>($"select * from WorkFlowProcedureProperty where ProcedureCode='{dto.ProcedureCode}'  ");
            var now = DateTime.Now;

            var title = getTitle(dto);


            var workFlowProcedure = GetById(dto.ProcedureCode);
            if (workFlowProcedure == null)
            {
                msg = "流程不存在";
                return msg;
            }

            //流程实例赋值
            //workFlowCase.ProjectCode = dto.ProjectCode;    //不赋值
            workFlowCase.ProcedureCode = dto.ProcedureCode;
            workFlowCase.ApplicationCode = dto.ApplicationCode;
            workFlowCase.SourceUnitCode = "";   //赋值为空
            workFlowCase.SourceUserCode = dto.UserCode;
            workFlowCase.CreateDate = now;
            workFlowCase.Status = "Begin";
            workFlowCase.ProcedureXml = workFlowProcedure.ProcedureXml;
            workFlowCase.ApplicationPath = workFlowProcedure.ApplicationPath;
            workFlowCase.ApplicationInfoPath = workFlowProcedure.ApplicationInfoPath;
            workFlowCase.ProcedureName = workFlowProcedure.ProcedureName;
            workFlowCase.Description = workFlowProcedure.Description;

            //流程任务实例赋值
            var taskList = GetWorkFlowTasks(dto.ProcedureCode);
            workFlowAct.ProcedureCode = dto.ProcedureCode;
            workFlowAct.ActUserCode = dto.UserCode;
            workFlowAct.FromTaskCode = router.FromTaskCode;
            workFlowAct.FromTaskName = taskList.Find(m => m.TaskCode == router.FromTaskCode).TaskName;
            workFlowAct.FromDate = now;
            workFlowAct.FromUserCode = dto.UserCode;
            workFlowAct.ToTaskCode = router.ToTaskCode;
            workFlowAct.ToTaskName = taskList.Find(m => m.TaskCode == router.ToTaskCode).TaskName;
            workFlowAct.Status = "DealWith";
            workFlowAct.SignDate = now;
            workFlowAct.ActType = 0;
            workFlowAct.Copy = 0;
            workFlowAct.IsSleep = workFlowAct.Copy != 1 ? 1 : 0;
            workFlowAct.ApplicationCode = dto.ApplicationCode;
            workFlowAct.ApplicationSubject = "";

            workFlowAct.IsSilenceCopy = 0;
            workFlowAct.LimitHour = 0;

            //流程任务实例用户赋值
            workFlowActUser.UserCode = dto.UserCode;
            workFlowActUser.IsAgent = 0;



            var unitManager = new UnitManager();
            Db.BeginTran();

            //流程实例赋值保存
            sql = $"SELECT 0 FROM workflowcase WHERE ApplicationCode='{dto.ApplicationCode}' AND ProcedureCode='{dto.ProcedureCode}'";
            exist = Db.Ado.GetString(sql);
            if (exist.IsNotNullAndEmpty())
            {
                Db.RollbackTran();
                msg = $"本业务单据已存在未结束的{dto.ProcedureName}流程";
                return msg;
            }

            var casecode = unitManager.GetSysCodeValue("CaseCode");
            workFlowCase.CaseCode = casecode;
            var row = Db.Insertable(workFlowCase).ExecuteCommand();
            logger.Info($"【WorkFlowSave】workFlowCase.CaseCode:{workFlowCase.CaseCode},执行结果：{row}");

            //流程任务实例赋值保存
            sql = $"SELECT 0 FROM WorkFlowAct WHERE CaseCode='{casecode}'";
            exist = Db.Ado.GetString(sql);
            if (exist.IsNotNullAndEmpty())
            {
                Db.RollbackTran();
                msg = $"本业务单据已存在未结束的{dto.ProcedureName}流程";
                return msg;
            }
            var actCode = unitManager.GetSysCodeValue("ActCode");
            workFlowAct.ActCode = actCode;
            workFlowAct.CaseCode = casecode;
            var row1 = Db.Insertable(workFlowAct).ExecuteCommand();
            logger.Info($"【WorkFlowSave】workFlowAct:{JsonConvert.SerializeObject(workFlowAct)},执行结果：{row1}");
            //流程任务实例用户赋值保存
            sql = $"SELECT 0 FROM workFlowActUser WHERE CaseCode='{casecode}'";
            exist = Db.Ado.GetString(sql);
            if (exist.IsNotNullAndEmpty())
            {
                Db.RollbackTran();
                msg = $"本业务单据已存在未结束的{dto.ProcedureName}流程";
                return msg;
            }
            var actUserCode = unitManager.GetSysCodeValue("ActUserCode");
            workFlowActUser.ActUserCode = actUserCode;
            workFlowActUser.ActCode = actCode;
            workFlowActUser.CaseCode = casecode;
            var row2 = Db.Insertable(workFlowActUser).ExecuteCommand();
            logger.Info($"【WorkFlowSave】workFlowActUser:{JsonConvert.SerializeObject(workFlowActUser)},执行结果：{row2}");

            //流程意见赋值及保存
            sql = $"SELECT 0 FROM WorkFlowOpinion WHERE CaseCode='{casecode}'";
            exist = Db.Ado.GetString(sql);
            if (exist.IsNotNullAndEmpty())
            {
                Db.RollbackTran();
                msg = $"本业务单据已存在未结束的{dto.ProcedureName}流程";
                return msg;
            }
            var opinion = new WorkFlowOpinion();
            opinion.OpinionCode = unitManager.GetSysCodeValue("OpinionCode");
            opinion.ApplicationCode = actCode;
            opinion.ProcedureCode = dto.ProcedureCode;
            opinion.CaseCode = casecode;
            opinion.UserCode = dto.UserCode;
            opinion.OpinionText = "";
            opinion.OpinionDate = now;
            opinion.TaskCode = router.ToTaskCode;
            opinion.TaskID = taskList.Find(m => m.TaskCode == router.ToTaskCode).TaskID;
            opinion.OpinionConfirm = "";
            var row3 = Db.Insertable(opinion).ExecuteCommand();
            logger.Info($"【WorkFlowSave】WorkFlowOpinion:{JsonConvert.SerializeObject(opinion)},执行结果：{row3}");

            #region 流程属性实例赋值及保存
            var shenqingTask = taskList.Find(m => m.TaskCode == router.ToTaskCode);
            foreach (var item in procedurePropertyList)
            {
                var entity1 = new WorkFlowCaseProperty();
                entity1.WorkFlowCasePropertyCode = unitManager.GetSysCodeValue("WorkFlowCaseProperty");
                entity1.WorkFlowCaseCode = casecode;
                entity1.WorkFlowProcedurePropertyCode = item.WorkFlowProcedurePropertyCode;
                entity1.WorkFlowProcedurePropertyName = item.ProcedurePropertyName;
                entity1.Remak = "";
                if (isNew || operatorState == ModuleState.Operable)
                {
                    if (isNew)
                    {
                        if (item.ProcedurePropertyName == "申请人")
                        {
                            entity1.WorkFlowProcedurePropertyValue = dto.UserCode;
                        }
                        else if (item.ProcedurePropertyName == "流水号")
                        {
                            string NumberString = DateTime.Now.Year.ToString().Substring(2, 2);
                            int FlowNumberLenth = 6;
                            NumberString += unitManager.GetSysCodeValue(NumberString).Substring(6 - FlowNumberLenth, FlowNumberLenth);
                            entity1.WorkFlowProcedurePropertyValue = NumberString;
                        }
                        else if (item.ProcedurePropertyName == "表单部门")
                        {
                            entity1.WorkFlowProcedurePropertyValue = "";
                        }
                        else if (item.ProcedurePropertyName == "决策值")
                        {
                            entity1.WorkFlowProcedurePropertyValue = "";
                        }
                    }
                    if (operatorState == ModuleState.Operable)
                    {
                        if (item.ProcedurePropertyName == "工作缓急")
                        {
                            entity1.WorkFlowProcedurePropertyValue = dto.RateValue ?? "";
                        }
                        else if (item.ProcedurePropertyName == "经办人意见")
                        {
                            //保存经办人、日期 2019.8.22
                            string ApplyOpinion = dto.Opinion;
                            ApplyOpinion += "|" + dto.UserCode;
                            ApplyOpinion += "|" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            entity1.WorkFlowProcedurePropertyValue = ApplyOpinion;
                        }
                    }


                }




                if (item.ProcedurePropertyName == "主题")
                {
                    entity1.WorkFlowProcedurePropertyValue = title;
                }
                else if (item.ProcedurePropertyName == "项目代码")
                {
                    entity1.WorkFlowProcedurePropertyValue = dto.ProjectCode;
                }
                else if (item.ProcedurePropertyName == "项目部门")
                {
                    entity1.WorkFlowProcedurePropertyValue = dto.ProjectCode;
                }
                else if (item.ProcedurePropertyName == "业务类别")
                {
                    entity1.WorkFlowProcedurePropertyValue = "";
                }
                else if (item.ProcedurePropertyName == "业务部门")
                {
                    entity1.WorkFlowProcedurePropertyValue = dto.UnitCode;
                }

                if (shenqingTask.ModuleState.Contains("Hand"))
                {
                    if (item.ProcedurePropertyName == "手送资料")
                    {
                        entity1.WorkFlowProcedurePropertyValue = dto.Hand ?? "";
                    }

                }

                getWorkFlowProcedurePropertyValue(dto, item, entity1);


                var row4 = Db.Insertable(entity1).ExecuteCommand();
                logger.Info($"【WorkFlowSave】WorkFlowCaseProperty:{JsonConvert.SerializeObject(entity1)},执行结果：{row4}");
            }

            #endregion


            #region 获取单据状态，做相应判断，并更改单据状态

            var state = getSate(dto);
            //logger.Info($"【WorkFlowSave】sql查询状态:{sql},执行结果：{state}");
            if (state.IsNullOrEmpty())
            {
                Db.RollbackTran();
                return "要审核的单据不存在";
            }
            if (state != "0")
            {
                Db.RollbackTran();
                return "单据状态已改变，不能再次审核";
            }


            var row6 = changeState(dto);
            //logger.Info($"【WorkFlowSave】sql更新状态:{sql},执行结果：{row6}");
            #endregion

            Db.CommitTran();
            msg = actCode;
            logger.Info($"【WorkFlowSave】保存完成msg:{msg}");

            createPDF(dto, casecode, title);
            return msg;
        }
        catch (Exception ex)
        {
            Db.RollbackTran();
            msg = ex.Message;
            throw;
        }

    }


    /// <summary>
    /// 获取工作流程列表
    /// </summary>
    /// <param name="procedureCode"></param>
    /// <returns></returns>
    public List<WorkFlowTask> GetWorkFlowTasks(string procedureCode)
    {
        var sql = $"SELECT * FROM dbo.WorkFlowTask WHERE ProcedureCode='{procedureCode}' ORDER BY TaskID";
        var list = Db.Ado.SqlQuery<WorkFlowTask>(sql);
        return list;
    }

    #region  保存过程中进行的各种操作
    /// <summary>
    /// 获取标题
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    private string getTitle(WorkFlowDTO dto)
    {
        string sql = "";
        if (dto.ProcedureName == "现场签证申请单审核" || dto.ProcedureName == "设计变更申请单审核")
        {
            sql = $"SELECT RequisitionName FROM dbo.Requisition WHERE RequisitionCode='{dto.ApplicationCode}'";
        }
        else if(dto.ProcedureName == "签证审核")
        {
            sql = $"SELECT ViseName FROM dbo.Vise WHERE ViseCode='{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "进度报告审核")
        {
            sql = $"SELECT c.ProgressName+' -> '+b.NodeName  FROM pmProgressReport a INNER JOIN dbo.pmProgressNode b ON a.ProgressNodeId=b.id INNER JOIN dbo.pmProgress c ON a.ProgressId=c.Id WHERE a.id= {dto.ApplicationCode.ToInteger()}";
        }
        else if (dto.ProcedureName == "质量检查审批" || dto.ProcedureName == "安全检查审批" || dto.ProcedureName == "材料检查审批")
        {
            sql = $"SELECT projectname FROM dbo.SafeQualityCheck WHERE CheckCode = '{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "设计变更")
        {
            sql = $"SELECT DesignChangesName FROM dbo.DesignChanges WHERE DesignChangesCode = '{dto.ApplicationCode}'";
        }
        return Db.Ado.GetString(sql);
    }
    /// <summary>
    /// 获取单据状态
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    private string getSate(WorkFlowDTO dto)
    {
        var sql = "";
        if (dto.ProcedureName == "现场签证申请单审核" || dto.ProcedureName == "设计变更申请单审核")
        {
            sql = $"SELECT state FROM dbo.Requisition WHERE RequisitionCode='{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "签证审核")
        {
            sql = $"SELECT state FROM dbo.Vise WHERE ViseCode='{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "进度报告审核")
        {
            sql = $"SELECT state  FROM pmProgressReport   WHERE id= {dto.ApplicationCode.ToInteger()}";
        }
        else if (dto.ProcedureName == "质量检查审批" || dto.ProcedureName == "安全检查审批" || dto.ProcedureName == "材料检查审批")
        {
            sql = $"SELECT Status FROM dbo.SafeQualityCheck WHERE CheckCode = '{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "设计变更")
        {
            sql = $"SELECT state  FROM DesignChanges   WHERE DesignChangesCode= '{dto.ApplicationCode}'";
        }
        return Db.Ado.GetString(sql);
    }
    /// <summary>
    /// 给流程属性实例的WorkFlowProcedurePropertyValue赋值
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="item"></param>
    /// <param name="entity1"></param>
    private void getWorkFlowProcedurePropertyValue(WorkFlowDTO dto, WorkFlowProcedureProperty item, WorkFlowCaseProperty entity1)
    {
        var sql = "";
        if (dto.ProcedureName == "现场签证申请单审核" || dto.ProcedureName == "设计变更申请单审核")
        {
            sql = $"SELECT * FROM dbo.Requisition WHERE RequisitionCode='{dto.ApplicationCode}'";
            var model = Db.Ado.SqlQuerySingle<Requisition>(sql);
            if (item.ProcedurePropertyName == "暂估金额")
            {
                entity1.WorkFlowProcedurePropertyValue = model.TotalEstimateCash.ToString();
            }
            else if (item.ProcedurePropertyName == "关联合同信息")
            {
                entity1.WorkFlowProcedurePropertyValue = "";
            }
            else if (item.ProcedurePropertyName == "是否编辑过关联合同信息")
            {
                entity1.WorkFlowProcedurePropertyValue = "";
            }
        }
        else if (dto.ProcedureName == "签证审核")
        {
            sql = $"select * from Vise where ViseCode='{dto.ApplicationCode}'";
            var model = Db.Ado.SqlQuerySingle<Vise>(sql);
            if (item.ProcedurePropertyName == "签证金额")
            {
                entity1.WorkFlowProcedurePropertyValue = model.TotalCash.ToString();
            }
            else if (item.ProcedurePropertyName == "费用项信息")
            {
                entity1.WorkFlowProcedurePropertyValue = "";
            }
            else if (item.ProcedurePropertyName == "是否编辑过费用项信息")
            {
                entity1.WorkFlowProcedurePropertyValue = "";
            }
        }
        else if (dto.ProcedureName == "进度报告审核")
        {
            sql = $"SELECT * FROM pmProgressReport WHERE id={dto.ApplicationCode.ToInteger()}";
            var report = Db.Ado.SqlQuerySingle<pmProgressReport>(sql);
            if (item.ProcedurePropertyName == "进度")
            {
                entity1.WorkFlowProcedurePropertyValue = report.CompletePercent.ToString();
            }
            else if (item.ProcedurePropertyName == "实际开始时间")
            {
                entity1.WorkFlowProcedurePropertyValue = report.ActualStartDate == null ? "" : report.ActualStartDate.Value.ToString("yyyy-MM-dd");
            }
            else if (item.ProcedurePropertyName == "实际结束时间")
            {
                entity1.WorkFlowProcedurePropertyValue = report.ActualFinishDate == null ? "" : report.ActualFinishDate.Value.ToString("yyyy-MM-dd");
            }

        }
        else if (dto.ProcedureName == "质量检查审批" || dto.ProcedureName == "安全检查审批" || dto.ProcedureName == "材料检查审批")
        {
            //nothing to do
        }
        else if (dto.ProcedureName == "设计变更")
        {
            sql = $"select * from DesignChanges where DesignChangesCode='{dto.ApplicationCode}'";
            var model = Db.Ado.SqlQuerySingle<DesignChangesDTO>(sql);
            if (item.ProcedurePropertyName == "设计变更金额")
            {
                entity1.WorkFlowProcedurePropertyValue = model.TotalCash.ToString();
            }
            else if (item.ProcedurePropertyName == "费用项信息")
            {
                entity1.WorkFlowProcedurePropertyValue = "";
            }
            else if (item.ProcedurePropertyName == "是否编辑过费用项信息")
            {
                entity1.WorkFlowProcedurePropertyValue = "";
            }
        }
    }
    /// <summary>
    /// 改变流程审核单据状态
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    private int changeState(WorkFlowDTO dto)
    {
        var sql = "";
        if (dto.ProcedureName == "现场签证申请单审核" || dto.ProcedureName == "设计变更申请单审核")
        {
            //更新签证申请单表状态
            sql = $"update dbo.Requisition set state =1   WHERE RequisitionCode='{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "签证审核")
        {
            sql = $"update  dbo.Vise set state='1' WHERE ViseCode='{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "进度报告审核")
        {
            sql = $"update dbo.pmProgressReport set state = 1  WHERE id={dto.ApplicationCode.ToInteger()}";
        }
        else if (dto.ProcedureName == "质量检查审批" || dto.ProcedureName == "安全检查审批" || dto.ProcedureName == "材料检查审批")
        {
            sql = $"update dbo.SafeQualityCheck set status = 1  WHERE checkcode='{dto.ApplicationCode}'";
        }
        else if (dto.ProcedureName == "设计变更")
        {
            sql = $"update dbo.DesignChanges set state = 1  WHERE DesignChangesCode='{dto.ApplicationCode}'";
        }
        return Db.Ado.ExecuteCommand(sql);
    }
    /// <summary>
    /// 根据单据不同创建pdf
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="casecode"></param>
    /// <param name="title"></param>
    private void createPDF(WorkFlowDTO dto, string casecode, string title)
    {
        if (WorkFlowPDFHelper.CheckServerPdfFolder() != "")
        {
            if (dto.ProcedureName == "现场签证申请单审核" || dto.ProcedureName == "设计变更申请单审核")
            {
                createPDFfileByRequisition(casecode, dto);
            }
            else if (dto.ProcedureName == "签证审核")
            {
                createPDFfileByVise(casecode, dto);
            }
            else if (dto.ProcedureName == "进度报告审核")
            {
                CreatePDFfile(casecode, dto.ProcedureName, dto.ApplicationCode, title);
            }
            else if (dto.ProcedureName == "质量检查审批" || dto.ProcedureName == "安全检查审批" || dto.ProcedureName == "材料检查审批")
            {
                CreatePDFfileBySafeQualityCheck(casecode, dto.ProcedureName, dto.ApplicationCode);
            }
            else if (dto.ProcedureName == "设计变更")
            {
                createPDFfileByDesignChanges(casecode, dto);
            }
        }
    }
    #endregion

    #region --写pdf表格数据--
    /// <summary>
    /// 写现场签证pdf表单
    /// </summary>
    private void createPDFfileByRequisition(string filename, WorkFlowDTO dto)
    {
        DataSet pdfDataset = new DataSet();
        pdfDataset.DataSetName = dto.ProcedureName;
        AddMainPdfTableByRequisition(pdfDataset, dto);
        if (pdfDataset.Tables.Count > 0)
        {
            AddDetailPdfTableByRequisition(pdfDataset, dto.ApplicationCode);
            WorkFlowPDFHelper.CreatePDFForm(pdfDataset, filename);
        }
    }
    /// <summary>
    /// 写主表单数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    private void AddMainPdfTableByRequisition(DataSet ds, WorkFlowDTO dto)
    {
        if (dto.ApplicationCode != string.Empty)
        {
            var model = RequisitionDb.GetById(dto.ApplicationCode);
            DataTable formMain = new DataTable();
            WorkFlowPDFHelper.FillMainFormData(formMain, "申请单编号", model.RequisitionNumber);


            WorkFlowPDFHelper.FillMainFormData(formMain, "申请单名称", model.RequisitionName);


            WorkFlowPDFHelper.FillMainFormData(formMain, "申请日期", model.RequisitionDate.Value.ToShortDateString());
            WorkFlowPDFHelper.FillMainFormData(formMain, "暂估金额", model.TotalEstimateCash.ToString());
            if (dto.ProcedureName == "设计变更申请单审核")
            {
                WorkFlowPDFHelper.FillMainFormData(formMain, "设计变更类型", model.ChangeType);
            }
            else
            {
                WorkFlowPDFHelper.FillMainFormData(formMain, "签证类型", model.ChangeType);
            }




            WorkFlowPDFHelper.FillMainFormData(formMain, "原因", model.RequisitionReason.Replace("<br>", "\n").Replace("&nbsp;", " "));
            ds.Tables.Add(formMain);
        }
    }
    /// <summary>
    /// 写明细表数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    protected void AddDetailPdfTableByRequisition(DataSet ds, string applicationCode)
    {
    }
    #region 现场签证申请单
    #endregion

    /// <summary>
    /// 写pdf表单
    /// </summary>
    public void CreatePDFfile(string filename, string workFlowName, string applicationCode, string title)
    {
        DataSet pdfDataset = new DataSet();
        pdfDataset.DataSetName = workFlowName;
        AddMainPdfTable(pdfDataset, applicationCode, title);
        if (pdfDataset.Tables.Count > 0)
        {
            AddDetailPdfTable(pdfDataset, applicationCode);
            WorkFlowPDFHelper.CreatePDFForm(pdfDataset, filename);
        }
    }

    #region  进度报告pdf
    /// <summary>
    /// 写主表单数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    private void AddMainPdfTable(DataSet ds, string applicationCode, string title)
    {
        if (applicationCode != string.Empty)
        {
            DataTable formMain = new DataTable();

            var sql = $"SELECT a.*,b.ProgressName FROM dbo.pmProgressReport a INNER JOIN dbo.pmProgress b ON a.ProgressId=b.id WHERE a.id={applicationCode}";
            var report = Db.Ado.SqlQuerySingle<pmProgressReportDTO>(sql);

            WorkFlowPDFHelper.FillMainFormData(formMain, "工作项名称", title);
            WorkFlowPDFHelper.FillMainFormData(formMain, "进度计划名称", report.ProgressName);
            WorkFlowPDFHelper.FillMainFormData(formMain, "报告日期", report.ReportDate);

            WorkFlowPDFHelper.FillMainFormData(formMain, "进度", report.CompletePercent + "%");
            WorkFlowPDFHelper.FillMainFormData(formMain, "实际开始时间", report.ActualStartDate);
            WorkFlowPDFHelper.FillMainFormData(formMain, "实际结束时间", report.ActualFinishDate);


            WorkFlowPDFHelper.FillMainFormData(formMain, "执行情况", report.Remark.Replace("<br>", "\n").Replace("&nbsp;", " "));
            ds.Tables.Add(formMain);
        }
    }
    /// <summary>
    /// 写明细表数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    protected void AddDetailPdfTable(DataSet ds, string applicationCode)
    {
    }
    #endregion

    #region  质量检查，安全检查，材料检查pdf
    /// <summary>
    /// 写质量安全检查pdf表单
    /// </summary>
    public void CreatePDFfileBySafeQualityCheck(string filename, string workFlowName, string applicationCode)
    {
        DataSet pdfDataset = new DataSet();
        pdfDataset.DataSetName = workFlowName;
        AddMainPdfTableBySafeQualityCheck(pdfDataset, applicationCode);
        if (pdfDataset.Tables.Count > 0)
        {
            WorkFlowPDFHelper.CreatePDFForm(pdfDataset, filename);
        }
    }
    /// <summary>
    /// 写主表单数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    private void AddMainPdfTableBySafeQualityCheck(DataSet ds, string applicationCode)
    {
        if (applicationCode != string.Empty)
        {
            DataTable formMain = new DataTable();

            var entity = SafeQualityCheckDb.GetById(applicationCode);
            if (entity != null)
            {
                WorkFlowPDFHelper.FillMainFormData(formMain, "工程名称", entity.ProjectName);
                WorkFlowPDFHelper.FillMainFormData(formMain, "编号", entity.CheckID);
                ds.Tables.Add(formMain);


                AddDetailPdfTableBySafeQualityCheck(ds, applicationCode);
            }



        }
    }
    /// <summary>
    /// 写明细表数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    protected void AddDetailPdfTableBySafeQualityCheck(DataSet ds, string applicationCode)
    {
        var sql = $" SELECT * FROM dbo.SafeQualityCheckItem WHERE CheckCode='{applicationCode}'";
        var detailList = Db.Ado.SqlQuery<SafeQualityCheckItem>(sql);
        if (detailList.Count > 0)
        {
            DataTable formDetail = new DataTable();
            formDetail.TableName = " ";

            formDetail.Columns.Add("序号");
            formDetail.Columns.Add("检查项目");
            formDetail.Columns.Add("检查结果");
            formDetail.Columns.Add("复查结果");
            int itemIndex = 0;
            foreach (var item in detailList)
            {
                itemIndex++;

                DataRow drNew = formDetail.NewRow();
                drNew["序号"] = itemIndex.ToString();
                drNew["检查项目"] = item.CheckContent.SConvertString();
                drNew["检查结果"] = item.CheckResult.SConvertString();
                drNew["复查结果"] = item.ReCheckResult.SConvertString();

                formDetail.Rows.Add(drNew);
            }
            if (formDetail.Rows.Count > 0)
            {
                ds.Tables.Add(formDetail);
            }

        }


    }
    #endregion


    #region 设计变更单
    /// <summary>
    /// 写现场签证pdf表单
    /// </summary>
    private void createPDFfileByDesignChanges(string filename, WorkFlowDTO dto)
    {
        DataSet pdfDataset = new DataSet();
        pdfDataset.DataSetName = dto.ProcedureName;
        AddMainPdfTableByDesignChanges(pdfDataset, dto);
        if (pdfDataset.Tables.Count > 0)
        {
            AddDetailPdfTableByDesignChanges(pdfDataset, dto.ApplicationCode);
            WorkFlowPDFHelper.CreatePDFForm(pdfDataset, filename);
        }
    }
    /// <summary>
    /// 写主表单数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    private void AddMainPdfTableByDesignChanges(DataSet ds, WorkFlowDTO dto)
    {
        if (dto.ApplicationCode != string.Empty)
        {
            var sql = $"select * from DesignChanges where DesignChangesCode='{dto.ApplicationCode}'";
            var model = Db.Ado.SqlQuerySingle<DesignChangesDTO>(sql);
            var requisitionModel = RequisitionDb.GetById(model.RequisitionCode);
            var contractModel = new UnitManager().GetContract(model.ContractCode);
            var huoban = new MaterialInManager().GetSupplierNameAndType(contractModel.SupplierCode, contractModel.SupplierTypeCode);
            DataTable formMain = new DataTable();
            WorkFlowPDFHelper.FillMainFormData(formMain, "设计变更编号", model.DesignChangesNumber);


            WorkFlowPDFHelper.FillMainFormData(formMain, "设计变更名称", model.DesignChangesName);
            WorkFlowPDFHelper.FillMainFormData(formMain, "申请单", requisitionModel.RequisitionName);
            WorkFlowPDFHelper.FillMainFormData(formMain, "关联合同", contractModel.ContractName);
            WorkFlowPDFHelper.FillMainFormData(formMain, "合作伙伴", huoban);
            WorkFlowPDFHelper.FillMainFormData(formMain, "币种汇率", $"币种：{model.MoneyType}汇率：{model.ExchangeRate.Value.ToString("#,##0.0000")}");
            WorkFlowPDFHelper.FillMainFormData(formMain, "税率", model.Rate.SConvertString() + "%");
            WorkFlowPDFHelper.FillMainFormData(formMain, "设计变更金额", model.TotalCash.ToString());
            WorkFlowPDFHelper.FillMainFormData(formMain, "设计变更日期", model.DesignChangesDate.ToString("yyyy-MM-dd"));
            WorkFlowPDFHelper.FillMainFormData(formMain, "设计变更类型", model.ChangeType);
            WorkFlowPDFHelper.FillMainFormData(formMain, "暂估金额", model.EstimateCash.ToString());
            WorkFlowPDFHelper.FillMainFormData(formMain, "设计变更原因", model.DesignChangesReason.Replace("<br>", "\n").Replace("&nbsp;", " "));
            ds.Tables.Add(formMain);
        }
    }
    /// <summary>
    /// 写明细表数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    protected void AddDetailPdfTableByDesignChanges(DataSet ds, string applicationCode)
    {
        var sql = $"select * from DesignChanges where DesignChangesCode='{applicationCode}'";
        var model = Db.Ado.SqlQuerySingle<DesignChangesDTO>(sql);
        sql = $" SELECT * FROM dbo.DesignChangesCost WHERE DesignChangesCode='{applicationCode}'";
        var detailList = Db.Ado.SqlQuery<DesignChangesCostDTO>(sql);
        var manager = new UnitManager();
        if (detailList.Count > 0)
        {
            var IsRate = true;
            string name = new ConfigItemValueManager().GetConfigItemValue("项目管理-成本控制-费用项模块名称"); ;

            if (String.IsNullOrEmpty(name))
            {
                name = "费用项";
            }

            DataTable formDetail = new DataTable();
            formDetail.TableName = "费用明细";
            if (model.IsCp == 1)
            {
                formDetail.Columns.Add("合约规划");
            }

            formDetail.Columns.Add(name);
            formDetail.Columns.Add("金额(原币)");

            //add by jinjie 20150901 营改增
            if (IsRate)
            {
                formDetail.Columns.Add("税额(原币)");
                formDetail.Columns.Add("不含税金额(原币)");
            }

            if (model.IsCp == 0)
            {
                formDetail.Columns.Add("备注");
            }
            int itemIndex = 0;
            foreach (var item in detailList)
            {
                itemIndex++;

                DataRow drNew = formDetail.NewRow();
                if (model.IsCp == 1)
                    drNew["合约规划"] = manager.GetContractPlanFullName(item.CpId.ToInteger());

                drNew[name] = manager.GetCostCodeName(item.CostCode, item.CostBudgetSetCode);
                drNew["金额(原币)"] = item.Cash.ToString("#,##0.00");

                //add by jinjie 20150901 营改增
                if (IsRate)
                {
                    drNew["税额(原币)"] = item.RateCash.ToString("N");
                    drNew["不含税金额(原币)"] = item.NoRateCash.ToString("N");
                }

                if (model.IsCp == 0)
                    drNew["备注"] = item.Remark;

                formDetail.Rows.Add(drNew);
            }
            if (formDetail.Rows.Count > 0)
            {
                ds.Tables.Add(formDetail);
            }
        }
    }
    #endregion

    #region 签证审核
    /// <summary>
    /// 写现场签证签证审核pdf表单
    /// </summary>
    private void createPDFfileByVise(string filename, WorkFlowDTO dto)
        {
            DataSet pdfDataset = new DataSet();
            pdfDataset.DataSetName = dto.ProcedureName;
            AddMainPdfTableByVise(pdfDataset, dto);
            if (pdfDataset.Tables.Count > 0)
            {
                AddDetailPdfTableByVise(pdfDataset, dto.ApplicationCode);
                WorkFlowPDFHelper.CreatePDFForm(pdfDataset, filename);
            }
        }
    /// <summary>
    /// 写主表单数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    private void AddMainPdfTableByVise(DataSet ds, WorkFlowDTO dto)
    {
        if (dto.ApplicationCode != string.Empty)
        {
            var sql = $"select * from vise where viseCode='{dto.ApplicationCode}'";
            var model = Db.Ado.SqlQuerySingle<ViseDTO>(sql);
            var requisitionModel = RequisitionDb.GetById(model.RequisitionCode);
            var contractModel = new UnitManager().GetContract(model.ContractCode);
            var huoban = new MaterialInManager().GetSupplierNameAndType(contractModel.SupplierCode, contractModel.SupplierTypeCode);
            DataTable formMain = new DataTable();
            WorkFlowPDFHelper.FillMainFormData(formMain, "签证编号", model.ViseId);
            WorkFlowPDFHelper.FillMainFormData(formMain, "签证名称", model.ViseName);
            WorkFlowPDFHelper.FillMainFormData(formMain, "签证类型", model.ViseType);
            WorkFlowPDFHelper.FillMainFormData(formMain, "签证日期", model.ViseDate.ToDateTime().ToString("yyyy-MM-dd"));
            WorkFlowPDFHelper.FillMainFormData(formMain, "申请单", requisitionModel==null?"":requisitionModel.RequisitionName);
            WorkFlowPDFHelper.FillMainFormData(formMain, "关联合同", contractModel.ContractName);
            WorkFlowPDFHelper.FillMainFormData(formMain, "合作伙伴", huoban);
            WorkFlowPDFHelper.FillMainFormData(formMain, "币种汇率", $"币种：{model.MoneyType} 汇率：{model.ExchangeRate.Value.ToString("#,##0.0000")}");
            WorkFlowPDFHelper.FillMainFormData(formMain, "税率", model.Rate.SConvertString() + "%");
            WorkFlowPDFHelper.FillMainFormData(formMain, "签证金额", model.TotalCash.ToString());
            WorkFlowPDFHelper.FillMainFormData(formMain, "办理期限", model.EndDate.ToDateTime().ToString("yyyy-MM-dd"));

            WorkFlowPDFHelper.FillMainFormData(formMain, "暂估金额", model.EstimateCash.ToString());
            WorkFlowPDFHelper.FillMainFormData(formMain, "施工单位报送金额", model.ReportCash.ToString());
            WorkFlowPDFHelper.FillMainFormData(formMain, "签证原因", model.Reason.Replace("<br>", "\n").Replace("&nbsp;", " "));
            ds.Tables.Add(formMain);
        }
    }
    /// <summary>
    /// 写明细表数据
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="applicationCode"></param>
    protected void AddDetailPdfTableByVise(DataSet ds, string applicationCode)
        {
            var sql = $"select * from vise where viseCode='{applicationCode}'";
            var model = Db.Ado.SqlQuerySingle<ViseDTO>(sql);
            sql = $" SELECT * FROM dbo.viseCost WHERE visecode='{applicationCode}'";
            var detailList = Db.Ado.SqlQuery<ViseCostDTO>(sql);
            var manager = new UnitManager();
            if (detailList.Count > 0)
            {
                var IsRate = true;
                string name = new ConfigItemValueManager().GetConfigItemValue("项目管理-成本控制-费用项模块名称"); ;

                if (String.IsNullOrEmpty(name))
                {
                    name = "费用项";
                }

                DataTable formDetail = new DataTable();
                formDetail.TableName = "费用明细";
                if (model.IsCp == 1)
                {
                    formDetail.Columns.Add("合约规划");
                }

                formDetail.Columns.Add(name);
                formDetail.Columns.Add("金额(原币)");

                //add by jinjie 20150901 营改增
                if (IsRate)
                {
                    formDetail.Columns.Add("税额(原币)");
                    formDetail.Columns.Add("不含税金额(原币)");
                }

                if (model.IsCp == 0)
                {
                    formDetail.Columns.Add("备注");
                }
                int itemIndex = 0;
                foreach (var item in detailList)
                {
                    itemIndex++;

                    DataRow drNew = formDetail.NewRow();
                    if (model.IsCp == 1)
                        drNew["合约规划"] = manager.GetContractPlanFullName(item.CpId.ToInteger());

                    drNew[name] = manager.GetCostCodeName(item.CostCode, item.CostBudgetSetCode);
                    drNew["金额(原币)"] = item.Cash.Value.ToString("#,##0.00");

                    //add by jinjie 20150901 营改增
                    if (IsRate)
                    {
                        drNew["税额(原币)"] = item.RateCash.ToString("N");
                        drNew["不含税金额(原币)"] = item.NoRateCash.ToString("N");
                    }

                    if (model.IsCp == 0)
                        drNew["备注"] = item.Remark;

                    formDetail.Rows.Add(drNew);
                }
                if (formDetail.Rows.Count > 0)
                {
                    ds.Tables.Add(formDetail);
                }
            }
        }
            #endregion


        #endregion


    }
