using DynamicExpresso;
using Microsoft.International.Converters.PinYinConverter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using wispro.sp.entity;
using wispro.sp.share;
using wispro.sp.share.Utility;
using wispro.sp.utility;

namespace wispro.sp.winClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        
        private void button1_Click(object sender, EventArgs e)
        {
            DateTime startTime = DateTime.Now;
            frmMerageExcel frm = new frmMerageExcel();

            if (frm.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show($"合并完成，合并后文件保存在:\r\n{frm.SaveFilePath}\r\n用时：{DateTime.Now - startTime }");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog()
            {
                Multiselect = false,
                Filter = "*.xls|*.xlsx"
            };

            string strDinashuRegularFile = ConfigurationSettings.AppSettings["DinashuRegularFile"];
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                new ExcelHelper().FillDianShu(ofd.FileName, strDinashuRegularFile);
            }

            MessageBox.Show("完成点数输入！");
        }

        private string[] InValidDoItem = new string[]
        {
            "案件异常-催缴年费",
            "案件异常-视为放弃取得专利权",
            "办理登记手续",
            "办理登记手续-确认客户是否委托",
            "代理所变更",
            "绘图",
            "技术确认",
            "缴年费",
            "请求保密审查",
            "请求费减",
            "请求实审",
            "取得申请号",
            "取得证书",
            "取得专利权评价报告",
            "确认官方审查状况",
            "询问放弃或复审",
            "知识点总结",
            "专利权人发明人申请人信息变更",
            "专利挖掘与布局",
            "我方文号前缀带J",
            "开卷",
            "请求提前公开",
            "取得国际检索报告",
            "委外检索",
            "中止程序",
            "终止",
            "案件异常-视为撤回",
            "进入国家阶段提醒",
            "请求恢复权利",
            "请求优先权",
            "取得【无效宣告请求审查决定】",
            "撤回",
            "请求退款",
            "确认是否委托申请与类型",
            "专利交易",
            "专利权评价报告",
            "专利权人发明人申请人信息变更+代理所变更"
        };

        private async Task InitRules(bool isSave)
        {
            List<BasePointRule> rules = new List<BasePointRule>();
            DataTable dt = wispro.sp.utility.NPOIExcel.ExcelToDataTable("ExcelFiles\\20211109-绩效点数规则-lcy-v1.xlsx", true);

            PerformanceItem item = new PerformanceItem() { CaseNo = "PAEPO2016277", DoItem= "提交检索主题声明", };
            foreach(DataRow row in dt.Rows)
            {
                BasePointRule rule = new BasePointRule()
                {
                    Rule = row["规则"].ToString(),
                    PointExpress = row["点数计算"].ToString(),
                    Priority = int.Parse(row["优先级修订"].ToString()),
                    Type = row["类型"].ToString()

                };

                try
                {
                    var interpreter = new Interpreter();

                    
                    //item.ApplicationType
                    Func<PerformanceItem, bool> func = interpreter.ParseAsDelegate<Func<PerformanceItem, bool>>(rule.Rule, "p");

                    bool result = func.Invoke(item);

                    if (result)
                    {
                        item.BasePoint = (double?)interpreter.Eval(rule.PointExpress);
                        item.Type = rule.Type;
                        System.Diagnostics.Debug.WriteLine("");
                    }

                    rules.Add(rule);
                }
                catch(Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(rule.Rule  + "\r\n" + ex.ToString());
                }

                
            }

            if (isSave)
            {
                foreach (BasePointRule rule in rules)
                {
                    double d;
                    if(double.TryParse(rule.PointExpress,out d))
                    {
                        rule.PointExpress = d.ToString("0.00");
                    }
                    await SaveBasePointRule(rule);
                }
            }
        }

        public async Task TestQueryFilter()
        {
            //QueryFilter filter = new QueryFilter();
            //filter.ConditionTree = new ExpressTree();
            //string ValueType = typeof(PerformanceItem).GetProperty("CaseNo").PropertyType.ToString();
            //FieldCondition condition1 = new FieldCondition() { FieldName = "CaseNo", Operator = OperatorEnum.Contains, Value = "PACN", ValueType = ValueType };
            //FieldCondition condition2 = new FieldCondition() { FieldName = "CaseNo", Operator = OperatorEnum.Contains, Value = "PAUS", ValueType = ValueType };

            //filter.ConditionTree.AddCondition(LogicEnum.And,condition1);
            //filter.ConditionTree.AddCondition(LogicEnum.Or, condition2);

            //System.Diagnostics.Debug.WriteLine(filter.ConditionTree.ToExpressString("s")); ;

        }

        enum enumTest
        {
            [Description("男")]
            man,
            [Description("女")]
            woman
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            //share.Utility.UserConditionHelper.GetPropertyDescription<Staff>(typeof(PerformanceItem).AssemblyQualifiedName);

            #region Demo流程数据
            HttpClient http = new HttpClient();
            int wfId = 6;
            var workflow = await GetWorkflow(wfId, http);
            var Steps = await GetSteps(wfId, http);
            var Actions = await GetActions(wfId, http);
            var Transfers = await GetTransfers(wfId,http);
            #endregion
            FlowChartUtility flowChart = new FlowChartUtility();
            flowChart.workflow = workflow;
            flowChart.Steps = Steps;
            flowChart.Transfers = Transfers;

            string strSvg = flowChart.GetSvgString();

            //var file = System.IO.File.CreateText("c:\\temp\\tem.svg");
            //file.WriteLine(strSvg);
            //file.Close();

            System.Xml.XmlDocument xmdoc = new System.Xml.XmlDocument();
            xmdoc.LoadXml(strSvg);
            Svg.SvgDocument svg = Svg.SvgDocument.Open(xmdoc);
            Bitmap bitmap = svg.Draw();
            bitmap.Save("c:\\temp\\test.jpg",ImageFormat.Jpeg);
            MemoryStream mStream = new MemoryStream();
            bitmap.Save(mStream, ImageFormat.Jpeg);
            byte[] bitMaps = new byte[mStream.Length];
            mStream.Read(bitMaps, 0, (int)mStream.Length);



            //var test =wispro.sp.utility.EmunHelper.getEnumDescriptionDic<wispro.sp.entity.workflowDefine.LogicSymbols>();

            //Console.WriteLine("");
            //dynamic dynObj = new ExpandoObject();
            //dynObj.Name = "名称";
            //dynObj.Text = "aaabc";


            //List<dynamic> list = new List<dynamic>();
            //for(int i = 0; i < 3; i++)
            //{
            //    dynamic d = new ExpandoObject();
            //    d.Id = i + 1;
            //    d.Filed1 = $"Field{i}";
            //    d.Date = DateTime.Now.AddDays(i);
            //    list.Add(d);
            //}

            //dynObj.List = list;
            //var temTxt = System.Text.Json.JsonSerializer.Serialize(dynObj);

            //var dynamic = System.Text.Json.JsonSerializer.Deserialize<ExpandoObject>(temTxt);


            //MessageBox.Show(((IDictionary<string, object>)dynamic)["Name"].ToString());

            //wispro.sp.utility.MailUtil.SendEmail("测试邮件标题","测试邮件内容","罗才洋","luocaiyang@139.com");
            //CreateAppealModel model = new CreateAppealModel();
            //HttpClient http = new HttpClient();
            //PerformanceItem item = await http.GetFromJsonAsync<wispro.sp.entity.PerformanceItem>($"http://localhost:39476/api/PerformanceItem/Get?Id=7341");
            //List<AppealType> appealTypes = await http.GetFromJsonAsync<List<AppealType>>($"http://localhost:39476/api/Appeal/GetAppealTypes");
            //var appealType = appealTypes.Where<AppealType>(a => a.Id == 1).FirstOrDefault();
            //await model.Init(item, appealType);
            ////await TestQueryFilter();
            //List<PerformanceItem> retList = new List<PerformanceItem>();
            //var test= retList.Where<PerformanceItem>(p => p.isDanger());

            //await InitRules(true);

            ////return;

            //await ImportUsers();
            //await InputPerformanceItem("ExcelFiles\\21.01-21.06 工程师绩效报表-总表.xlsx", true, false, 0);

            ////CalMonth cal = new CalMonth()
            ////{
            ////    Year = 2021,
            ////    Month = 9,
            ////    Status = 0
            ////};

            ////await InputPerformanceItem(@"C:\Users\luowen\Downloads\每月绩效统计--发客户超过一个月未完成案件.xlsx", true,false,1, cal);

            ////await InputPerformanceItem(@"C:\Users\luowen\Downloads\每月绩效统计--上个月递交完成案件.xlsx", true, false, 1, cal);

            ////await InputPerformanceItem(@"C:\Users\luowen\Downloads\每月绩效统计--中国一次OA授权表.xlsx", true, false, 1, cal,true);

            //MessageBox.Show("导入完成！");
        }

        private PerformanceItem Row2Item_1(DataRow row, List<Staff> Staffs, CalMonth calMonth)
        {
            PerformanceItem item = new PerformanceItem();
            item.ApplicationType = row["申请类型"].ToString().Trim();

            if(item.ApplicationType != "发明")
            {
                return null;
            }

            item.CaseNo = row["我方文号"].ToString().Trim();

            if (calMonth != null)
            {
                item.CalMonth = calMonth;
            }
            else
            {
                if (row.Table.Columns.Contains("绩效核算月份"))
                {
                    string strjxyf = row["绩效核算月份"].ToString().Trim();
                    string[] temYFs = strjxyf.Split(new char[] { '.' });
                    item.CalMonth = new CalMonth();
                    item.CalMonth.Year = int.Parse(temYFs[0]);
                    item.CalMonth.Month = int.Parse(temYFs[1]);
                    item.CalMonth.Status = 4;
                }
                else
                {
                    item.CalMonth = new CalMonth();
                    item.Status = 0;
                    item.CalMonth.Year = DateTime.Now.AddMonths(-1).Year;
                    item.CalMonth.Month = DateTime.Now.AddMonths(-1).Month;
                }
            }

            item.ApplicationType = row["申请类型"].ToString().Trim();
            item.BusinessType = "普通新申请"; // row["业务类型"].ToString().Trim();
            item.AgentFeedbackMemo = "发明一次OA授权"; //row["备注（填表注意事项）"].ToString().Trim();
            item.DoItem = "发明一次OA授权"; //row["处理事项"].ToString().Trim();

            string strHandler = "";
            if (row.Table.Columns.Contains("处理人"))
            {
                strHandler = row["处理人"].ToString().Trim();
            }
            else
            {
                if (row.Table.Columns.Contains("案件处理人"))
                {
                    strHandler = row["案件处理人"].ToString().Trim();
                }
            }
            
            string[] temHandlers = strHandler.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            item.ItemStaffs = new List<ItemStaff>();

            foreach (string name in temHandlers)
            {
                ItemStaff itemStaff = new ItemStaff();
                int? iTem = GetStaff(name, Staffs);
                if ((iTem != null))
                {
                    //itemStaff.Item = item;
                    itemStaff.DoPersonId = iTem.Value;
                    item.ItemStaffs.Add(itemStaff);
                }
                else
                {
                    itemStaff.DoPerson = new Staff()
                    {
                        Name = name,
                        Account = name,
                        Password = "12345678",
                        IsCalPerformsnce = false,
                        Status = "正式员工",
                        StaffGradeId = 4
                    };
                    item.ItemStaffs.Add(itemStaff);
                }
            }

            if (item.ItemStaffs.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine($"没有处理人: {item.CaseNo}\t{item.DoItem}");
            }

            if (row.Table.Columns.Contains("核稿人"))
            {
                item.ReviewerId = GetStaff(row["核稿人"].ToString().Trim(), Staffs);
            }
            else
            {
                if (row.Table.Columns.Contains("案件核稿人"))
                {
                    item.ReviewerId = GetStaff(row["案件核稿人"].ToString().Trim(), Staffs);
                }
            }

            item.Customer = new Customer() { Name = row["客户名称"].ToString().Trim() };
            item.ApplicationName = row["申请人"].ToString().Trim();
            item.CaseName = row["案件名称"].ToString().Trim();
            
            //案件备注
            item.CaseMemo = $"发文日期:{row["发文日期"].ToString().Trim()}\r\n客户文号:{row["客户文号"].ToString().Trim()}\r\n上传日期:{row["上传日期"].ToString().Trim()}\r\n文件描述:{row["文件描述"].ToString().Trim()}";

            return item;
        }

        private PerformanceItem Row2Item(DataRow row, List<Staff> Staffs,CalMonth calMonth)
        {
            PerformanceItem item = new PerformanceItem();
            item.CaseNo = row["我方文号"].ToString().Trim();

            if (calMonth != null)
            {
                item.CalMonth = calMonth;
            }
            else
            {
                if (row.Table.Columns.Contains("绩效核算月份"))
                {
                    string strjxyf = row["绩效核算月份"].ToString().Trim();
                    string[] temYFs = strjxyf.Split(new char[] { '.' });
                    item.CalMonth = new CalMonth();
                    item.CalMonth.Year = int.Parse(temYFs[0]);
                    item.CalMonth.Month = int.Parse(temYFs[1]);
                    item.CalMonth.Status = 4;
                }
                else
                {
                    item.CalMonth = new CalMonth();
                    item.Status = 0;
                    item.CalMonth.Year = DateTime.Now.AddMonths(-1).Year;
                    item.CalMonth.Month = DateTime.Now.AddMonths(-1).Month;
                }
            }

            item.ApplicationType = row["申请类型"].ToString().Trim();
            item.BusinessType = row["业务类型"].ToString().Trim();

            if (row.Table.Columns.Contains("备注（填表注意事项）"))
                item.AgentFeedbackMemo = row["备注（填表注意事项）"].ToString().Trim();

            item.DoItem = row["处理事项"].ToString().Trim();
            item.CaseStage = row["案件阶段"].ToString().Trim();
            item.CaseCoefficient = row["案件系数"].ToString().Trim();
            item.DoItemCoefficient = row["处理事项系数"].ToString().Trim();
            item.PreOastaffId = GetStaff(row["前一次OA处理人"].ToString().Trim(), Staffs);

            string strHandler = "";
            if (row.Table.Columns.Contains("处理人"))
            {
                strHandler = row["处理人"].ToString().Trim();
            }
            else
            {
                if (row.Table.Columns.Contains("案件处理人"))
                {
                    strHandler = row["案件处理人"].ToString().Trim();
                }
            }
            string[] temHandlers = strHandler.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            item.ItemStaffs = new List<ItemStaff>();

            foreach (string name in temHandlers)
            {
                ItemStaff itemStaff = new ItemStaff();

                string temName = name.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0];
                int? iTem = GetStaff(temName, Staffs);
                if ((iTem != null))
                {
                    //itemStaff.Item = item;
                    itemStaff.DoPersonId = iTem.Value;
                    item.ItemStaffs.Add(itemStaff);
                }
                else
                {
                    itemStaff.DoPerson = new Staff()
                    {
                        Name = temName,
                        Account = temName,
                        Password = "12345678",
                        IsCalPerformsnce = false,
                        Status = "已离职",
                        StaffGradeId = 4
                    };
                    item.ItemStaffs.Add(itemStaff);
                }
            }

            if (item.ItemStaffs.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine($"没有处理人: {item.CaseNo}\t{item.DoItem}");
            }

            if (row.Table.Columns.Contains("核稿人"))
            {
                if (!string.IsNullOrEmpty(row["核稿人"].ToString().Trim()))
                {
                    string temName = row["核稿人"].ToString().Trim().Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0];
                    item.ReviewerId = GetStaff(temName.Trim(), Staffs);
                }
            }
            else
            {
                if (row.Table.Columns.Contains("案件核稿人"))
                {
                    if (!string.IsNullOrEmpty(row["案件核稿人"].ToString().Trim()))
                    {
                        string temName = row["案件核稿人"].ToString().Trim().Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0];
                        item.ReviewerId = GetStaff(temName.Trim(), Staffs);
                    }
                    
                }
            }




            item.Customer = new Customer() { Name = row["客户名称"].ToString().Trim() };
            item.ApplicationName = row["申请人"].ToString().Trim();

            DateTime temDate = new DateTime();
            if (DateTime.TryParse(row["处理事项完成日"].ToString().Trim(), out temDate))
            {
                item.FinishedDate = temDate;
            }


            //定稿日
            if (DateTime.TryParse(row["定稿日"].ToString().Trim(), out temDate))
            {
                item.FinalizationDate = temDate;
            }
            //返稿日
            if (DateTime.TryParse(row["返稿日"].ToString().Trim(), out temDate))
            {
                item.ReturnDate = temDate;
            }
            //案件类型
            item.CaseType = row["案件类型"].ToString().Trim();

            //案件状态
            item.CaseState = row["案件状态"].ToString().Trim();
            //处理事项备注
            item.DoItemMemo = row["处理事项备注"].ToString().Trim();
            //处理状态
            item.DoItemState = row["处理状态"].ToString().Trim();
            //案件名称
            item.CaseName = row["案件名称"].ToString().Trim();
            //委案日期
            if (DateTime.TryParse(row["委案日期"].ToString().Trim(), out temDate))
            {
                item.EntrustingDate = temDate;
            }
            //客户期限
            if (DateTime.TryParse(row["客户期限"].ToString().Trim(), out temDate))
            {
                item.CustomerLimitDate = temDate;
            }
            //内部期限
            if (DateTime.TryParse(row["内部期限"].ToString().Trim(), out temDate))
            {
                item.InternalDate = temDate;
            }
            //初稿日
            if (DateTime.TryParse(row["初稿日"].ToString().Trim(), out temDate))
            {
                item.FirstDraftDate = temDate;
            }

            //备注（发文严重超期是否属客观原因，若为否，请填写原因）
            if (row.Table.Columns.Contains("备注（发文严重超期是否属客观原因，若为否，请填写原因）"))
            {
                item.OverDueMemo = row["备注（发文严重超期是否属客观原因，若为否，请填写原因）"].ToString().Trim();
            }
            //案件备注
            item.CaseMemo = row["案件备注"].ToString().Trim();

            return item;

        }

        private async Task InputPerformanceItem(string strExcelFile,bool isColumnName,bool ignorHideRows=false,int ColumnNameRow=0,CalMonth calMonth=null,bool isFirstOAFile=false)
        {
            DataTable dt = NPOIExcel.ExcelToDataTable(strExcelFile, isColumnName,ignorHideRows,ColumnNameRow);

            #region 删除重复行
            DataTable temdt = new DataTable();
            foreach (DataColumn col in dt.Columns)
            {

                DataColumn temCol = new DataColumn();
                temCol.ColumnName = col.ColumnName;
                temCol.DataType = col.DataType;
                temCol.Caption = col.Caption;

                temdt.Columns.Add(temCol);
            }
            
            new ExcelHelper().MerageDataTable(temdt, dt);
            #endregion

            List<Staff> Staffs =await GetStaffsAsync();

            foreach(DataRow row in temdt.Rows)
            {
                PerformanceItem item = null;
                if (isFirstOAFile)
                {
                    item = Row2Item_1(row, Staffs, calMonth);
                }
                else
                {
                    item = Row2Item(row, Staffs, calMonth);
                }

                if (item != null )
                {
                    if (!InValidDoItem.Contains(item.DoItem))
                    {
                        await SavePerformanceItem(item);
                    }
                }
            }

        }

        private int? GetStaff(string v, List<Staff> staffs)
        {
            if (!string.IsNullOrEmpty(v))
            {
                string[] temNames = v.Trim().Split(new char[] { '-' },StringSplitOptions.RemoveEmptyEntries);

                foreach (Staff sf in staffs)
                {
                    if(sf.Name == temNames[0])
                    {
                        return sf.Id;
                    }
                }
            }

            return null;
        }

        private async Task ImportUsers()
        {
            DataTable dt = NPOIExcel.ExcelToDataTable(@"C:\temp\用户列表(2021年10月26日).xlsx", true,false,1);
            List<StaffGrade> staffGrades = await GetStaffGrades();

            foreach (DataRow row in dt.Rows)
            {
                Staff staff = new Staff();
                staff.Account = row["用户名"].ToString().Trim();
                staff.Name = row["姓名"].ToString().Trim();
                staff.Tel = row["电话号码"].ToString().Trim();
                staff.Mobile = row["手机号码"].ToString().Trim();
                staff.Sex = row["性别"].ToString().Trim();
                staff.Mail = row["邮箱"].ToString().Trim();

                string strGrade = row["工程师等级"].ToString().Trim(); // + "级";

                foreach (StaffGrade sg in staffGrades)
                {
                    if (strGrade.Trim() == sg.Grade.Trim())
                    {
                        staff.StaffGradeId = sg.Id;
                        break;
                    }
                }

                staff.IsOnJob = (row["是否在职"].ToString().Trim()=="是");

                staff.Status = row["岗位状态"].ToString().Trim();
                staff.Department = row["部门"].ToString();
                staff.WorkPlace = row["工作地"].ToString();

                DateTime temDate;
                if (DateTime.TryParse(row["入职时间"].ToString(), out temDate))
                {
                    staff.EntyDate = temDate;
                }

                //staff.IsCalPerformsnce = (row["是否核算绩效"].ToString() == "是");
                //staff.Memo = row["备注"].ToString().Trim();

                staff.Password = MD5Utility.GetMD5("12345678");
                //staff.StaffGradeId = row["姓名"].ToString();

                await SaveStaff(staff);
            }
        }

        private string getPinYin(string str)
        {
            string retStr = "";
            
            for(int i = 0; i < str.Length; i++)
            {
                ChineseChar cc = new ChineseChar(str[i]);
               
                retStr = retStr + cc.Pinyins[0].ToLower().Replace("1","")
                    .Replace("2", "").Replace("3", "").Replace("4", "");
            }
            return retStr;
        }

        public async Task<entity.workflowDefine.Workflow> GetWorkflow(int Id, HttpClient _httpClient)
        {
            var ret = await _httpClient.GetFromJsonAsync<entity.workflowDefine.Workflow>($"http://localhost:39476/api/WorkflowEngine/GetWorkflow?workflowId={Id}");

            
            return ret;
        }

        public async Task<List<entity.workflowDefine.Step>> GetSteps(int Id, HttpClient _httpClient)
        {
            var ret = await _httpClient.GetFromJsonAsync<List<entity.workflowDefine.Step>>($"http://localhost:39476/api/WorkflowEngine/GetSteps?workflowId={Id}");
            return ret;
        }

        public async Task<List<entity.workflowDefine.Action>> GetActions(int workflowId, HttpClient _httpClient)
        {
            var ret = await _httpClient.GetFromJsonAsync<List<entity.workflowDefine.Action>>($"http://localhost:39476/api/WorkflowEngine/GetActions?workflowId={workflowId}");
            return ret;
        }

        public async Task<List<entity.workflowDefine.TrasferCondition>> GetTransfers(int workflowId, HttpClient _httpClient)
        {
            var ret = await _httpClient.GetFromJsonAsync<List<entity.workflowDefine.TrasferCondition>>($"http://localhost:39476/api/WorkflowEngine/GetTrasfers?workflowId={workflowId}");
            return ret;
        }
        private async  Task SaveStaff(Staff obj)
        {
            HttpClient http = new HttpClient();
            var data = await http.PostAsJsonAsync<wispro.sp.entity.Staff>($"http://localhost:39476/api/Staff/Save", obj);
            if (data.IsSuccessStatusCode)
            {
                ApiSaveResponse result = await data.Content.ReadFromJsonAsync<ApiSaveResponse>();
                //await Task.Delay(1000);

                if (result.Success)
                {
                }
                else
                {
                }
            }
            else
            {
            }
        }

        private async Task SaveBasePointRule(BasePointRule obj)
        {
            HttpClient http = new HttpClient();
            var data = await http.PostAsJsonAsync<BasePointRule>($"http://localhost:39476/api/BasePointRule/New", obj);
            if (data.IsSuccessStatusCode)
            {
                ApiSaveResponse result = await data.Content.ReadFromJsonAsync<ApiSaveResponse>();
                //await Task.Delay(1000);

                if (result.Success)
                {
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"保存错误： {obj.Rule}\t{obj.PointExpress}\r\n{result.ErrorMessage}");
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"调用API错误： {obj.Type}\t{obj.Rule}");
            }
        }
        private async Task SavePerformanceItem(PerformanceItem obj)
        {
            HttpClient http = new HttpClient();
            var data = await http.PostAsJsonAsync<PerformanceItem>($"http://localhost:39476/api/PerformanceItem/New", obj);
            if (data.IsSuccessStatusCode)
            {
                ApiSaveResponse result = await data.Content.ReadFromJsonAsync<ApiSaveResponse>();
                //await Task.Delay(1000);

                if (result.Success)
                {
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"保存错误： {obj.CaseNo}\t{obj.DoItem}\r\n{result.ErrorMessage}");
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"调用API错误： {obj.CaseNo}\t{obj.DoItem}");
            }
        }

        private async Task<List<StaffGrade>> GetStaffGrades()
        {
            HttpClient http = new HttpClient();
            var _StaffGrade = await http.GetFromJsonAsync<List<StaffGrade>>($"http://localhost:39476/api/StaffGrade/GetAll");
            return _StaffGrade;
        }

        private async Task<List<Staff>> GetStaffsAsync()
        {
            HttpClient http = new HttpClient();
            ListApiResponse<Staff> data = await http.GetFromJsonAsync<ListApiResponse<Staff>>($"http://localhost:39476/api/Staff/Query?pageIndex=1&pageSize=200");

            return data.Results;


        }

        private void button4_Click(object sender, EventArgs e)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
           
            dynamic retObj = wispro.sp.utility.IPEasyUtility.GetPerformanceRecord("S2112392-洗碗机调查分析","提出报告");
            PerformanceItem Item = new PerformanceItem();
            Item.CaseName = retObj.CaseName;
            Item.CaseNo = retObj.CaseNo;
            Item.DoItem = retObj.DoItem;

            Item.CustomerLimitDate = string.IsNullOrEmpty(retObj.CustomerLimitDate) ? null : DateTime.Parse(retObj.CustomerLimitDate);
            Item.Customer = new Customer();
            Item.Customer.Name = retObj.CustomerName;
            Item.DoItemCoefficient = retObj.DoItemCoefficient;
            Item.DoItemMemo = retObj.DoItemMemo;
            Item.DoItemState = retObj.DoItemState;
            Item.EntrustingDate = string.IsNullOrEmpty(retObj.EntrustingDate) ? null : DateTime.Parse(retObj.EntrustingDate);
            Item.FinalizationDate = string.IsNullOrEmpty(retObj.FinalizationDate) ? null : DateTime.Parse(retObj.FinalizationDate);
            Item.FinishedDate = string.IsNullOrEmpty(retObj.FinishedDate) ? null : DateTime.Parse(retObj.FinishedDate);
            //Item.FirstDraftDate = string.IsNullOrEmpty(retObj.FirstDraftDate) ? null : DateTime.Parse(retObj.FirstDraftDate);
            Item.InternalDate = string.IsNullOrEmpty(retObj.InternalDate) ? null : DateTime.Parse(retObj.InternalDate);
            
            if (!string.IsNullOrEmpty(retObj.DoPersons))
            {
                Item.ItemStaffs = new List<ItemStaff>();
                string[] names = retObj.DoPersons.ToString().Split(new char[] { ','},StringSplitOptions.RemoveEmptyEntries);
                foreach(var name in names)
                {
                    ItemStaff iStaff = new ItemStaff();
                    iStaff.DoPerson = new Staff() { Name = name };
                    Item.ItemStaffs.Add(iStaff);
                }
            }

            Item.ReturnDate = string.IsNullOrEmpty(retObj.ReturnDate) ? null : DateTime.Parse(retObj.ReturnDate);

            if (!string.IsNullOrEmpty(retObj.Reviewer))
            {
                Item.Reviewer = new Staff() { Name = retObj.Reviewer };
            }
            Item.ApplicationType = retObj.ApplicationType;
            Item.BusinessType = retObj.BusinessType;
            Item.CaseCoefficient = retObj.CaseCoefficient;
            Item.CaseMemo = retObj.CaseMemo;
            Item.CaseStage = retObj.CaseStage;
            Item.CaseState = retObj.CaseState;
            Item.CaseType = retObj.CaseType;

            watch.Stop();
            System.Diagnostics.Debug.WriteLine("用时{0}毫秒", watch.ElapsedMilliseconds);//获取当前实例测量得出的总运行时间（以毫秒为单位）


            //wispro.sp.utility.IPEasyUtility.DownloadReport("每月绩效统计--上个月递交完成案件", true);
            //wispro.sp.utility.IPEasyUtility.DownloadReport("每月绩效统计--发客户超过一个月未完成案件", false);
            //wispro.sp.utility.IPEasyUtility.DownloadReport("每月绩效统计--中国一次OA授权表", true);
            ////每月绩效统计--发客户超过一个月未完成案件
            //NewMethod("506aa7ad-c3f4-4ec6-9ec8-ff6b92dcd7c1", "每月绩效统计--发客户超过一个月未完成案件.xlsx", calMonth);

            ////每月绩效统计--上个月递交完成案件
            //NewMethod("d7308cd2-71e4-4444-9f47-f4d731ddb26a", "每月绩效统计--上个月递交完成案件.xlsx", calMonth);

            ////每月绩效统计--中国一次OA授权表
            //NewMethod("72454834-afdd-4b98-b42a-0bc912d07610", "每月绩效统计--中国一次OA授权表.xlsx", calMonth, true);
        }
    }
}
