几行设计规范 概念

 

 

 

对代码 进而进行了优化 

 

using Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson.Serialization.Attributes;
using System.Data.Entity;
using Models.SysModels;
using Models.UserModels;
using Models.Constraints;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using Services.UserServices;
using Models.PlanModels;
using Models.TaskModels;
using IServices.ISysServices;
using Services.SysServices;
using IServices.IUserServices;
using Models.ViewModels;
using Services.Infrastructure;
using Services.PlanServices;
using IServices.IMonitorServices;
using Services.MonitorServices;
using Models.ViewModels.VMRoutePlan;
using DBHelper.MySql;
using System.Collections;
using System.Reflection;


namespace WF_DRs
{
    public partial class Form1 : Form, IForm
    {
        private DateTime _lastRun = DateTime.MinValue;

        private bool _stop = false;

        public Form1()
        {
            InitializeComponent();
            //Trace.Listeners.Add(new ShowLogTraceListener(this));
        }

        public void showLog(string title, string message) // 实现
        {
            this.Invoke((EventHandler)delegate
            {
                if (listBox1.Items.Count > 1000)
                    listBox1.Items.RemoveAt(listBox1.Items.Count - 1);
                listBox1.Items.Insert(0, string.Format("{0} {1} {2}", DateTime.Now, title, message));
            });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value;
            Summary(st, et);
        }

        private void Summary(DateTime st, DateTime et)
        {
            showLog("Summary", "Start");
            insertShowlog("Summary----Start", st, et);
            List<Summary> Summlist = new List<Summary>();
            //DateTime st = DateTime.Now.Date;
            //DateTime et = st.AddDays(1);
            DateTime tmpdtm = st;
            try
            {
                using (var db = new ApplicationDb())
                {
                    var projs = db.SysProjects.Where(a => !a.Deleted).ToList();
                    var linedets = db.LineInfos.Where(a => !a.Deleted && a.TaskTime >= st & a.TaskTime < et).Select(a => new { a.TaskTime, a.ProjectId, a.Id });
                    int dayint = 1;
                    var dictbo = db.SysDictBos.ToList();
                    //
                    //var atmbar = db.AtmBarCodes.Where(a => !a.Deleted);
                    var atmbar = db.AtmBarCodes;
                    var Gunssss = db.Guns.Where(a => !a.Deleted).ToList();
                    var LineLogisticsssss = db.LineLogisticss.Where(a => !a.Deleted);
                    var KeyPasswordssss = db.KeyPasswords.Where(a => !a.Deleted);
                    var AtmPdasssss = db.AtmPdas.Where(a => !a.Deleted).ToList();
                    var WorkingTELssss = db.WorkingTELs.Where(a => !a.Deleted).ToList();
                    var AtmTrucksssss = db.AtmTrucks.Where(a => !a.Deleted).ToList();
                    var GPSNavigatorsss = db.GPSNavigator.Where(a => !a.Deleted).ToList();
                    var EasyPassTagssss = db.EasyPassTag.Where(a => !a.Deleted).ToList();
                    var ATMPassCardsssss = db.ATMPassCards.Where(a => !a.Deleted).ToList();
                    var OtherBarcodessss = db.OtherBarcode.Where(a => !a.Deleted).ToList();
                    while (tmpdtm < et)    // 时间
                    {
                        var tmpenddtm = tmpdtm.AddDays(1);
                        foreach (var item in projs)  //城市
                        {
                            //Guns
                            var Guns = Gunssss.Where(a => a.ProjectId == item.Id).Select(a => new { a.IsDamage, a.AtmBarCodeId }).ToList();
                            List<Guid> gunbarcode = Guns.Select(a => a.AtmBarCodeId).ToList();
                            var gun_barcode = atmbar.Where(a => gunbarcode.Contains(a.Id)).ToList();
                            Summary sm = new Summary();
                            sm.Total = gun_barcode.Count();
                            sm.Date = tmpdtm;
                            sm.Branck = item.Name;
                            sm.Item = "Gun";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm.Date && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            var lineids = linedets.Where(a => a.TaskTime >= tmpdtm.Date && a.TaskTime < tmpenddtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1 = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "191" && !a.Deleted).Count();
                            int p2 = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                .Where(a => a.FLG == 10).Where(a => a.LogTag == "191" && !a.Deleted && a.ProjectId == item.Id).Count();
                            sm.Issued = (p1 + p2);
                            sm.Damaged = (Guns.Count(a => a.IsDamage));
                            int r1 = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "191" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2 = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "191" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            sm.Returned = (r1 + r2);
                            Summlist.Add(sm);

                            //foreach (var goods in guns)  // 物品
                            //{
                            //    //foreach (var taskdate in linedets.where(a => a.projectid == item.projectid )) // 时间
                            //    //{
                            //        //sm.total = gun_barcode.where(a => a.createddate.date <= sm.date).count().tostr();
                            //        int r1 = db.persongoodss.where(a => a.createddate <= sm.date).where(a => a.logtag == "191" && !a.deleted && a.projectid == item.projectid).where(a => a.flg == 20).count();
                            //        int r2 = db.linelogisticss.where(a => a.createddate <= sm.date).where(a => a.logtag == "191" && !a.deleted && a.projectid == item.projectid).where(a => a.flg == 20).count();
                            //        sm.returned = (r1 + r2).tostr();
                            //    }
                            //}

                            //atm key  spare key
                            var atmkey = KeyPasswordssss.Where(a => !a.Deleted).Where(a => a.ProjectId == item.Id && a.KeyPasswordType == Models.Constraints.KeyPasswordTypes.KeyPasswordTypes_KEY).Select(a => new { a.AtmBarCodeId, a.keyState }).ToList();
                            List<Guid> atmkeybarcode = atmkey.Select(a => a.AtmBarCodeId).ToList();
                            var atmkey_barcode = atmbar.Where(a => atmkeybarcode.Contains(a.Id)).ToList();
                            Summary atmk2 = new Summary();
                            atmk2.Total = atmkey_barcode.Count();
                            atmk2.Date = tmpdtm;
                            atmk2.Branck = item.Name;
                            atmk2.Item = "ATM key";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1atmkey = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "181" && !a.Deleted).Count();
                            int p2atmkey = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                            .Where(a => a.FLG == 10).Where(a => a.LogTag == "181" && !a.Deleted && a.ProjectId == item.Id).Count();
                            atmk2.Issued = (p1atmkey + p2atmkey); //atmkey.Where(a => a.keyState == Models.Constraints.KeyStates.KeyStates_Out).Count(); // Sum(a => a.keyState);
                            atmk2.Damaged = 0;  //(PDA.Count(a => a.IsDamage)).ToStr(); 
                            int r1atmkey = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "181" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2atmkey = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "181" && !a.Deleted).Where(a => a.FLG == 20).Count();

                            atmk2.Returned = (r1atmkey + r2atmkey);//atmkey.Where(a => a.keyState == Models.Constraints.KeyStates.KeyStates_Returned).Count();
                            Summlist.Add(atmk2);


                            var atmkeybei = KeyPasswordssss.Where(a => !a.Deleted).Where(a => a.ProjectId == item.Id && a.KeyPasswordType == Models.Constraints.KeyPasswordTypes.KeyByPasswordTypes_KEY).Select(a => new { a.AtmBarCodeId, a.keyState }).ToList();
                            List<Guid> atmkeybarcodebei = atmkeybei.Select(a => a.AtmBarCodeId).ToList();
                            var atmkey_barcodebei = atmbar.Where(a => atmkeybarcodebei.Contains(a.Id)).ToList();
                            Summary atmk2bei = new Summary();
                            atmk2bei.Total = atmkey_barcodebei.Count();
                            atmk2bei.Date = tmpdtm;
                            atmk2bei.Branck = item.Name;
                            atmk2bei.Item = "AtmSpareKey";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1atmkeybei = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "182" && !a.Deleted).Count();
                            int p2atmkeybei = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                            .Where(a => a.FLG == 10).Where(a => a.LogTag == "182" && !a.Deleted && a.ProjectId == item.Id).Count();
                            atmk2bei.Issued = (p1atmkeybei + p2atmkeybei); //atmkey.Where(a => a.keyState == Models.Constraints.KeyStates.KeyStates_Out).Count(); // Sum(a => a.keyState);
                            atmk2bei.Damaged = 0;  //(PDA.Count(a => a.IsDamage)).ToStr(); 
                            int r1atmkeybei = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "182" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2atmkeybei = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "182" && !a.Deleted).Where(a => a.FLG == 20).Count();

                            atmk2bei.Returned = (r1atmkeybei + r2atmkeybei);//atmkey.Where(a => a.keyState == Models.Constraints.KeyStates.KeyStates_Returned).Count();
                            Summlist.Add(atmk2bei);



                            //




                            //PDA
                            var PDA = AtmPdasssss.Where(a => a.ProjectId == item.Id).Select(a => new { a.AtmBarCodeId }).ToList();
                            List<Guid> PDAbarcode = PDA.Select(a => a.AtmBarCodeId).ToList();
                            var PDA_barcode = atmbar.Where(a => PDAbarcode.Contains(a.Id)).ToList();
                            Summary sm2 = new Summary();
                            sm2.Total = PDA_barcode.Count();
                            sm2.Date = tmpdtm;
                            sm2.Branck = item.Name;
                            sm2.Item = "PDA";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1pda = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "PDA" && !a.Deleted).Count();
                            int p2pda = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                .Where(a => a.FLG == 10).Where(a => a.LogTag == "PDA" && !a.Deleted && a.ProjectId == item.Id).Count();
                            sm2.Issued = (p1pda + p2pda);
                            sm2.Damaged = 0;  //(PDA.Count(a => a.IsDamage)).ToStr(); 
                            int r1pda = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "PDA" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2pda = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "PDA" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            sm2.Returned = (r1pda + r2pda);
                            Summlist.Add(sm2);

                            //MobilePhone
                            var MobilePhone = WorkingTELssss.Where(a => a.ProjectId == item.Id).Select(a => new { a.IsDamage, a.AtmBarCodeId }).ToList();
                            List<Guid> MobilePhonebarcode = MobilePhone.Select(a => a.AtmBarCodeId).ToList();
                            var MobilePhone_barcode = atmbar.Where(a => MobilePhonebarcode.Contains(a.Id)).ToList();
                            Summary sm3 = new Summary();
                            sm3.Total = MobilePhone_barcode.Count();
                            sm3.Date = tmpdtm;
                            sm3.Branck = item.Name;
                            sm3.Item = "MobilePhone";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1MobilePhone = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "185" && !a.Deleted).Count();
                            int p2MobilePhone = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                .Where(a => a.FLG == 10).Where(a => a.LogTag == "185" && !a.Deleted && a.ProjectId == item.Id).Count();
                            sm3.Issued = (p1MobilePhone + p2MobilePhone);
                            sm3.Damaged = (MobilePhone.Count(a => a.IsDamage));
                            int r1MobilePhone = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "185" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2MobilePhone = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "185" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            sm3.Returned = (r1MobilePhone + r2MobilePhone);
                            Summlist.Add(sm3);

                            //Vehicle key





                            //Vehicle
                            var AtmTrucks = AtmTrucksssss.Where(a => a.ProjectId == item.Id).Select(a => new { a.AtmBarCodeId }).ToList();
                            List<Guid> AtmTrucksbarcode = AtmTrucks.Select(a => a.AtmBarCodeId).ToList();
                            var AtmTrucks_barcode = atmbar.Where(a => AtmTrucksbarcode.Contains(a.Id)).ToList();
                            Summary sm4 = new Summary();
                            sm4.Total = AtmTrucks_barcode.Count();
                            sm4.Date = tmpdtm;
                            sm4.Branck = item.Name;
                            sm4.Item = "Vehicle";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1Vehicle = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "186" && !a.Deleted).Count();
                            int p2Vehicle = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                .Where(a => a.FLG == 10).Where(a => a.LogTag == "186" && !a.Deleted && a.ProjectId == item.Id).Count();
                            sm4.Issued = (p1Vehicle + p2Vehicle);
                            sm4.Damaged = 0;  //(AtmTrucks.Count(a => a.IsDamage)).ToStr();
                            int r1Vehicle = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "186" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2Vehicle = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "186" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            sm4.Returned = (r1Vehicle + r2Vehicle);
                            Summlist.Add(sm4);
                            //

                            //Navigator
                            var GPSNavigator = GPSNavigatorsss.Where(a => a.ProjectId == item.Id).Select(a => new { a.AtmBarCodeId }).ToList();
                            List<Guid> GPSNavigatorbarcode = GPSNavigator.Select(a => a.AtmBarCodeId).ToList();
                            var GPSNavigatorbarcode_barcode = atmbar.Where(a => GPSNavigatorbarcode.Contains(a.Id)).ToList();
                            Summary sm5 = new Summary();
                            sm5.Total = GPSNavigatorbarcode_barcode.Count();
                            sm5.Date = tmpdtm;
                            sm5.Branck = item.Name;
                            sm5.Item = "Navigator";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1Navigator = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "195" && !a.Deleted).Count();
                            int p2Navigator = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                .Where(a => a.FLG == 10).Where(a => a.LogTag == "195" && !a.Deleted && a.ProjectId == item.Id).Count();
                            sm5.Issued = (p1Navigator + p2Navigator);
                            sm5.Damaged = 0;  //(AtmTrucks.Count(a => a.IsDamage)).ToStr();
                            int r1Navigator = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "195" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2Navigator = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "195" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            sm5.Returned = (r1Navigator + r2Navigator);
                            Summlist.Add(sm5);

                            //EasyPassTag
                            var EasyPassTag = EasyPassTagssss.Where(a => a.ProjectId == item.Id).Select(a => new { a.AtmBarCodeId }).ToList();
                            List<Guid> EasyPassTagbarcode = EasyPassTag.Select(a => a.AtmBarCodeId).ToList();
                            var EasyPassTagbarcode_barcode = atmbar.Where(a => EasyPassTagbarcode.Contains(a.Id)).ToList();
                            Summary sm6 = new Summary();
                            sm6.Total = EasyPassTagbarcode_barcode.Count();
                            sm6.Date = tmpdtm;
                            sm6.Branck = item.Name;
                            sm6.Item = "EasyPassTag";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1EasyPassTag = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "194" && !a.Deleted).Count();
                            int p2EasyPassTag = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                .Where(a => a.FLG == 10).Where(a => a.LogTag == "194" && !a.Deleted && a.ProjectId == item.Id).Count();
                            sm6.Issued = (p1EasyPassTag + p2EasyPassTag);
                            sm6.Damaged = 0;  //(AtmTrucks.Count(a => a.IsDamage)).ToStr();
                            int r1EasyPassTag = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "194" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2EasyPassTag = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "194" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            sm6.Returned = (r1EasyPassTag + r2EasyPassTag);
                            Summlist.Add(sm6);

                            //AdminCard
                            var ATMPassCards = ATMPassCardsssss.Where(a => a.ProjectId == item.Id).Select(a => new { a.BarCodeId }).ToList();
                            List<Guid> ATMPassCardsbarcode = ATMPassCards.Select(a => a.BarCodeId).ToList();
                            var ATMPassCardsbarcode_barcode = atmbar.Where(a => ATMPassCardsbarcode.Contains(a.Id)).ToList();
                            Summary sm7 = new Summary();
                            sm7.Total = ATMPassCardsbarcode_barcode.Count();
                            sm7.Date = tmpdtm;
                            sm7.Branck = item.Name;
                            sm7.Item = "AdminCard";
                            //var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            int p1AdminCard = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "99" && !a.Deleted).Count();
                            int p2AdminCard = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                .Where(a => a.FLG == 10).Where(a => a.LogTag == "99" && !a.Deleted && a.ProjectId == item.Id).Count();
                            sm7.Issued = (p1AdminCard + p2AdminCard);
                            sm7.Damaged = 0;  //(AtmTrucks.Count(a => a.IsDamage)).ToStr();
                            int r1AdminCard = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == "99" && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                            int r2AdminCard = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "99" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            sm7.Returned = (r1AdminCard + r2AdminCard);
                            Summlist.Add(sm7);




                            //Other

                            var OtherBarcode = OtherBarcodessss.Where(a => a.ProjectId == item.Id).Select(a => new { a.AtmBarCodeId, a.BarCodeType }).ToList();

                            foreach (var othertype in OtherBarcode.Distinct(a => a.BarCodeType))
                            {
                                List<Guid> OtherBarcodebarcode = OtherBarcode.Where(a => a.BarCodeType == othertype.BarCodeType)
                                    .Select(a => a.AtmBarCodeId).ToList();
                                var OtherBarcodebarcode_barcode = atmbar.Where(a => OtherBarcodebarcode.Contains(a.Id)).ToList();
                                Summary ot8 = new Summary();
                                ot8.Total = OtherBarcodebarcode_barcode.Count();
                                ot8.Date = tmpdtm;
                                ot8.Branck = item.Name;
                                ot8.Item = othertype.BarCodeType;
                                var dictid = dictbo.FirstOrDefault(a => a.DictName == othertype.BarCodeType) != null ? dictbo.FirstOrDefault(a => a.DictName == othertype.BarCodeType).DictDisplayName : "";
                                int p1Other = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == dictid && !a.Deleted).Count();
                                int p2Other = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm)
                                    .Where(a => a.FLG == 10).Where(a => a.LogTag == dictid && !a.Deleted && a.ProjectId == item.Id).Count();
                                ot8.Issued = (p1Other + p2Other);
                                ot8.Damaged = 0;
                                int r1Other = db.PersonGoodss.Where(a => a.CreatedDate >= tmpdtm && a.CreatedDate < tmpenddtm).Where(a => a.LogTag == dictid && !a.Deleted && a.ProjectId == item.Id).Where(a => a.FLG == 20).Count();
                                int r2Other = LineLogisticsssss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == dictid && !a.Deleted).Where(a => a.FLG == 20).Count();
                                ot8.Returned = (r1Other + r2Other);
                                Summlist.Add(ot8);
                            }


                            //List<Guid> OtherBarcodebarcode = OtherBarcode.Select(a => a.AtmBarCodeId).ToList();
                            //var OtherBarcodebarcode_barcode = db.AtmBarCodes.Where(a => !a.Deleted).Where(a => OtherBarcodebarcode.Contains(a.Id)).ToList();
                            //Summary sm8 = new Summary();
                            //sm8.Total = OtherBarcodebarcode_barcode.Count().ToStr();
                            //sm8.Date = tmpdtm;
                            //sm8.Branck = item.Name;
                            //sm8.Item = "Other";
                            ////var lineids = linedets.Where(a => a.TaskTime == tmpdtm && a.ProjectId == item.Id).Select(a => a.Id).ToList();
                            //int p1Other = db.LineLogisticss.Where(a => lineids.Contains(a.LineInfoId) && a.PState >= 40 && a.LogTag == "100052" && !a.Deleted).Count();
                            //int p2Other = db.PersonGoodss.Where(a => a.CreatedDate > tmpdtm && a.CreatedDate <= tmpenddtm)
                            //    .Where(a => a.FLG == 10).Where(a => a.LogTag == "100052" && !a.Deleted && a.ProjectId == item.ProjectId).Count();
                            //sm8.Issued = (p1Other + p2Other).ToStr();
                            //sm8.Damaged = "";  //(AtmTrucks.Count(a => a.IsDamage)).ToStr();
                            //int r1Other = db.PersonGoodss.Where(a => a.CreatedDate > tmpdtm && a.CreatedDate <= tmpenddtm).Where(a => a.LogTag == "100052" && !a.Deleted && a.ProjectId == item.ProjectId).Where(a => a.FLG == 20).Count();
                            //int r2Other = db.LineLogisticss.Where(a => lineids.Contains(a.LineInfoId)).Where(a => a.LogTag == "100052" && !a.Deleted).Where(a => a.FLG == 20).Count();
                            //sm8.Returned = (r1Other + r2Other).ToStr();
                            //Summlist.Add(sm8);
                        }
                        int cnt = Summlist.Count();

                        tmpdtm = st.AddDays(dayint);
                        dayint++;
                    }
                }
                var cntsd = Summlist.Count;

                List<IMongoQuery> list1 = new List<IMongoQuery>();
                list1.Add(Query.GTE("Date", st));
                list1.Add(Query.LT("Date", et));

                IMongoQuery query = Query.And(list1);
                Common.MongodbHelper.Remove<Summary>(query, "table_Summary");
                Common.MongodbHelper.Add_List<Summary>("table_Summary", Summlist);
                showLog("Summary", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                insertShowlog("Summary----Count" + cntsd, st, et);
            }
            catch (Exception ex)
            {
                showLog("Summary", "Error:" + ex.ToString());
                insertShowlog("Summary----Error" + ex.ToString(), st, et);
            }
            insertShowlog("Summary----End", st, et);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value;
            Issuereturn(st, et);
        }

        private void Issuereturn(DateTime st, DateTime et)
        {
            showLog("Issuereturn", "Start");
            insertShowlog("Issuereturn----Start", st, et);
            List<Issuereturn> Issuereturnlist = new List<Issuereturn>();

            //DateTime st = DateTime.Now.Date;
            //DateTime et = st.AddDays(1);
            //DateTime st = new DateTime(2018, 7, 1);
            //DateTime et = new DateTime(2018, 10, 1);
            DateTime tmpdtm = st;
            try
            {
                using (var db = new ApplicationDb())
                {
                    var projs = db.SysProjects.Where(a => !a.Deleted).ToList();
                    //var lineLogistic = db.LineLogisticss.Where(a => !a.Deleted && a.LineInfoof.TaskTime >= st & a.LineInfoof.TaskTime < et).Select(a => new { a.LineInfoof.TaskTime, a.OutDateTime, a.InDateTime, a.ProjectId, a.LineInfoof.LineName, a.LineInfoof.Driver, a.LineInfoof.CarCaptain, a.LineInfoof.OtherPeople, a.AtmAtmOf.AtmNo, a.AtmAtmOf.ATMName, a.BarCode, a.Id, a.LogTag }).ToList();
                    //var lineLogistic = (from a in db.LineLogisticss
                    //                    join abc in db.AtmBarCodes on a.BarCode equals abc.BarCode into joinTemp1
                    //                    from tmp1 in joinTemp1.DefaultIfEmpty()
                    //                    where !a.Deleted && a.LineInfoof.TaskTime >= st && a.LineInfoof.TaskTime < et
                    //                    select new { a.LineInfoof.TaskTime, a.OutDateTime, a.InDateTime, a.ProjectId, a.LineInfoof.LineName, a.LineInfoof.Driver, a.LineInfoof.CarCaptain, a.LineInfoof.OtherPeople, a.AtmAtmOf.AtmNo, a.AtmAtmOf.ATMName, a.BarCode, a.Id, a.LogTag, barid = (tmp1 == null ? Guid.Empty : tmp1.Id) }).ToList();

                    var lineLogistic = (from a in db.LineLogisticss.Where(c => c.LineInfoof.TaskTime >= st && c.LineInfoof.TaskTime < et)
                                        select
                                            new
                                            {
                                                a.LineInfoof.TaskTime,
                                                a.OutDateTime,
                                                a.InDateTime,
                                                a.ProjectId,
                                                a.LineInfoof.LineName,
                                                a.LineInfoof.Driver,
                                                a.LineInfoof.CarCaptain,
                                                a.LineInfoof.OtherPeople,
                                                a.AtmAtmOf.AtmNo,
                                                a.AtmAtmOf.ATMName,
                                                a.BarCode,
                                                a.Id,
                                                a.LogTag,
                                                a.Deleted,
                                                a.DepotOutUser,
                                                a.DepotInUser
                                            }).ToList();
                    lineLogistic = lineLogistic.Where(a => !a.Deleted).ToList();
                    // cl cd cm
                    var clcdcm = lineLogistic.Select(a => a.Driver).Union(lineLogistic.Select(a => a.CarCaptain)).Union(lineLogistic.Select(a => a.OtherPeople)).ToList();
                    var sysusers = db.SysUsers.Where(a => clcdcm.Contains(a.WorkerId)).ToList();

                    var barcodelist = lineLogistic.Where(a => !string.IsNullOrWhiteSpace(a.BarCode)).Select(a => a.BarCode).Distinct().ToList();
                    var baridlist = db.AtmBarCodes.Where(a => barcodelist.Contains(a.BarCode)).Select(a => new
                    {
                        a.BarCode,
                        a.Id
                    }).ToList();
                    List<string> userinfo = new List<string>();
                    userinfo.AddRange(lineLogistic.Select(a => a.DepotInUser).Union(lineLogistic.Select(a => a.DepotOutUser)));
                    var UserDepot = db.SysUsers.Where(a => userinfo.Contains(a.WorkerId)).ToList();
                    int dayint = 1;
                    var dictbo = db.SysDictBos.ToList();
                    SysProject ppr = new SysProject();
                    //AtmBarCode barcode = new AtmBarCode();
                    //while (tmpdtm <= et)    // 时间
                    //{
                    var tmpenddtm = tmpdtm.AddDays(1);
                    SysUser sy = new SysUser();
                    Gun Gun = new Gun();
                    var atmtrucks = db.AtmTrucks.ToList();
                    //Where(a => !string.IsNullOrEmpty(a.BarCode))
                    SysUser suclcdcm = new SysUser();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "191")) //Gun
                    {
                        //取机具不直接显示出来    循环里面 不写db
                        Issuereturn It = new Issuereturn();
                        It.Item = "Gun";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;
                        //-- 
                        //CarCaptain =cl
                        //Driver=cd
                        //OtherPeople=cm
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        //barcode = db.AtmBarCodes.FirstOrDefault(a => a.BarCode == item.BarCode);
                        //if (barcode != null)
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            Gun = db.Guns.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        }
                        if (Gun != null)
                        {
                            It.Remark = Gun.Remark;
                            It.AssetCode = Gun.GunNo;
                            It.Description = Gun.Remark;
                            It.SerialNumber = Gun.GunNo;
                        }
                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }

                        It.Barcode = item.BarCode;

                        Issuereturnlist.Add(It);
                    }

                    KeyPassword kp = new KeyPassword();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "181" || a.LogTag == "182"))  //atm key  spare key
                    {//
                        Issuereturn It = new Issuereturn();
                        It.Item = "ATM key";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;
                        //--
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");

                        It.ATMID = item.AtmNo;
                        It.Name = item.ATMName;  //Location name
                        //barcode = db.AtmBarCodes.FirstOrDefault(a => a.BarCode == item.BarCode);
                        //if (barcode != null)
                        //{
                        //    kp = db.KeyPasswords.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        //}
                        It.Key = item.BarCode;   //Barcode
                        //if(kp.KeyPasswordType == Models.Constraints.KeyPasswordTypes.KeyPasswordTypes_KEY)
                        //{
                        //    It.Remark ="Key";
                        //}
                        // if(kp.KeyPasswordType == Models.Constraints.KeyPasswordTypes.KeyByPasswordTypes_KEY)
                        //{
                        //    It.Remark ="Spare Key";
                        //}

                        if ((item.BarCode ?? "").Contains("181"))
                        {
                            It.KeySparekey = "Key";
                            //It.Remark = "Key";
                        }
                        if ((item.BarCode ?? "").Contains("182"))
                        {
                            It.KeySparekey = "Spare key";
                            //It.Remark = "Spare Key";
                        }


                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            kp = db.KeyPasswords.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        }
                        if (kp != null)
                        {
                            It.ATMShortcode = kp.AtmAtm != null ? kp.AtmAtm.TerminalNum : "";
                            It.Customer = kp.AtmCustomer != null ? kp.AtmCustomer.Name : "";
                            It.Remark = kp.Remark;
                        }
                        Issuereturnlist.Add(It);
                    }

                    ////PDA
                    AtmPda pda = new AtmPda();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "PDA"))
                    {//
                        Issuereturn It = new Issuereturn();
                        It.Item = "PDA";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;

                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        It.ItemBarcode = item.BarCode;
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            pda = db.AtmPdas.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        }
                        if (pda != null)
                        {
                            It.Name = pda.Name;
                            It.Number = pda.IMEI;
                            It.Model = pda.PdaModel;
                            It.Customer = pda.SIM;
                            switch (pda.PdaUseType)
                            {
                                case PdaUsed.Use_ZY:
                                    It.Remark = "Replenishment";
                                    break;
                                case PdaUsed.Use_PD:
                                    It.Remark = "Dispatch";
                                    break;
                                case PdaUsed.Use_Preload:
                                    It.Remark = "Cassette Management";
                                    break;
                            }
                            It.IMEI = pda.IMEI;
                            It.Brand = pda.Brand;
                        }
                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        Issuereturnlist.Add(It);
                    }


                    //MobilePhone
                    WorkingTEL MobilePhone = new WorkingTEL();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "185"))
                    {//
                        Issuereturn It = new Issuereturn();
                        It.Item = "MobilePhone";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        It.ItemBarcode = item.BarCode;
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            MobilePhone = db.WorkingTELs.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        }
                        if (MobilePhone != null)
                        {
                            It.Name = MobilePhone.WorkerId;
                            It.Number = MobilePhone.IMEI;
                            It.Model = MobilePhone.BUType;
                            It.Customer = MobilePhone.SIM;
                            It.Remark = MobilePhone.Remark;
                            It.StaffName = MobilePhone.UserName;
                            It.StaffID = MobilePhone.WorkerId;
                            //MobilePhone.s
                        }
                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        Issuereturnlist.Add(It);
                    }


                    //Vehicle
                    //AtmTruck atk = new AtmTruck();
                    TruckKey atk = new TruckKey();
                    AtmTruck at = new AtmTruck();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "186"))
                    {//
                        Issuereturn It = new Issuereturn();
                        It.Item = "Vehicle";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            //atk = db.AtmTrucks.FirstOrDefault(a => a.AtmBarCodeId == item.barid);
                            atk = db.TruckKeys.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        }
                        if (atk != null)
                        {
                            //It.CallSign = atk.Radio;
                            at = atmtrucks.Where(a => a.ATMkeyCodeID == atk.AtmBarCodeId).FirstOrDefault();
                            if (at != null)
                            {
                                It.CallSign = at.Radio;
                                It.LicensePlate = at.PlateNumber;
                                It.Brand = at.Brand;
                                It.Model = at.BusModel;
                                It.Category = at.TruckCompany == null ? "" : at.TruckCompany.Name;
                                It.Remark = at.Remark;
                                It.TruckType = at.truckType.ToStr();
                            }
                        }
                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        It.BarcodeKey = item.BarCode;
                        Issuereturnlist.Add(It);
                    }
                    //

                    //Navigator
                    GPSNavigator gps = new GPSNavigator();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "195"))
                    {//
                        Issuereturn It = new Issuereturn();
                        It.Item = "Navigator";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        It.ItemBarcode = item.BarCode;
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            gps = db.GPSNavigator.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        }
                        if (gps != null)
                        {
                            It.Name = gps.Brand;
                            It.Number = "";
                            It.Model = gps.Type;
                            It.Customer = "";
                            It.Remark = gps.Remark;
                        }
                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        Issuereturnlist.Add(It);
                    }


                    //EasyPassTag
                    EasyPassTag ept = new EasyPassTag();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "194"))
                    {//
                        Issuereturn It = new Issuereturn();
                        It.Item = "EasyPassTag";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        It.ItemBarcode = item.BarCode;
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            ept = db.EasyPassTag.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                        }
                        if (ept != null)
                        {
                            It.Name = ept.RegistrationNo;
                            It.Number = ept.EasypassTagNumber;
                            It.Model = ept.CallsignNo;
                            It.Remark = ept.Remark;
                            It.CardNumber = ept.EasypassCardNumber;
                            It.RegisterProvince = ept.RegisterProvince;
                        }
                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        It.Customer = "";
                        Issuereturnlist.Add(It);
                    }

                    //AdminCard
                    ATMPassCard apc = new ATMPassCard();
                    foreach (var item in lineLogistic.Where(a => a.LogTag == "99"))
                    {//
                        Issuereturn It = new Issuereturn();
                        It.Item = "AdminCard";
                        ppr = projs.FirstOrDefault(a => a.Id == item.ProjectId);
                        It.Branch = ppr.Name;
                        It.Branchcode = ppr.Code;
                        It.JobDate = item.TaskTime;
                        It.IssueTime = item.OutDateTime;
                        It.ReturnTime = item.InDateTime;
                        It.Route = item.LineName;
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        It.CL = item.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.Driver);
                        It.CD = item.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        It.CM = item.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                        It.ItemBarcode = item.BarCode;
                        var barcode = baridlist.FirstOrDefault(a => a.BarCode == item.BarCode);
                        if (barcode != null)
                        {
                            apc = db.ATMPassCards.FirstOrDefault(a => a.BarCodeId == barcode.Id);
                        }
                        if (apc != null)
                        {
                            It.Number = apc.Number;
                            switch (apc.AtmTypeID)
                            {
                                case JobTypes.JobTypes_Deposit:
                                    It.Model = "CDM";
                                    break;
                                case JobTypes.JobTypes_WithDrawal:
                                    It.Model = "ATM";
                                    break;
                                case JobTypes.JobTypes_Recycling:
                                    It.Model = "RATM";
                                    break;
                                case JobTypes.JobTypes_AllInOne:
                                    It.Model = "3INI";
                                    break;
                                case JobTypes.JobTypes_Other:
                                    It.Model = "Other ATMs";
                                    break;
                            }
                            It.Customer = apc.AtmCustomer == null ? "" : apc.AtmCustomer.Name;
                            It.Remark = apc.Remark;
                            It.Password = apc.Password;
                            It.Name = apc.CardId;
                            //apc.CardId

                        }
                        if (!string.IsNullOrEmpty(item.DepotOutUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotOutUser);
                            It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        if (!string.IsNullOrEmpty(item.DepotInUser))
                        {
                            sy = UserDepot.FirstOrDefault(a => a.WorkerId == item.DepotInUser);
                            It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                        }
                        Issuereturnlist.Add(It);
                    }

                    //Other
                    var OtherBarcode = new OtherBarcode();
                    var otheres = db.OtherBarcode.Where(a => !a.Deleted).Select(a => new { a.AtmBarCodeId, a.BarCodeType }).ToList();
                    var otherds = otheres.Distinct(a => a.BarCodeType);
                    //取  物品的类型   LogTag
                    foreach (var item in otherds)
                    {
                        var DictDisplayName = db.SysDictBos.Where(a => a.CustomtypeId == Customtype.OtherBarCode && !a.Deleted).Where(a => a.DictName == item.BarCodeType).FirstOrDefault();//DictDisplayName
                        if (DictDisplayName != null)
                        {
                            foreach (var item2 in lineLogistic.Where(a => a.LogTag == DictDisplayName.DictDisplayName))
                            {
                                Issuereturn It = new Issuereturn();
                                //It.Item = "other";
                                It.Item = item.BarCodeType;
                                ppr = projs.FirstOrDefault(a => a.Id == item2.ProjectId);
                                It.Branch = ppr.Name;
                                It.Branchcode = ppr.Code;
                                It.JobDate = item2.TaskTime;
                                It.IssueTime = item2.OutDateTime;
                                It.ReturnTime = item2.InDateTime;
                                It.Route = item2.LineName;
                                suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item2.CarCaptain);
                                It.CL = item2.CarCaptain + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                                suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item2.Driver);
                                It.CD = item2.Driver + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                                suclcdcm = sysusers.FirstOrDefault(a => a.WorkerId == item2.OtherPeople);
                                It.CM = item2.OtherPeople + (suclcdcm != null ? "(" + suclcdcm.f_name_TH + " " + suclcdcm.l_name_TH + ")" : "");
                                It.ItemBarcode = item2.BarCode;
                                var barcode = baridlist.FirstOrDefault(a => a.BarCode == item2.BarCode);
                                if (barcode != null)
                                {
                                    OtherBarcode = db.OtherBarcode.FirstOrDefault(a => a.AtmBarCodeId == barcode.Id);
                                }
                                if (OtherBarcode != null)
                                {
                                    It.Name = OtherBarcode.ItemName;
                                    It.Number = OtherBarcode.Number;
                                    It.Model = OtherBarcode.Models;
                                    It.Customer = OtherBarcode.AtmCustomer == null ? "" : OtherBarcode.AtmCustomer.Name;
                                    It.Remark = OtherBarcode.Remark;
                                }
                                if (!string.IsNullOrEmpty(item2.DepotOutUser))
                                {
                                    sy = UserDepot.FirstOrDefault(a => a.WorkerId == item2.DepotOutUser);
                                    It.DispatchIssued = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                                }
                                if (!string.IsNullOrEmpty(item2.DepotInUser))
                                {
                                    sy = UserDepot.FirstOrDefault(a => a.WorkerId == item2.DepotInUser);
                                    It.DispatchReturned = sy != null ? (sy.UserName + " (" + sy.WorkerId + ")") : "";
                                }
                                Issuereturnlist.Add(It);
                            }
                        }
                    }
                    int cnt = Issuereturnlist.Count();
                    tmpdtm = st.AddDays(dayint);
                    dayint++;
                }
                //}
                var cntsd = Issuereturnlist.Count;
                List<IMongoQuery> list1 = new List<IMongoQuery>();
                list1.Add(Query.GTE("JobDate", st));
                list1.Add(Query.LT("JobDate", et));
                IMongoQuery query = Query.And(list1);
                Common.MongodbHelper.Remove<Issuereturn>(query, "table_Issuereturn");
                Common.MongodbHelper.Add_List<Issuereturn>("table_Issuereturn", Issuereturnlist);

                showLog("Issuereturn", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                insertShowlog("Issuereturn----Count" + cntsd, st, et);
            }
            catch (Exception ex)
            {

                showLog("Issuereturn", "Error:" + ex.ToString());
                insertShowlog("Issuereturn----Error" + ex.ToString(), st, et);
            }
            insertShowlog("Issuereturn----End", st, et);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value;
            summary_total_hours_route(st, et.AddDays(1));
        }
        //summary total hours route 
        private void summary_total_hours_route(DateTime st, DateTime et)
        {
            showLog("summary_total_hours_route", "Start");
            insertShowlog("summary_total_hours_route----Start", st, et);
            //DateTime st = DateTime.Now.Date;
            //DateTime et = st.AddDays(1);
            //DateTime st = new DateTime(2018, 7, 1);
            //DateTime et = new DateTime(2018, 10, 1);
            //DateTime tmpdtm = st;
            try
            {
                using (var db = new ApplicationDb())
                {
                    var projs = db.SysProjects.ToList();
                    //var LineInfos = db.LineInfos.Where(a => !a.Deleted).Where(a => a.TaskTime >= st && a.TaskTime < et).ToList();
                    var LineInfos = db.LineInfos.Where(a => !a.Deleted).Where(a => a.TaskTime >= st && a.TaskTime < et).Include("AtmTruck").ToList();
                    List<Guid> AllotGroupIdList = LineInfos.Where(a => a.AllotGroupId != null).Select(a => a.AllotGroupId.Value).ToList();
                    var WeeklyPlanDetailsID = db.WeeklyPlanDetails.Where(a => AllotGroupIdList.Contains(a.Id)).ToList();


                    List<Guid> LineIds = LineInfos.Select(a => a.Id).ToList();
                    var TaskLogs = db.AtmTaskLogs.Where(a => LineIds.Contains(a.LineInfoId.Value)).ToList();
                    //var BankIds = db.LineGoodss.Where(a => !a.Deleted).Where(a => LineIds.Contains(a.LineInfoId)).Select(a => a.BankOrderOf);
                    //var BankOrders = db.BankOrders;
                    //var Repairs = db.Repairs;
                    //var Inspections = db.Inspections;
                    List<AtmTaskLog> atmtasklogs = new List<AtmTaskLog>();

                    //LineInfos.FirstOrDefault().AtmTruck
                    List<string> workerids = new List<string>();
                    workerids = LineInfos.Select(a => a.CarCaptain).Union(LineInfos.Select(a => a.Driver)).Union(LineInfos.Select(a => a.OtherPeople)).ToList();
                    var users = db.SysUsers.Where(a => workerids.Contains(a.WorkerId)).ToList();
                    var LineinfoIdIDs = LineInfos.Select(a => a.Id);
                    var linegoods = db.LineGoodss.Where(a => LineinfoIdIDs.Contains(a.LineInfoId)).ToList();
                    var bankID = linegoods.Select(a => a.BankOrderID).ToList();
                    var AtmSysLogs = db.AtmSysLogs.Where(a => bankID.Contains(a.SysUserId)).ToList();
                    List<AtmSysLog> asls = new List<AtmSysLog>();
                    List<Guid?> LineinfoLinegoods = new List<Guid?>();
                    SqlConnection conn = new SqlConnection(SiteConst.DisableUser);
                    DataTable dt = new DataTable();
                    List<StaffWork> stafflist = new List<StaffWork>();
                    StaffWork sfw = new StaffWork();
                    List<RouteTotal> RouteTotal = new List<RouteTotal>();
                    WeeklyPlanDetail wpdsdtmp = new WeeklyPlanDetail();
                    try
                    {
                        conn.Open();
                        string sql = "select * from stander_id  where sj BETWEEN '" + st + "' and '" + et + "'";
                        SqlCommand cmd = new SqlCommand(sql, conn);
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
                        if (dt.Rows.Count > 0)
                        {
                            stafflist = EntityConvert.GetEntities<StaffWork>(dt);
                        }
                    }
                    catch (Exception e)
                    {
                        showLog("SQLServer", e.Message);
                        insertShowlog("SQLServer----Error " + e.Message, st, et);
                    }
                    finally
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                    SysUser user1 = new SysUser();
                    SysUser user2 = new SysUser();
                    SysUser user3 = new SysUser();
                    AtmTaskLog t1 = new AtmTaskLog();
                    AtmTruck atk = new AtmTruck();
                    int Crewno = 0;

                    //换人换车
                    SortByDocument sbd = new SortByDocument();
                    IMongoQuery queryss = null;
                    List<IMongoQuery> list = new List<IMongoQuery>();
                    List<IMongoQuery> mq = new List<IMongoQuery>();
                    List<IMongoQuery> mq3 = new List<IMongoQuery>();
                    List<Linelog> Linelog = new List<Linelog>();
                    if (LineInfos.Count > 1)
                    {
                        foreach (var item in LineInfos.Select(A => A.Id))
                        {
                            mq.Add(Query.Matches("Lineid", item.ToStr()));
                        }
                        mq3.Add(Query.Matches("Content", "Change Vehicle"));
                        mq3.Add(Query.Matches("Content", "Change Crew"));
                        list.Add(Query.Or(mq));
                        list.Add(Query.Or(mq3));
                        queryss = Query.And(list);
                        Linelog = Common.MongodbHelper.FindListBy<Linelog>(queryss, sbd, "Log_Line");
                    }
                    else if (LineInfos.Count == 1)
                    {
                        mq3.Add(Query.Matches("Content", "Change Vehicle"));
                        mq3.Add(Query.Matches("Content", "Change Crew"));
                        list.Add(Query.Matches("Lineid", LineInfos[0].Id.ToStr()));
                        list.Add(Query.Or(mq3));
                        queryss = Query.And(list);
                        Linelog = Common.MongodbHelper.FindListBy<Linelog>(queryss, sbd, "Log_Line");
                    }
                    else
                    {

                    }

                    DateTime? temdateas = null;
                    foreach (var item in LineInfos)
                    {
                        RouteTotal rt = new RouteTotal();
                        rt.JobDate = item.TaskTime;
                        rt.Remark = item.TaskTime.ToShortDateString();
                        rt.Branch = projs.FirstOrDefault(a => a.Id == item.ProjectId).Name;
                        rt.RouteName = item.LineName;
                        user1 = users.FirstOrDefault(a => a.WorkerId == item.CarCaptain);
                        user2 = users.FirstOrDefault(a => a.WorkerId == item.Driver);
                        user3 = users.FirstOrDefault(a => a.WorkerId == item.OtherPeople);
                        if (user1 != null)
                            rt.CrewLeader = user1.f_name_eng + " " + user1.l_name_eng + "(" + item.CarCaptain + ")";
                        if (user2 != null)
                            rt.CrewDriver = user2.f_name_eng + " " + user2.l_name_eng + "(" + item.Driver + ")";
                        if (user3 != null)
                            rt.CrewMember = user3.f_name_eng + " " + user3.l_name_eng + "(" + item.OtherPeople + ")";

                        //fx=1 表示上班(Finger Scan in)  fx=2表示下班(Finger Scan Out)
                        if (!string.IsNullOrEmpty(item.CarCaptain))
                        {//rt.FingerScanin    rt.FingerScanOut
                            sfw = stafflist.Where(a => a.user_no == item.CarCaptain && a.fx == 1).Where(a => a.sj.Date == item.TaskTime.Date).OrderBy(a => a.sj).FirstOrDefault();
                            if (sfw != null)
                                rt.CrewLeaderScanIn = sfw.sj;

                            sfw = stafflist.Where(a => a.user_no == item.CarCaptain && a.fx == 2).Where(a => a.sj.Date == item.TaskTime.Date).OrderByDescending(a => a.sj).FirstOrDefault();
                            if (sfw != null)
                                rt.CrewLeaderScanOut = sfw.sj;
                            //var sdsss = stafflist.Where(a => a.user_no == item.CarCaptain && a.fx == 2);
                        }
                        if (!string.IsNullOrEmpty(item.Driver))
                        {//rt.FingerScanin    rt.FingerScanOut
                            sfw = stafflist.Where(a => a.user_no == item.Driver && a.fx == 1).Where(a => a.sj.Date == item.TaskTime.Date).OrderBy(a => a.sj).FirstOrDefault();
                            if (sfw != null)
                                rt.CrewDriverScanIn = sfw.sj;

                            sfw = stafflist.Where(a => a.user_no == item.Driver && a.fx == 2).Where(a => a.sj.Date == item.TaskTime.Date).OrderByDescending(a => a.sj).FirstOrDefault();
                            if (sfw != null)
                                rt.CrewDriverScanOut = sfw.sj;
                            //var sdsss = stafflist.Where(a => a.user_no == item.CarCaptain && a.fx == 2);
                        }
                        if (!string.IsNullOrEmpty(item.OtherPeople))
                        {//rt.FingerScanin    rt.FingerScanOut
                            sfw = stafflist.Where(a => a.user_no == item.OtherPeople && a.fx == 1).Where(a => a.sj.Date == item.TaskTime.Date).OrderBy(a => a.sj).FirstOrDefault();
                            if (sfw != null)
                                rt.CrewMemberScanIn = sfw.sj;

                            sfw = stafflist.Where(a => a.user_no == item.OtherPeople && a.fx == 2).Where(a => a.sj.Date == item.TaskTime.Date).OrderByDescending(a => a.sj).FirstOrDefault();
                            if (sfw != null)
                                rt.CrewMemberScanOut = sfw.sj;
                            //var sdsss = stafflist.Where(a => a.user_no == item.CarCaptain && a.fx == 2);
                        }


                        wpdsdtmp = WeeklyPlanDetailsID.FirstOrDefault(a => a.Id == item.AllotGroupId);
                        if (wpdsdtmp != null)
                        {
                            rt.Rosteredstart = wpdsdtmp.BeginBanCi;    //暂时没有
                        }

                        atmtasklogs = TaskLogs.Where(a => a.LineInfoId == item.Id).ToList();
                        //atmtasklogs.Where(a => a.taskType == "Preload_begin").OrderBy(a => a.OperTime).FirstOrDefault();
                        t1 = atmtasklogs.Where(a => a.taskType == "Preload_begin").OrderBy(a => a.OperTime).FirstOrDefault();
                        if (t1 != null)
                            rt.Inbaytime = t1.OperTime;
                        t1 = atmtasklogs.Where(a => a.taskType == "Preload_Leave").OrderBy(a => a.OperTime).FirstOrDefault();
                        if (t1 != null)
                            rt.Outbaytime = t1.OperTime;
                        // Drive time total    Loading time total

                        var temp = atmtasklogs.Select(a => new { a.LineInfoId, a.taskType, a.OperTime }).Distinct().ToList();

                        var tempt1 = temp.FirstOrDefault();
                        tempt1 = temp.Where(a => a.taskType == "Departure_Out").OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip1_Depart = tempt1.OperTime;
                            temdateas = rt.Trip1_Depart;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_In" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip1_Return = tempt1.OperTime;
                            temdateas = rt.Trip1_Return;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_Out" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip2_Depart = tempt1.OperTime;
                            temdateas = rt.Trip2_Depart;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_In" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip2_Return = tempt1.OperTime;
                            temdateas = rt.Trip2_Return;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_Out" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip3_Depart = tempt1.OperTime;
                            temdateas = rt.Trip3_Depart;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_In" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip3_Return = tempt1.OperTime;
                            temdateas = rt.Trip3_Return;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_Out" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip4_Depart = tempt1.OperTime;
                            temdateas = rt.Trip4_Depart;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_In" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip4_Return = tempt1.OperTime;
                            temdateas = rt.Trip4_Return;
                        }

                        //tempt1 = temp.Where(a => a.taskType == "Departure_Out").OrderByDescending(a => a.OperTime).FirstOrDefault();
                        //if (tempt1 != null)
                        //{
                        //    rt.Trip5_Depart = tempt1.OperTime;
                        //    temdateas = rt.Trip5_Depart;
                        //}
                        //tempt1 = temp.Where(a => a.taskType == "Departure_In" && (temdateas != null ? a.OperTime > temdateas : true)).OrderByDescending(a => a.OperTime).FirstOrDefault();
                        //if (tempt1 != null)
                        //    rt.Trip5_Return = tempt1.OperTime;


                        tempt1 = temp.Where(a => a.taskType == "Departure_Out" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                        {
                            rt.Trip5_Depart = tempt1.OperTime;
                            temdateas = rt.Trip5_Depart;
                        }
                        tempt1 = temp.Where(a => a.taskType == "Departure_In" && (temdateas != null ? a.OperTime > temdateas : true)).OrderBy(a => a.OperTime).FirstOrDefault();
                        if (tempt1 != null)
                            rt.Trip5_Return = tempt1.OperTime;



                        t1 = atmtasklogs.Where(a => a.taskType == "Preload_end").OrderByDescending(a => a.OperTime).FirstOrDefault();
                        if (t1 != null)
                            rt.Returnbaytime = t1.OperTime;
                        rt.Runfinish = item.TruckBackTime;
                        if (!string.IsNullOrEmpty(item.CarCaptain))
                            Crewno++;
                        if (!string.IsNullOrEmpty(item.Driver))
                            Crewno++;
                        if (!string.IsNullOrEmpty(item.OtherPeople))
                            Crewno++;
                        rt.Crewno = Crewno.ToStr();
                        LineinfoLinegoods = linegoods.Where(a => a.LineInfoId == item.Id).Select(a => a.BankOrderID).ToList();
                        asls = AtmSysLogs.Where(a => LineinfoLinegoods.Contains(a.SysUserId)).Where(a => a.AtmSysAction == 11 || a.AtmSysAction == 17 || a.AtmSysAction == 14 || a.AtmSysAction == 18).ToList();
                        if (asls != null)
                            rt.Jobs_completed = asls.Count().ToStr();
                        asls = AtmSysLogs.Where(a => LineinfoLinegoods.Contains(a.SysUserId)).Where(a => a.AtmSysAction == 14).ToList();
                        //rt.Jobsnotcompleted = AtmSysLogs.Where(a => LineinfoLinegoods.Contains(a.SysUserId)).Where(a => a.AtmSysAction == 14).Count().ToStr();
                        //if (asls != null)     // LineinfoLinegoods - rt.Jobs_completed.toint();
                        //rt.Jobsnotcompleted = asls.Count().ToStr();
                        rt.Jobsnotcompleted = (LineinfoLinegoods.Count - rt.Jobs_completed.ToInt()).ToStr();

                        atk = item.AtmTruck;
                        if (atk != null)
                            rt.TruckNumber = atk.Radio + " " + atk.PlateNumber;
                        rt.StartKms = item.Outkilometre.ToStr();
                        rt.FinishKms = item.Inkilometre.ToStr();
                        //rt.Comments = item.Remark;
                        //换人换车

                        string str = "";
                        Linelog.Where(a => a.Lineid == item.Id.ToStr()).ToList().ForEach(a => str += a.Content + " \n");
                        rt.Comments = str;
                        RouteTotal.Add(rt);
                    }
                    var cntsd = RouteTotal.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<RouteTotal>(query, "table_RouteTotal");
                    Common.MongodbHelper.Add_List<RouteTotal>("table_RouteTotal", RouteTotal);
                    showLog("summary_total_hours_route", string.Format("{0} - {1} Ok . Data Count : {2} ."
                        , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("summary_total_hours_route----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {

                showLog("summary_total_hours_route", "Error:" + ex.ToString());
                insertShowlog("summary_total_hours_route----Error" + ex.ToString(), st, et);
            }
            insertShowlog("summary_total_hours_route----End", st, et);
        }


        private void insertShowlog(string text, DateTime st, DateTime et)
        {
            List<ShowReportlog> srls = new List<ShowReportlog>();
            ShowReportlog srl = new ShowReportlog();
            srl.JobDate = DateTime.Now.ToLocalTime().ToString();
            srl.Content = st.ToString() + " - " + et.ToString() + " " + text;
            srls.Add(srl);
            //Common.MongodbHelper.insert<ShowReportlog>("table_ShowReportlog", new ShowReportlog { JobDate = DateTime.Now.ToLocalTime().ToString(), Content = st.ToString() + " - " + et.ToString() + " " + text });
            Common.MongodbHelper.Add_List<ShowReportlog>("table_ShowReportlog", srls);
        }

        private bool _running = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (_stop) return;
            if (_running) return;
            // 每小时执行一次

            _running = true;
            if (_lastRun.Date != DateTime.Today)
            {
                // 日期变化 再算一次昨天的数据


                insertShowlog("日期变化 再算一次昨天的数据", DateTime.Now, DateTime.Now);
                if (chbSummary.Checked)
                    Summary(DateTime.Today.AddDays(-1), DateTime.Today);
                if (chbIssue.Checked)
                    Issuereturn(DateTime.Today.AddDays(-1), DateTime.Today);
                if (chbKPI2.Checked)
                    summary_total_hours_route(DateTime.Today.AddDays(-1), DateTime.Today);
                if (chbKPI.Checked)
                    Atmtask(DateTime.Today.AddDays(-1), DateTime.Today.AddDays(-1));
                if (chbCassetle.Checked)
                    CassetteTrackPageReport(DateTime.Today.AddDays(-1), DateTime.Today.AddDays(-1));

                //
                if (chbRMSummary.Checked)
                    SummaryofOrder(DateTime.Today.AddDays(-1), DateTime.Today);
                if (chbRMResult.Checked)
                    ResultofOrder(DateTime.Today.AddDays(-1), DateTime.Today);
                if (chbRMOrderbyCustomer.Checked)
                    StatusCustomer(DateTime.Today.AddDays(-1), DateTime.Today);
                if (chbRMOrderbyRoute.Checked)
                    StatusRoute(DateTime.Today.AddDays(-1), DateTime.Today);

                if (FSPSummarychk.Checked)
                    FSPSummaryofOrder(DateTime.Today.AddDays(-1), DateTime.Today);
                if (FSPResultchk.Checked)
                    FSPResultofOrder(DateTime.Today.AddDays(-1), DateTime.Today);
                if (FSPOrderbyCustomchb.Checked)
                    FSPStatusCustomer(DateTime.Today.AddDays(-1), DateTime.Today);
                if (FSPOrderbyRoutechb.Checked)
                    FSPStatusRoute(DateTime.Today.AddDays(-1), DateTime.Today);

                if (ATMSummaryATMOrderCKB.Checked)
                    ATMSummaryATMOrders(DateTime.Today.AddDays(-1), DateTime.Today);

                if (ATMSummaryATMNumberCHB.Checked)
                    ATMSummaryATMNumber(DateTime.Today, DateTime.Today);

                insertShowlog("日期变化结束 ", DateTime.Now, DateTime.Now);
            }
            if (_lastRun.Hour != DateTime.Now.Hour)
            {
                insertShowlog("小时变化 再算一次数据", DateTime.Now, DateTime.Now);
                if (chbSummary.Checked)
                    Summary(DateTime.Today, DateTime.Today.AddDays(1));
                if (chbIssue.Checked)
                    Issuereturn(DateTime.Today, DateTime.Today.AddDays(1));
                if (chbKPI2.Checked)
                    summary_total_hours_route(DateTime.Today, DateTime.Today.AddDays(1));
                if (chbKPI.Checked)
                    Atmtask(DateTime.Today, DateTime.Today);
                if (chbCassetle.Checked)
                    CassetteTrackPageReport(DateTime.Today, DateTime.Today);


                //
                if (chbRMSummary.Checked)
                    SummaryofOrder(DateTime.Today, DateTime.Today.AddDays(1));
                if (chbRMResult.Checked)
                    ResultofOrder(DateTime.Today, DateTime.Today.AddDays(1));
                if (chbRMOrderbyCustomer.Checked)
                    StatusCustomer(DateTime.Today, DateTime.Today.AddDays(1));
                if (chbRMOrderbyRoute.Checked)
                    StatusRoute(DateTime.Today, DateTime.Today.AddDays(1));
                if (FSPResultchk.Checked)
                    FSPResultofOrder(DateTime.Today, DateTime.Today.AddDays(1));

                if (FSPSummarychk.Checked)
                    FSPSummaryofOrder(DateTime.Today, DateTime.Today.AddDays(1));
                if (FSPResultchk.Checked)
                    FSPResultofOrder(DateTime.Today, DateTime.Today.AddDays(1));
                if (FSPOrderbyCustomchb.Checked)
                    FSPStatusCustomer(DateTime.Today, DateTime.Today.AddDays(1));
                if (FSPOrderbyRoutechb.Checked)
                    FSPStatusRoute(DateTime.Today, DateTime.Today.AddDays(1));

                if (ATMSummaryATMOrderCKB.Checked)
                    ATMSummaryATMOrders(DateTime.Today, DateTime.Today.AddDays(1));

                _lastRun = DateTime.Now;
                insertShowlog("小时变化结束 ", DateTime.Now, DateTime.Now);
            }
            _running = false;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dateTimePicker1.Value = DateTime.Now.Date;
            this.dateTimePicker2.Value = this.dateTimePicker1.Value.AddDays(1);
            this.button7_Click(null, null);
            Trace.WriteLine("Test");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            showLog("Query", string.Format("Query Data. DateTime {0} - {1} .", this.dateTimePicker1.Value.ToShortDateString(),
                this.dateTimePicker2.Value.ToShortDateString()));
            SortByDocument sbd = new SortByDocument();
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value;
            IMongoQuery query = null;
            List<IMongoQuery> list = new List<IMongoQuery>();
            list.Add(Query.GTE("JobDate", st));
            list.Add(Query.LT("JobDate", et));
            query = Query.And(list);
            List<RouteTotal> task = Common.MongodbHelper.FindListBy<RouteTotal>(query, sbd, "table_RouteTotal");

            showLog("Query", string.Format("Query Data count {0}.", task.Count));
        }

        private void button5_Click(object sender, EventArgs ea)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value;

            Atmtask(st, et);
        }
        private void Atmtask(DateTime st, DateTime et)
        {
            insertShowlog("table_text1----Start", st, et);
            var df = new DatabaseFactory();
            var _ilineGoodsService = new LineGoodsService(df, null);
            IVMDispatchService _ivmdispatchService = new VMDispatchMikeService(null, null, null, null, null, null, null
                , null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null
                , _ilineGoodsService, null, null, null, null);
            try
            {//10   10
                //int days = (int)et.Date.Subtract(st.Date).TotalDays + 1;    1
                //for (int i = 0; i <= days; i++)    0     1
                //{
                //    var time = st.AddDays(i);
                //    showLog("Atmtask", string.Format("Info KPI {0}  Start.", time.ToShortDateString()));
                //    //DateTime time = times.AddDays(i);
                //    var patch = _ivmdispatchService.Atmtask(time);
                //    var timeTo = time.ToString("yyyy-MM-dd");
                //    IMongoQuery query = Query.And((Query.EQ("JobDate", DateTime.Parse(timeTo))));
                //    Common.MongodbHelper.Remove<AtmTaskLogdetail>(query, "table_text");
                //    bool bln = Common.MongodbHelper.Add_List<AtmTaskLogdetail>("table_text", patch);

                //    Common.MongodbHelper.insert<SysLog>("Log_text",
                //        new SysLog { Level = "Info_KPI", Message = "更新" + timeTo + "的KPI数据" + bln.ToString() });

                //    showLog("Atmtask", string.Format("Info KPI {0} Ok. Data count {1}", time.ToShortDateString(), patch.Count));
                //    Application.DoEvents();
                //Application.DoEvents();
                //}

                // 10  10
                DateTime time = st.AddDays(-1);
                while (time <= et)
                {
                    time = time.AddDays(1);
                    showLog("Atmtask", string.Format("Info KPI {0}  Start.", time.ToShortDateString()));
                    var patch = _ivmdispatchService.Atmtask(time);
                    var timeTo = time.ToString("yyyy-MM-dd");
                    DateTime end = time.AddDays(1).Date;
                    //IMongoQuery query = Query.And((Query.EQ("JobDate", DateTime.Parse(timeTo))));
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", time.Date));
                    list1.Add(Query.LT("JobDate", end));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<AtmTaskLogdetail>(query, "table_text");
                    Common.MongodbHelper.Add_List<AtmTaskLogdetail>("table_text", patch);
                    showLog("Atmtask", string.Format("Info KPI {0} Ok. Data count {1}", time.ToShortDateString(), patch.Count));

                    insertShowlog("table_text1----Count" + patch.Count, time, time);
                }
            }
            catch (Exception e)
            {
                showLog("Atmtask", string.Format("Error {0}.", e.ToString()));
                Common.MongodbHelper.insert<SysLog>("Log_text", new SysLog { Level = "Info_KPIError", Message = e.ToString() });
                insertShowlog("table_text1----Error" + e.ToString(), st, et);
            }
            insertShowlog("table_text1----End", st, et);
        }


        private void button6_Click(object sender, EventArgs ea)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value;
            CassetteTrackPageReport(st, et);
        }


        private void CassetteTrackPageReport(DateTime st, DateTime et)
        {
            //IVMDispatchService _ivmdispatchService = new VMDispatchMikeService(null, null, null, null, null, null, null
            //    , null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null
            //    , null, null, null, null, null);
            //try
            //{
            //    int pagecnt = 1;
            //    int currentPage = 1;
            //    int showCount = int.MaxValue;
            //    DateTime time = st;

            //    int days = (int)et.Date.Subtract(st.Date).TotalDays + 1;
            //    for (int i = 0; i < days; i++)
            //    {
            //        DateTime enddate = time.AddDays(1);
            //        showLog("CassetteTrack", string.Format("Info Cassette Track {0}  Start.", time.ToShortDateString()));
            //        Application.DoEvents();
            //        var patch = _ivmdispatchService.CassetteTrackPageReport(time.ToString()
            //            , enddate.ToString(), "", "", "", "", out pagecnt, currentPage, showCount);
            //        var timeTo = enddate.ToString("yyyy-MM-dd");
            //        IMongoQuery query = Query.And((Query.EQ("moneyFiveTen", timeTo)));
            //        Common.MongodbHelper.Remove<VMLineInfoOperation>(query, "table_text");
            //        bool bln = Common.MongodbHelper.Add_List<VMLineInfoOperation>("table_text", patch);

            //        Common.MongodbHelper.insert<SysLog>("Log_text",
            //            new SysLog { Level = "CassetteReport", Message = "更新" + timeTo + "的Cassette数据" + bln.ToString() });

            //        showLog("CassetteTrack", string.Format("Info Cassette Track {0} Ok. Data count {1}", time.ToShortDateString(), patch.Count));

            //        time = time.AddDays(1);

            //        Application.DoEvents();
            //        Application.DoEvents();
            //    }
            //}

            //catch (Exception e)
            //{

            //    showLog("CassetteTrack", string.Format("Error {0}.", e.ToString()));
            //    Common.MongodbHelper.insert<SysLog>("Log_text", new SysLog { Level = "CassetteReportError", Message = e.ToString() });
            //}
        }

        private void button7_Click(object sender, EventArgs e)
        {
            _stop = !_stop;
            if (_stop)
            {
                button7.Text = "start timer";
                showLog("Timer", "Timer Stop!");
            }
            else
            {
                button7.Text = "stop timer";
                showLog("Timer", "Timer Start!");
            }
        }


        private void button8_Click(object sender, EventArgs e)
        {//Summary of Order

            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            SummaryofOrder(st, et);
        }
        private void SummaryofOrder(DateTime st, DateTime et)
        {
            showLog("SummaryofOrder", "Start");
            insertShowlog("SummaryofOrder----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<SummaryofOrder> SummoOrder = new List<SummaryofOrder>();
                    var bankdes = db.AtmCustomers.ToList();
                    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    var bankorders = db.BankOrders.Where(a => !a.Deleted && a.Release == "1"
                                    && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).ToList();
                    List<Guid> bankatmId = bankorders.Where(a => a.AtmId != null).Select(a => a.AtmId.Value).ToList();
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    while (temp < et)  //每天
                    {
                        DateTime temped = temp.AddDays(1);
                        foreach (var item in prolist)
                        {
                            var bankorderlist = (from a in bankorders.Where(a => a.ImplementTime.Value >= temp && a.ImplementTime.Value < temped)
                                                 join b in atmlist.Where(a => a.ProjectId == item.Id)
                                                 on a.AtmId equals b.Id
                                                 join c in bankdes
                                                 on b.CustomerId equals c.Id
                                                 select new
                                                 {
                                                     a.ImplementTime,
                                                     a.OrderTime,
                                                     a.IsDropBag,
                                                     Bank = c.Name
                                                 }).ToList();
                            var orderbank = bankorderlist.Select(a => a.Bank).ToList();
                            SummoOrder.AddRange(bankorderlist.GroupBy(c => c.Bank).Select(g => (new SummaryofOrder
                            {
                                Bank = g.Key,
                                OrderInAdvance = g.Count(item0 => (!item0.OrderTime.Equals((DateTime)item0.ImplementTime) && (item0.IsDropBag == 2 || item0.IsDropBag == 0))),
                                SameDayOrder = g.Count(item0 => (item0.OrderTime.Equals((DateTime)item0.ImplementTime) && (item0.IsDropBag == 2 || item0.IsDropBag == 0))),
                                CassetteDamage = g.Count(item0 => item0.IsDropBag == 4),
                                DropBag = g.Count(item0 => item0.IsDropBag == 1 || item0.IsDropBag == 3),
                                //Totalorder = 0.ToStr(),
                                Branch = item.Name,
                                JobDate = temp.Date
                            })));

                            //暂时不注释
                            //foreach (var itembk in Banks)
                            //{
                            //    if (!orderbank.Contains(itembk))
                            //    {
                            //        SummoOrder.Add(new SummaryofOrder
                            //        {
                            //            Bank = itembk,
                            //            OrderInAdvance = 0,
                            //            SameDayOrder = 0,
                            //            CassetteDamage = 0,
                            //            DropBag = 0,
                            //            //Status = 1
                            //            Branch = item.Name,
                            //            JobDate = temp.Date
                            //        });
                            //    }
                            //}

                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = SummoOrder.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<SummaryofOrder>(query, "table_SummoOrder");
                    Common.MongodbHelper.Add_List<SummaryofOrder>("table_SummoOrder", SummoOrder);

                    showLog("SummaryofOrder", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("SummaryofOrder----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("SummaryofOrder", "Error:" + ex.Message);
                insertShowlog("SummaryofOrder----Error" + ex.ToString(), st, et);
            }
            insertShowlog("SummaryofOrder----End", st, et);
        }


        private void button9_Click(object sender, EventArgs e)
        {//Result of Order

            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            ResultofOrder(st, et);
        }
        private void ResultofOrder(DateTime st, DateTime et)
        {
            showLog("ResultofOrder", "Start");
            insertShowlog("ResultofOrder----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<ResultofOrder> ResultofOrder = new List<ResultofOrder>();
                    var bankdes = db.AtmCustomers.ToList();
                    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    var bankorders = db.BankOrders.Where(a => !a.Deleted && a.Release == "1"
                                    && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).ToList();
                    List<Guid> bankatmId = bankorders.Where(a => a.AtmId != null).Select(a => a.AtmId.Value).ToList();
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    var ORDERiD = bankorders.Select(a => a.Id).ToList();
                    //    var _iAtmSysLog = db.AtmSysLogs.Where(a => !a.Deleted).Where(a => ORDERiD.Contains(a.SysUserId) &&
                    //((a.AtmSysAction >= 11 && a.AtmSysAction < 22) || a.AtmSysAction == 24 || a.AtmSysAction == 25) && a.CreatedDate >= st && a.CreatedDate < et).OrderByDescending(a => a.UpdatedDate).ToList();

                    var _iAtmSysLog = db.AtmSysLogs.Where(a => !a.Deleted).Where(a => ORDERiD.Contains(a.SysUserId) &&
                ((a.AtmSysAction >= 11 && a.AtmSysAction < 22) || a.AtmSysAction == 24 || a.AtmSysAction == 25 || a.AtmSysAction == 16 || a.AtmSysAction == 13) && a.CreatedDate >= st && a.CreatedDate < et).OrderByDescending(a => a.UpdatedDate).ToList();

                    while (temp < et)  //每天
                    {

                        DateTime temped = temp.AddDays(1);
                        foreach (var item in prolist)
                        {
                            //var dones = 0;
                            //var drops = 0;
                            //var cassettes = 0;
                            var bankorderlist = (from a in bankorders.Where(a => a.ImplementTime.Value >= temp && a.ImplementTime.Value < temped)
                                                 join tmp in atmlist.Where(a => a.ProjectId == item.Id)
                                                 on a.AtmId equals tmp.Id
                                                 join tmp2 in bankdes
                                                 on tmp.CustomerId equals tmp2.Id
                                                 select new
                                                 {
                                                     a,
                                                     Project = tmp.ProjectId,
                                                     Bank = tmp2.Name
                                                 }).ToList();
                            //var orderbank = bankorderlist.Select(a => a.Bank).ToList();
                            var orderid = bankorderlist.Select(a => a.a.Id).ToList();
                            var sysatm = _iAtmSysLog.Where(a => a.CreatedDate >= temp && a.CreatedDate < temped).ToList();
                            var bankorder = bankorderlist.GroupBy(c => new { c.a.ImplementTime, c.a.CustomerId, c.Bank }).ToList();

                            if (bankorder.Count > 0)
                            {
                                foreach (var itembk in bankorder)
                                {
                                    ResultofOrder or = new ResultofOrder();
                                    or.JobDate = itembk.Key.ImplementTime;
                                    //or.CustomerId = itembk.Key.CustomerId;
                                    or.Bank = itembk.Key.Bank;
                                    or.Branch = item.Name;
                                    or.Totalorder = itembk.Count();
                                    var orid = itembk.Select(a => new { a.a.Id, a.a.OrderStatus }).ToList();
                                    int done = 0;
                                    int drop = 0;
                                    int cassette = 0;
                                    int Failed = 0;
                                    foreach (var items in orid)
                                    {
                                        //var d = sysatm.Where(a => a.SysUserId == items.Id).FirstOrDefault();
                                        if ((items.OrderStatus >= 11 && items.OrderStatus < 22) || items.OrderStatus == 24 || items.OrderStatus == 25)
                                        {
                                            done = done + 1;
                                        }
                                        var dro = sysatm.Where(a => a.SysUserId == items.Id && a.AtmSysAction == 14).FirstOrDefault();
                                        if (dro != null)
                                        {
                                            drop = drop + 1;
                                        }
                                        var cass = sysatm.Where(a => a.SysUserId == items.Id && a.AtmSysAction == 18).FirstOrDefault();
                                        if (cass != null)
                                        {
                                            cassette = cassette + 1;
                                        }

                                        var Fail = sysatm.Where(a => a.SysUserId == items.Id && (a.AtmSysAction == 16 || a.AtmSysAction == 13)).FirstOrDefault();
                                        if (Fail != null)
                                        {
                                            Failed = Failed + 1;
                                        }
                                    }
                                    or.Failed = Failed;
                                    or.Done = done;
                                    or.DropBag = drop;
                                    or.BadCassette = cassette;
                                    ResultofOrder.Add(or);
                                    //dones = dones + done;
                                    //drops = drops + drop;
                                    //cassettes = cassettes + cassette;
                                }
                            }

                            //ResultofOrder.Add(new ResultofOrder
                            //{
                            //    Bank = "Total",
                            //    TotalOrder = bankorderlist.Count(),

                            //    Done = dones,
                            //    DropBag = drops,
                            //    CassetteDamage = cassettes,
                            //    Status = 1,
                            //});



                            //ResultofOrder.AddRange(bankorderlist.GroupBy(c => c.Bank).Select(g => (new SummaryofOrder
                            //{
                            //    Bank = g.Key,
                            //    OrderInAdvance = g.Count(item0 => (!item0.OrderTime.Equals((DateTime)item0.ImplementTime) && (item0.IsDropBag == 2 || item0.IsDropBag == 0))),
                            //    SameDayOrder = g.Count(item0 => (item0.OrderTime.Equals((DateTime)item0.ImplementTime) && (item0.IsDropBag == 2 || item0.IsDropBag == 0))),
                            //    CassetteDamage = g.Count(item0 => item0.IsDropBag == 4),
                            //    DropBag = g.Count(item0 => item0.IsDropBag == 1 || item0.IsDropBag == 3),
                            //    //Totalorder = 0.ToStr(),
                            //    Branch = item.Name,
                            //    JobDate = temp.Date
                            //})));
                            //foreach (var itembk in Banks)
                            //{
                            //    if (!orderbank.Contains(itembk))
                            //    {
                            //        SummoOrder.Add(new SummaryofOrder
                            //        {
                            //            Bank = itembk,
                            //            OrderInAdvance = 0,
                            //            SameDayOrder = 0,
                            //            CassetteDamage = 0,
                            //            DropBag = 0,
                            //            //Status = 1
                            //            Branch = item.Name,
                            //            JobDate = temp.Date
                            //        });
                            //    }
                            //}

                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = ResultofOrder.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<ResultofOrder>(query, "table_ResultofOrder");
                    Common.MongodbHelper.Add_List<ResultofOrder>("table_ResultofOrder", ResultofOrder);
                    showLog("ResultofOrder", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("ResultofOrder----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("ResultofOrder", "Error:" + ex.Message);
                insertShowlog("ResultofOrder----Error" + ex.ToString(), st, et);
            }
            insertShowlog("ResultofOrder----End", st, et);
        }

        private void button10_Click(object sender, EventArgs e)
        {//Order Status by Customer
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            StatusCustomer(st, et);
        }
        private void StatusCustomer(DateTime st, DateTime et)
        {//--OrderStatusbyCustomer

            showLog("OrderStatusbyCustomer", "Start");
            insertShowlog("OrderStatusbyCustomer----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<OrderStatusbyCustomer> OrderStatusbyCustomer = new List<OrderStatusbyCustomer>();
                    var bankdes = db.AtmCustomers.ToList();
                    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    var bankorders = db.BankOrders.Where(a => !a.Deleted && a.Release == "1"
                                    && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).ToList();
                    List<Guid> bankatmId = bankorders.Where(a => a.AtmId != null).Select(a => a.AtmId.Value).ToList();
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    List<Guid> bankIdS = bankorders.Select(a => a.Id).ToList();
                    var atmnolists = db.AtmNoLists.Where(a => bankIdS.Contains(a.BankOrderId))
                .Select(a => new { a.BankOrderId, a.LineInfom.LineName }).ToList();
                    while (temp < et)  //每天
                    {
                        DateTime temped = temp.AddDays(1);
                        foreach (var item in prolist)
                        {
                            var bankorderlist = (from a in bankorders.Where(a => a.ImplementTime.Value >= temp && a.ImplementTime.Value < temped)
                                                 join tmp in atmlist.Where(a => a.ProjectId == item.Id)
                                                 on a.AtmId equals tmp.Id
                                                 join tmp4 in bankdes
                                                 on a.CustomerId equals tmp4.Id
                                                 orderby a.ImplementTime, a.CreatedDate, a.UpdatedDate descending
                                                 select new
                                                 {
                                                     orderid = a.Id,
                                                     a.PubTime,
                                                     Project = tmp.ProjectId,
                                                     CustomerId = a.CustomerId,
                                                     ATMID = tmp.AtmNo,
                                                     Location = tmp.ATMName,
                                                     Customer = tmp4.Name,
                                                     Area = a.OrderStatus,
                                                     JobDate = a.ImplementTime
                                                 }).ToList();
                            var orderids = bankorderlist.Select(a => a.orderid).ToList();
                            var ordernoList = atmnolists.Where(a => orderids.Contains(a.BankOrderId))
                .Select(a => new { a.BankOrderId, a.LineName }).ToList();
                            foreach (var item2 in bankorderlist)
                            {
                                OrderStatusbyCustomer or = new OrderStatusbyCustomer();
                                or.Branch = item.Name;
                                or.Customer = item2.Customer;
                                or.JobDate = item2.JobDate;
                                or.ATMID = item2.ATMID;
                                or.Location = item2.Location;
                                or.Customer = item2.Customer;
                                or.RouteName = "";
                                var ordernost = ordernoList.Where(a => a.BankOrderId == item2.orderid).FirstOrDefault();
                                if (ordernost != null)
                                {
                                    or.RouteName = ordernost.LineName;
                                }
                                or.OrderStatus = ((item2.Area >= 11 && item2.Area < 22) || item2.Area == 24 || item2.Area == 25 ? "DONE" : "Pending");
                                OrderStatusbyCustomer.Add(or);
                            }

                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = OrderStatusbyCustomer.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<OrderStatusbyCustomer>(query, "table_OrderStatusbyCustomer");
                    Common.MongodbHelper.Add_List<OrderStatusbyCustomer>("table_OrderStatusbyCustomer", OrderStatusbyCustomer);

                    showLog("OrderStatusbyCustomer", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("OrderStatusbyCustomer----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("OrderStatusbyCustomer", "Error:" + ex.Message);
                insertShowlog("OrderStatusbyCustomer----Error" + ex.ToString(), st, et);
            }
            insertShowlog("OrderStatusbyCustomer----End", st, et);
        }
        private void button11_Click(object sender, EventArgs e)
        {//Order Status by Route OrderStatusbyRoute
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            StatusRoute(st, et);
        }
        private void StatusRoute(DateTime st, DateTime et)
        {//--OrderStatusbyRoute

            showLog("OrderStatusbyRoute", "Start");
            insertShowlog("OrderStatusbyRoute----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<OrderStatusbyRoute> OrderStatusbyRoutes = new List<OrderStatusbyRoute>();

                    //    var bankdes = db.AtmCustomers.ToList();
                    //    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    //    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    //    var bankorders = db.BankOrders.Where(a => !a.Deleted && a.Release == "1"
                    //                    && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).ToList();
                    //    List<Guid> bankatmId = bankorders.Where(a => a.AtmId != null).Select(a => a.AtmId.Value).ToList();
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    //    var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    //    List<Guid> bankIdS = bankorders.Select(a => a.Id).ToList();
                    //    var atmnolists = db.AtmNoLists.Where(a => bankIdS.Contains(a.BankOrderId))
                    //.Select(a => new { a.BankOrderId, a.LineInfom.LineName }).ToList();


                    //
                    var linetmplist = db.LineInfos.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => a.TaskTime >= st && a.TaskTime < et
                && a.TaskLineType == 0 && !a.Deleted)
                .Select(a => new { a.Id, a.ProjectId, a.TruckOutTime, a.TruckBackTime, a.LineName, a.TaskTime }).ToList();
                    //
                    List<Guid> linegidsS = linetmplist.Select(a => a.Id).ToList();

                    var linelistS = db.AtmNoLists.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => linegidsS.Contains(a.LineInfoId)).ToList();
                    var orderidS = linelistS.Select(a => a.BankOrderId).ToArray();
                    var sysatmS = db.AtmSysLogs.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => orderidS.Contains(a.SysUserId)).ToList();
                    //&& (a.AtmSysAction == 11 || a.AtmSysAction == 17) && a.CreatedDate >= st
                    //&& a.CreatedDate < et).ToList();
                    //    var linelists = linelist.GroupBy(c => new { c.LineInfoId }).ToList();
                    while (temp < et)  //每天  
                    {
                        foreach (var item in prolist)
                        {
                            //OrderStatusbyRoute or = new OrderStatusbyRoute();
                            var linstlist = linetmplist.Where(a => a.TaskTime == temp && a.ProjectId == item.Id).ToList();
                            List<Guid> linegids = linstlist.Select(a => a.Id).ToList();

                            var linelist = linelistS.Where(a => linegids.Contains(a.LineInfoId)).ToList();
                            var orderid = linelist.Select(a => a.BankOrderId).ToArray();
                            var sysatm = sysatmS.Where(a => orderid.Contains(a.SysUserId)
                                && (a.AtmSysAction == 11 || a.AtmSysAction == 17) && a.CreatedDate >= temp
                                && a.CreatedDate < temp.AddDays(1)).ToList();
                            var linelists = linelist.GroupBy(c => new { c.LineInfoId }).ToList();
                            if (linelists.Count > 0)
                            {
                                foreach (var item2 in linelists)
                                {
                                    OrderStatusbyRoute or = new OrderStatusbyRoute();
                                    //or.RouteId = item.Key.LineInfoId;
                                    or.JobDate = temp;
                                    or.Branch = item.Name;
                                    or.RouteName = "";
                                    var linobj = linstlist.Where(a => a.Id == item2.Key.LineInfoId).FirstOrDefault();
                                    if (linobj != null)
                                    {
                                        if (linobj.TruckBackTime.HasValue)
                                        {
                                            //or.ReturnTime = linobj.TruckBackTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                            or.ReturnTime = linobj.TruckBackTime.Value;
                                        }
                                        if (linobj.TruckOutTime.HasValue)
                                        {
                                            //or.Location = linobj.TruckOutTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                            or.DepatureTime = linobj.TruckOutTime.Value;
                                        }
                                        or.RouteName = linobj.LineName;
                                    }
                                    or.JobAssigned = item2.Count();
                                    var orid = item2.Select(a => a.BankOrderId).ToArray();
                                    int done = 0;
                                    foreach (var items in orid)
                                    {
                                        var d = sysatm.Where(a => a.SysUserId == items).FirstOrDefault();
                                        if (d != null)
                                        {
                                            done = done + 1;
                                        }
                                    }
                                    or.JobDone = done;
                                    OrderStatusbyRoutes.Add(or);
                                }
                            }
                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = OrderStatusbyRoutes.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<OrderStatusbyRoute>(query, "table_OrderStatusbyRoutes");
                    Common.MongodbHelper.Add_List<OrderStatusbyRoute>("table_OrderStatusbyRoutes", OrderStatusbyRoutes);

                    showLog("OrderStatusbyRoute", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("OrderStatusbyRoute----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("OrderStatusbyRoute", "Error:" + ex.Message);
                insertShowlog("OrderStatusbyRoute----Error" + ex.ToString(), st, et);
            }
            insertShowlog("OrderStatusbyRoute----End", st, et);
        }


        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            if (listBox1.SelectedItems.Count > 0)
            {
                textBox1.Text = listBox1.SelectedItems[0].ToString();
            }
        }

        //Employee assigned
        private void button12_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value;
            Employeeassigned(st, et);
        }
        private void Employeeassigned(DateTime st, DateTime et)
        {
            insertShowlog("Employeeassigned----Start", st, et);
            try
            {
                var df = new DatabaseFactory();
                SysProjectService sp = new SysProjectService(df, null);
                LineInfoService ls = new LineInfoService(df, null);
                SysUserService ss = new SysUserService(df, null);
                IRosterPlanService _iRosterPlanService = new RosterPlanService(null, null, null, null, null, null, null, sp
                         , ls, null, null, null, null, null, ss, null, null, null, null, null, null, null, null, null, null
                         , null, null, null, null);
                var EmployeeAssigneds = _iRosterPlanService.SetLineSetListIsPr(st, et);
                List<IMongoQuery> list1 = new List<IMongoQuery>();
                list1.Add(Query.GTE("JobDate", st.Date));
                list1.Add(Query.LT("JobDate", et.AddDays(1).Date));
                IMongoQuery query = Query.And(list1);
                Common.MongodbHelper.Remove<EmployeeAssigned>(query, "table_EmployeeAssigneds");
                Common.MongodbHelper.Add_List<EmployeeAssigned>("table_EmployeeAssigneds", EmployeeAssigneds);
                showLog("Employeeassigned", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), EmployeeAssigneds.Count));

                insertShowlog("Employeeassigned----Count" + EmployeeAssigneds.Count, st, et);
            }
            catch (Exception e)
            {
                showLog("Employeeassigned", string.Format("Error {0}.", e.ToString()));
                //Common.MongodbHelper.insert<SysLog>("Log_text", new SysLog { Level = "Info_KPIError", Message = e.ToString() });
                insertShowlog("Employeeassigned----Error" + e.ToString(), st, et);
            }
            insertShowlog("Employeeassigned----End", st, et);
        }

        private void button13_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            FSPSummaryofOrder(st, et);
        }
        private void FSPSummaryofOrder(DateTime st, DateTime et)
        {//Order in Sameday 同一天    Order in advance 不同天
            showLog("FSPSummaryofOrder", "Start");
            insertShowlog("FSPSummaryofOrder----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<FSPSummaryofOrder> SummoOrder = new List<FSPSummaryofOrder>();
                    var bankdes = db.AtmCustomers.ToList();
                    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    //db.BankOrders
                    //var bankorders = db.BankOrders.Where(a => !a.Deleted && a.Release == "1"
                    // && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).ToList();

                    var bankorders = db.Repairs.Where(a => !a.Deleted && a.Release == "1"
                                   && a.FaultTime >= st && a.FaultTime < et).Select(a => new { Id = a.Id, AtmId = a.AtmId, ImplementTime = a.FaultTime, CustomerId = a.CustomerId, OrderStatus = a.OrderStatus, OrderTime = a.NoticeTime }).ToList().Union(db.Inspections.Where(a => !a.Deleted && a.Release == "1" && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).Select(a => new { Id = a.Id, AtmId = a.AtmId, ImplementTime = a.ImplementTime.Value, CustomerId = a.CustomerId, OrderStatus = a.OrderStatus, OrderTime = a.OrderTime }).ToList());

                    List<Guid> bankatmId = bankorders.Where(a => a.AtmId != null).Select(a => a.AtmId.Value).ToList();
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    while (temp < et)  //每天
                    {
                        DateTime temped = temp.AddDays(1);
                        foreach (var item in prolist)
                        {
                            var bankorderlist = (from a in bankorders.Where(a => a.ImplementTime >= temp && a.ImplementTime < temped)
                                                 join b in atmlist.Where(a => a.ProjectId == item.Id)
                                                 on a.AtmId equals b.Id
                                                 join c in bankdes
                                                 on b.CustomerId equals c.Id
                                                 select new
                                                 {
                                                     a.ImplementTime,
                                                     a.OrderTime,
                                                     //a.IsDropBag,
                                                     Bank = c.Name
                                                 }).ToList();
                            var orderbank = bankorderlist.Select(a => a.Bank).ToList();
                            SummoOrder.AddRange(bankorderlist.GroupBy(c => c.Bank).Select(g => (new FSPSummaryofOrder
                            {
                                Bank = g.Key,
                                OrderInAdvance = g.Count(item0 => (!item0.OrderTime.Date.Equals((DateTime)item0.ImplementTime.Date))),
                                SameDayOrder = g.Count(item0 => (item0.OrderTime.Date.Equals((DateTime)item0.ImplementTime.Date))),
                                //CassetteDamage = g.Count(item0 => item0.IsDropBag == 4),
                                //DropBag = g.Count(item0 => item0.IsDropBag == 1 || item0.IsDropBag == 3),
                                //Totalorder = 0.ToStr(),
                                Branch = item.Name,
                                JobDate = temp.Date
                            })));

                            //暂时不注释
                            //foreach (var itembk in Banks)
                            //{
                            //    if (!orderbank.Contains(itembk))
                            //    {
                            //        SummoOrder.Add(new SummaryofOrder
                            //        {
                            //            Bank = itembk,
                            //            OrderInAdvance = 0,
                            //            SameDayOrder = 0,
                            //            CassetteDamage = 0,
                            //            DropBag = 0,
                            //            //Status = 1
                            //            Branch = item.Name,
                            //            JobDate = temp.Date
                            //        });
                            //    }
                            //}

                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = SummoOrder.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<FSPSummaryofOrder>(query, "table_FSPSummoOrder");
                    Common.MongodbHelper.Add_List<FSPSummaryofOrder>("table_FSPSummoOrder", SummoOrder);

                    showLog("FSPSummaryofOrder", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("FSPSummaryofOrder----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("FSPSummaryofOrder", "Error:" + ex.Message);
                insertShowlog("FSPSummaryofOrder----Error" + ex.ToString(), st, et);
            }
            insertShowlog("FSPSummaryofOrder----End", st, et);
        }


        private void button14_Click(object sender, EventArgs e)
        {//FSP Result of Order
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            FSPResultofOrder(st, et);
        }
        private void FSPResultofOrder(DateTime st, DateTime et)
        {
            showLog("FSPResultofOrder", "Start");
            insertShowlog("FSPResultofOrder----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<FSPResultofOrder> ResultofOrder = new List<FSPResultofOrder>();
                    var bankdes = db.AtmCustomers.ToList();
                    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    //var bankorders = db.Repairs.Where(a => !a.Deleted && (a.OrderFlg == 10 || a.OrderFlg == 20) && a.Release == "1"
                    //                && a.FaultTime >= st && a.FaultTime < et).Select(a => new { Id = a.Id, AtmId = a.AtmId, ImplementTime = a.FaultTime, CustomerId = a.CustomerId, OrderStatus = a.OrderStatus }).ToList().Union(db.Inspections.Where(a => !a.Deleted && a.OrderFlg == 30 && a.Release == "1" && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).Select(a => new { Id = a.Id, AtmId = a.AtmId, ImplementTime = a.ImplementTime.Value, CustomerId = a.CustomerId, OrderStatus = a.OrderStatus }).ToList());
                    var bankorders = db.Repairs.Where(a => !a.Deleted && a.Release == "1"
                                    && a.FaultTime >= st && a.FaultTime < et).Select(a => new { Id = a.Id, AtmId = a.AtmId, ImplementTime = a.FaultTime, CustomerId = a.CustomerId, OrderStatus = a.OrderStatus }).ToList().Union(db.Inspections.Where(a => !a.Deleted && a.Release == "1" && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).Select(a => new { Id = a.Id, AtmId = a.AtmId, ImplementTime = a.ImplementTime.Value, CustomerId = a.CustomerId, OrderStatus = a.OrderStatus }).ToList());


                    List<Guid> bankatmId = bankorders.Where(a => a.AtmId != null).Select(a => a.AtmId.Value).ToList();
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    var ORDERiD = bankorders.Select(a => a.Id).ToList();
                    //var _iAtmSysLog = db.AtmSysLogs.Where(a => !a.Deleted).Where(a => ORDERiD.Contains(a.SysUserId) &&
                    //((a.AtmSysAction >= 11 && a.AtmSysAction < 22) || a.AtmSysAction == 24 || a.AtmSysAction == 25) && a.CreatedDate >= st && a.CreatedDate < et).OrderByDescending(a => a.UpdatedDate).ToList();
                    var _iAtmSysLog = db.AtmSysLogs.Where(a => !a.Deleted).Where(a => ORDERiD.Contains(a.SysUserId) &&
                    ((a.AtmSysAction >= 11 && a.AtmSysAction < 22) || a.AtmSysAction == 24 || a.AtmSysAction == 25 || a.AtmSysAction == 16 || a.AtmSysAction == 13) && a.CreatedDate >= st && a.CreatedDate < et).OrderByDescending(a => a.UpdatedDate).ToList();

                    while (temp < et)  //每天
                    {

                        DateTime temped = temp.AddDays(1);
                        foreach (var item in prolist)
                        {
                            //var dones = 0;
                            //var drops = 0;
                            //var cassettes = 0;
                            var bankorderlist = (from a in bankorders.Where(a => a.ImplementTime >= temp && a.ImplementTime < temped)
                                                 join tmp in atmlist.Where(a => a.ProjectId == item.Id)
                                                 on a.AtmId equals tmp.Id
                                                 join tmp2 in bankdes
                                                 on tmp.CustomerId equals tmp2.Id
                                                 select new
                                                 {
                                                     a,
                                                     Project = tmp.ProjectId,
                                                     Bank = tmp2.Name
                                                 }).ToList();
                            //var orderbank = bankorderlist.Select(a => a.Bank).ToList();
                            var orderid = bankorderlist.Select(a => a.a.Id).ToList();
                            var sysatm = _iAtmSysLog.Where(a => a.CreatedDate >= temp && a.CreatedDate < temped).ToList();
                            var bankorder = bankorderlist.GroupBy(c => new { c.a.ImplementTime, c.a.CustomerId, c.Bank }).ToList();

                            if (bankorder.Count > 0)
                            {
                                foreach (var itembk in bankorder)
                                {
                                    FSPResultofOrder or = new FSPResultofOrder();
                                    or.JobDate = itembk.Key.ImplementTime;
                                    //or.CustomerId = itembk.Key.CustomerId;
                                    or.Bank = itembk.Key.Bank;
                                    or.Branch = item.Name;
                                    //or.Totalorder = itembk.Count();
                                    var orid = itembk.Select(a => new { a.a.Id, a.a.OrderStatus }).ToList();
                                    int done = 0;
                                    //int drop = 0;
                                    //int cassette = 0;
                                    int Failed = 0;
                                    foreach (var items in orid)
                                    {
                                        //var d = sysatm.Where(a => a.SysUserId == items.Id).FirstOrDefault();
                                        if ((items.OrderStatus >= 11 && items.OrderStatus < 22) || items.OrderStatus == 24 || items.OrderStatus == 25)
                                        {
                                            done = done + 1;
                                        }
                                        //var dro = sysatm.Where(a => a.SysUserId == items.Id && a.AtmSysAction == 14).FirstOrDefault();
                                        //if (dro != null)
                                        //{
                                        //    drop = drop + 1;
                                        //}
                                        //var cass = sysatm.Where(a => a.SysUserId == items.Id && a.AtmSysAction == 18).FirstOrDefault();
                                        //if (cass != null)
                                        //{
                                        //    cassette = cassette + 1;
                                        //}
                                        var Fail = sysatm.Where(a => a.SysUserId == items.Id && (a.AtmSysAction == 16 || a.AtmSysAction == 13)).FirstOrDefault();
                                        if (Fail != null)
                                        {
                                            Failed = Failed + 1;
                                        }
                                    }
                                    or.Failed = Failed;
                                    or.Done = done;
                                    //or.DropBag = drop;
                                    //or.BadCassette = cassette;
                                    ResultofOrder.Add(or);
                                    //dones = dones + done;
                                    //drops = drops + drop;
                                    //cassettes = cassettes + cassette;
                                }
                            }

                            //ResultofOrder.Add(new ResultofOrder
                            //{
                            //    Bank = "Total",
                            //    TotalOrder = bankorderlist.Count(),

                            //    Done = dones,
                            //    DropBag = drops,
                            //    CassetteDamage = cassettes,
                            //    Status = 1,
                            //});



                            //ResultofOrder.AddRange(bankorderlist.GroupBy(c => c.Bank).Select(g => (new SummaryofOrder
                            //{
                            //    Bank = g.Key,
                            //    OrderInAdvance = g.Count(item0 => (!item0.OrderTime.Equals((DateTime)item0.ImplementTime) && (item0.IsDropBag == 2 || item0.IsDropBag == 0))),
                            //    SameDayOrder = g.Count(item0 => (item0.OrderTime.Equals((DateTime)item0.ImplementTime) && (item0.IsDropBag == 2 || item0.IsDropBag == 0))),
                            //    CassetteDamage = g.Count(item0 => item0.IsDropBag == 4),
                            //    DropBag = g.Count(item0 => item0.IsDropBag == 1 || item0.IsDropBag == 3),
                            //    //Totalorder = 0.ToStr(),
                            //    Branch = item.Name,
                            //    JobDate = temp.Date
                            //})));
                            //foreach (var itembk in Banks)
                            //{
                            //    if (!orderbank.Contains(itembk))
                            //    {
                            //        SummoOrder.Add(new SummaryofOrder
                            //        {
                            //            Bank = itembk,
                            //            OrderInAdvance = 0,
                            //            SameDayOrder = 0,
                            //            CassetteDamage = 0,
                            //            DropBag = 0,
                            //            //Status = 1
                            //            Branch = item.Name,
                            //            JobDate = temp.Date
                            //        });
                            //    }
                            //}

                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = ResultofOrder.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<FSPResultofOrder>(query, "table_FSPResultofOrder");
                    Common.MongodbHelper.Add_List<FSPResultofOrder>("table_FSPResultofOrder", ResultofOrder);
                    showLog("FSPResultofOrder", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("FSPResultofOrder----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("FSPResultofOrder", "Error:" + ex.Message);
                insertShowlog("FSPResultofOrder----Error" + ex.ToString(), st, et);
            }
            insertShowlog("FSPResultofOrder----End", st, et);
        }

        private void button16_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            FSPStatusRoute(st, et);
        }
        private void FSPStatusRoute(DateTime st, DateTime et)
        {//--OrderStatusbyRoute
            showLog("FSPOrderStatusbyRoute", "Start");
            insertShowlog("FSPOrderStatusbyRoute----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<FSPOrderStatusbyRoute> OrderStatusbyRoutes = new List<FSPOrderStatusbyRoute>();
                    DateTime temp = st;
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    //    var linetmplist = db.LineInfos.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => a.TaskTime >= st && a.TaskTime < et
                    //&& a.TaskLineType == 0 && !a.Deleted)
                    //.Select(a => new { a.Id, a.ProjectId, a.TruckOutTime, a.TruckBackTime, a.LineName, a.TaskTime }).ToList();
                    var linetmplist = db.LineInfos.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => a.TaskTime >= st && a.TaskTime < et
                && (a.TaskLineType == TaskLineTypes.TaskLineTypes_Xj || a.TaskLineType == TaskLineTypes.TaskLineTypes_Wx) && !a.Deleted)
                .Select(a => new { a.Id, a.ProjectId, a.TruckOutTime, a.TruckBackTime, a.LineName, a.TaskTime }).ToList();

                    List<Guid> linegidsS = linetmplist.Select(a => a.Id).ToList();
                    var linelistS = db.AtmNoLists.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => linegidsS.Contains(a.LineInfoId)).ToList();
                    var orderidS = linelistS.Select(a => a.BankOrderId).ToArray();
                    var sysatmS = db.AtmSysLogs.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => orderidS.Contains(a.SysUserId)).ToList();
                    //&& (a.AtmSysAction == 11 || a.AtmSysAction == 17) && a.CreatedDate >= st
                    //&& a.CreatedDate < et).ToList();
                    //    var linelists = linelist.GroupBy(c => new { c.LineInfoId }).ToList();
                    while (temp < et)  //每天  
                    {
                        foreach (var item in prolist)
                        {
                            //OrderStatusbyRoute or = new OrderStatusbyRoute();
                            var linstlist = linetmplist.Where(a => a.TaskTime == temp && a.ProjectId == item.Id).ToList();
                            List<Guid> linegids = linstlist.Select(a => a.Id).ToList();

                            var linelist = linelistS.Where(a => linegids.Contains(a.LineInfoId)).ToList();
                            var orderid = linelist.Select(a => a.BankOrderId).ToArray();
                            var sysatm = sysatmS.Where(a => orderid.Contains(a.SysUserId)
                                && (a.AtmSysAction == 11 || a.AtmSysAction == 17) && a.CreatedDate >= temp
                                && a.CreatedDate < temp.AddDays(1)).ToList();
                            var linelists = linelist.GroupBy(c => new { c.LineInfoId }).ToList();
                            if (linelists.Count > 0)
                            {
                                foreach (var item2 in linelists)
                                {
                                    FSPOrderStatusbyRoute or = new FSPOrderStatusbyRoute();
                                    //or.RouteId = item.Key.LineInfoId;
                                    or.JobDate = temp;
                                    or.Branch = item.Name;
                                    or.RouteName = "";
                                    var linobj = linstlist.Where(a => a.Id == item2.Key.LineInfoId).FirstOrDefault();
                                    if (linobj != null)
                                    {
                                        if (linobj.TruckBackTime.HasValue)
                                        {
                                            //or.ReturnTime = linobj.TruckBackTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                            or.ReturnTime = linobj.TruckBackTime.Value;
                                        }
                                        if (linobj.TruckOutTime.HasValue)
                                        {
                                            //or.Location = linobj.TruckOutTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                            or.DepatureTime = linobj.TruckOutTime.Value;
                                        }
                                        or.RouteName = linobj.LineName;
                                    }
                                    or.JobAssigned = item2.Count();
                                    var orid = item2.Select(a => a.BankOrderId).ToArray();
                                    int done = 0;
                                    foreach (var items in orid)
                                    {
                                        var d = sysatm.Where(a => a.SysUserId == items).FirstOrDefault();
                                        if (d != null)
                                        {
                                            done = done + 1;
                                        }
                                    }
                                    or.JobDone = done;
                                    OrderStatusbyRoutes.Add(or);
                                }
                            }
                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = OrderStatusbyRoutes.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<FSPOrderStatusbyRoute>(query, "table_FSPOrderStatusbyRoutes");
                    Common.MongodbHelper.Add_List<FSPOrderStatusbyRoute>("table_FSPOrderStatusbyRoutes", OrderStatusbyRoutes);

                    showLog("FSPOrderStatusbyRoute", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("FSPOrderStatusbyRoute----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("FSPOrderStatusbyRoute", "Error:" + ex.Message);
                insertShowlog("FSPOrderStatusbyRoute----Error" + ex.ToString(), st, et);
            }
            insertShowlog("FSPOrderStatusbyRoute----End", st, et);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            FSPStatusCustomer(st, et);
        }
        private void FSPStatusCustomer(DateTime st, DateTime et)
        {//--OrderStatusbyCustomer

            showLog("FSPOrderStatusbyCustomer", "Start");
            insertShowlog("FSPOrderStatusbyCustomer----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<FSPOrderStatusbyCustomer> OrderStatusbyCustomer = new List<FSPOrderStatusbyCustomer>();
                    var bankdes = db.AtmCustomers.ToList();
                    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    //var bankorders = db.BankOrders.Where(a => !a.Deleted && a.Release == "1"
                    //&& a.ImplementTime.Value >= st && a.ImplementTime.Value < et).ToList();
                    var bankorders = db.Repairs.Where(a => !a.Deleted && a.Release == "1"
                                    && a.FaultTime >= st && a.FaultTime < et).Select(a => new
                                    {
                                        Id = a.Id,
                                        AtmId = a.AtmId,
                                        ImplementTime = a.FaultTime,
                                        CustomerId = a.CustomerId,
                                        OrderStatus = a.OrderStatus,
                                        CreatedDate = a.CreatedDate,
                                        UpdatedDate = a.UpdatedDate,
                                        PubTime = a.PubTime
                                    }).ToList().
                                    Union(db.Inspections.Where(a => !a.Deleted && a.Release == "1"
                                    && a.ImplementTime.Value >= st && a.ImplementTime.Value < et).
                                    Select(a => new
                                    {
                                        Id = a.Id,
                                        AtmId = a.AtmId,
                                        ImplementTime = a.ImplementTime.Value,
                                        CustomerId = a.CustomerId,
                                        OrderStatus = a.OrderStatus,
                                        CreatedDate = a.CreatedDate,
                                        UpdatedDate = a.UpdatedDate,
                                        PubTime = a.PubTime
                                    }).ToList());

                    List<Guid> bankatmId = bankorders.Where(a => a.AtmId != null).Select(a => a.AtmId.Value).ToList();
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    List<Guid> bankIdS = bankorders.Select(a => a.Id).ToList();
                    var atmnolists = db.AtmNoLists.Where(a => bankIdS.Contains(a.BankOrderId))
                .Select(a => new { a.BankOrderId, a.LineInfom.LineName }).ToList();
                    while (temp < et)  //每天
                    {
                        DateTime temped = temp.AddDays(1);
                        foreach (var item in prolist)
                        {
                            var bankorderlist = (from a in bankorders.Where(a => a.ImplementTime >= temp && a.ImplementTime < temped)
                                                 join tmp in atmlist.Where(a => a.ProjectId == item.Id)
                                                 on a.AtmId equals tmp.Id
                                                 join tmp4 in bankdes
                                                 on a.CustomerId equals tmp4.Id
                                                 orderby a.ImplementTime, a.CreatedDate, a.UpdatedDate descending
                                                 select new
                                                 {
                                                     orderid = a.Id,
                                                     a.PubTime,
                                                     Project = tmp.ProjectId,
                                                     CustomerId = a.CustomerId,
                                                     ATMID = tmp.AtmNo,
                                                     Location = tmp.ATMName,
                                                     Customer = tmp4.Name,
                                                     Area = a.OrderStatus,
                                                     JobDate = a.ImplementTime
                                                 }).ToList();
                            var orderids = bankorderlist.Select(a => a.orderid).ToList();
                            var ordernoList = atmnolists.Where(a => orderids.Contains(a.BankOrderId))
                .Select(a => new { a.BankOrderId, a.LineName }).ToList();
                            foreach (var item2 in bankorderlist)
                            {
                                FSPOrderStatusbyCustomer or = new FSPOrderStatusbyCustomer();
                                or.Branch = item.Name;
                                or.Customer = item2.Customer;
                                or.JobDate = item2.JobDate;
                                or.ATMID = item2.ATMID;
                                or.Location = item2.Location;
                                or.Customer = item2.Customer;
                                or.RouteName = "";
                                var ordernost = ordernoList.Where(a => a.BankOrderId == item2.orderid).FirstOrDefault();
                                if (ordernost != null)
                                {
                                    or.RouteName = ordernost.LineName;
                                }
                                or.OrderStatus = ((item2.Area >= 11 && item2.Area < 22) || item2.Area == 24 || item2.Area == 25 ? "DONE" : "Pending");
                                OrderStatusbyCustomer.Add(or);
                            }
                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = OrderStatusbyCustomer.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<FSPOrderStatusbyCustomer>(query, "table_FSPOrderStatusbyCustomer");
                    Common.MongodbHelper.Add_List<FSPOrderStatusbyCustomer>("table_FSPOrderStatusbyCustomer", OrderStatusbyCustomer);

                    showLog("FSPOrderStatusbyCustomer", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("FSPOrderStatusbyCustomer----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("FSPOrderStatusbyCustomer", "Error:" + ex.Message);
                insertShowlog("FSPOrderStatusbyCustomer----Error" + ex.ToString(), st, et);
            }
            insertShowlog("FSPOrderStatusbyCustomer----End", st, et);
        }


        private void button17_Click(object sender, EventArgs e)
        {
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            ATMSummaryATMOrders(st, et);
        }
        private void ATMSummaryATMOrders(DateTime st, DateTime et)
        {
            showLog("ATMSummaryATMOrder", "Start");
            insertShowlog("ATMSummaryATMOrder----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<ATMSummaryATMOrder> atmsumorders = new List<ATMSummaryATMOrder>();
                    var bankdes = db.AtmCustomers.ToList();
                    var bank = bankdes.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).ToList();
                    var Banks = bank.Select(a => a.Name).ToList();
                    DateTime temp = st;
                    var _bankorder = db.BankOrders.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => a.ImplementTime.HasValue).Where(a => a.ImplementTime.Value >= st && a.ImplementTime.Value < et).Include(a => a.AtmAtm).Include(a => a.AtmCustomer).ToList();
                    var _inspection = db.Inspections.Where(a => a.ImplementTime.HasValue && a.AtmId.HasValue && !a.Deleted).Where(a => a.ImplementTime.Value >= st && a.ImplementTime.Value < et).Include(a => a.AtmAtm).Include(a => a.AtmCustomer).ToList();
                    var _repair = db.Repairs.Where(a => !a.Deleted).OrderByDescending(a => a.UpdatedDate).Where(a => a.FaultTime >= st && a.FaultTime < et).Include(a => a.AtmAtm).Include(a => a.AtmCustomer).ToList();
                    //
                    var prolist = db.SysProjects.Where(a => !a.Deleted).ToList();
                    //var atmlist = db.AtmAtms.Where(a => bankatmId.Contains(a.Id)).ToList();
                    while (temp < et)  //每天
                    {  // 每天下    也可以不根据时间分 在后面直接根据时间date ProjectId  客户分组 
                        DateTime temped = temp.AddDays(1);
                        foreach (var item in prolist)
                        { // 每个城市下      --     之前是每个城市 都要显示出来 没有的显示0  最后不用后 就 可以不根据城市分
                            //RM
                            var bankorderlist = _bankorder.Where(a => a.ImplementTime >= temp && a.ImplementTime < temped && a.AtmAtm.ProjectId == item.Id).Select(a => new
                            {
                                a.ImplementTime.Value.Date,
                                a.AtmAtm.ProjectId,
                                a.AtmCustomer.Name
                            }).GroupBy(a => new { a.Date, a.ProjectId, a.Name })    //分组求总
               .Select(a => new
               {
                   Type = "Replenishment",
                   a.Key.Date,
                   a.Key.ProjectId,
                   a.Key.Name,
                   Count = a.Count(),
               }).ToList();
                            var inspectionlist = _inspection.Where(a => a.ImplementTime >= temp && a.ImplementTime < temped && a.AtmAtm.ProjectId == item.Id).Select(a => new
                            {
                                a.ImplementTime.Value.Date,
                                a.AtmAtm.ProjectId,
                                a.AtmCustomer.Name
                            }).GroupBy(a => new { a.Date, a.ProjectId, a.Name })
                            .Select(a => new
                            {
                                Type = "FLM/SLM/PM",
                                a.Key.Date,
                                a.Key.ProjectId,
                                a.Key.Name,
                                Count = a.Count()
                            }).ToList();
                            var repairlist = _repair.Where(a => a.FaultTime >= temp && a.FaultTime < temped && a.AtmAtm.ProjectId == item.Id).Select(a => new
                            {
                                a.FaultTime.Date,
                                a.AtmAtm.ProjectId,
                                a.AtmCustomer.Name
                            }).GroupBy(a => new { a.Date, a.ProjectId, a.Name })
                       .Select(a => new
                       {
                           Type = "FLM/SLM/PM",
                           a.Key.Date,
                           a.Key.ProjectId,
                           a.Key.Name,
                           Count = a.Count()
                       }).ToList();
                            inspectionlist.AddRange(repairlist);
                            var Flmslmpmorder = inspectionlist.GroupBy(a => new { a.Date, a.ProjectId, a.Name }).Select(a => new
                            {
                                Type = "FLM/SLM/PM",
                                a.Key.Date,
                                a.Key.ProjectId,
                                a.Key.Name,
                                Count = a.Sum(i => i.Count)
                            }).ToList();

                            bankorderlist.AddRange(Flmslmpmorder);
                            //FLM/SLM/PM
                            foreach (var itemor in bankorderlist)
                            {
                                ATMSummaryATMOrder asaOrder = new ATMSummaryATMOrder();
                                asaOrder.Branch = item.Name;
                                asaOrder.Bank = itemor.Name;
                                asaOrder.JobDate = itemor.Date;
                                asaOrder.Number = itemor.Count;
                                asaOrder.JobType = itemor.Type;
                                atmsumorders.Add(asaOrder);
                            }
                        }
                        temp = temp.AddDays(1);
                    }
                    var cntsd = atmsumorders.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.GTE("JobDate", st));
                    list1.Add(Query.LT("JobDate", et));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<ATMSummaryATMOrder>(query, "table_ATMSummaryATMOrder");
                    Common.MongodbHelper.Add_List<ATMSummaryATMOrder>("table_ATMSummaryATMOrder", atmsumorders);
                    showLog("ATMSummaryATMOrder", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("ATMSummaryATMOrder----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("ATMSummaryATMOrder", "Error:" + ex.Message);
                insertShowlog("ATMSummaryATMOrder----Error" + ex.ToString(), st, et);
            }
            insertShowlog("ATMSummaryATMOrder----End", st, et);
        }

        private void button18_Click(object sender, EventArgs e)
        {//ATM Summary ATM Number
            DateTime st = this.dateTimePicker1.Value;
            DateTime et = this.dateTimePicker2.Value.AddDays(1);
            ATMSummaryATMNumber(st, et);
        }
        private void ATMSummaryATMNumber(DateTime st, DateTime et)
        {
            showLog("ATMSummaryATMNumber", "Start");
            insertShowlog("ATMSummaryATMNumber----Start", st, et);
            try
            {
                using (var db = new ApplicationDb())
                {
                    List<ATMSummaryATMNumber> atmsum = new List<ATMSummaryATMNumber>();
                    var bankdes = db.AtmCustomers.ToList();
                    var prolist = db.SysProjects.ToList();
                    var Provinces = db.BaseDataMgrs.ToList();
                    //var atmCount = db.AtmAtms.Where(a => !a.Deleted && a.province != null && a.province != Guid.Empty).GroupBy(a => new { a.ProjectId, a.province, a.CustomerId, a.IsNon, a.JobType }).ToList();
                    //var atmCount = db.AtmAtms.Where(a => !a.Deleted).GroupBy(a => new { a.ProjectId, a.province, a.CustomerId, a.IsNon }
                    //).ToList();
                    DataTable dtlall = new MySqlHelper().ExecuteDataTable(@"SELECT  ProjectId,`province`,CustomerID,IsNon,jobtype,COUNT(1) cnt FROM t_atm_atm   WHERE `jobtype` IN(1,2,3)
 GROUP BY ProjectId,`province`,CustomerID,IsNon,jobtype ");
                    List<tmpATMCount> CountATMAll = new List<tmpATMCount>();
                    if (dtlall.Rows.Count > 0) CountATMAll = EntityConvert.GetEntities<tmpATMCount>(dtlall);

                    //存列
                    var Cloall = CountATMAll.Distinct(a => new { a.CustomerID, a.IsNon, a.jobtype }).OrderBy(a => a.CustomerID).ThenBy(a => a.IsNon).ThenBy(a => a.jobtype);
                    List<ATMSummaryATMNumberClo> atmclos = new List<ATMSummaryATMNumberClo>();
                    foreach (var item in Cloall)
                    {
                        ATMSummaryATMNumberClo aclo = new ATMSummaryATMNumberClo();
                        aclo.JobMonth = st.Month;
                        aclo.Bank = bankdes.FirstOrDefault(a => a.Id == item.CustomerID).Name;
                        aclo.CustomerID = item.CustomerID.ToStr();
                        aclo.IsNon = item.IsNon;
                        aclo.JobType = item.jobtype;
                        atmclos.Add(aclo);
                    }
                    var closd = atmclos.Count;
                    List<IMongoQuery> listclo = new List<IMongoQuery>();
                    listclo.Add(Query.EQ("JobMonth", st.Month));
                    IMongoQuery queryclo = Query.And(listclo);
                    Common.MongodbHelper.Remove<ATMSummaryATMNumberClo>(queryclo, "table_ATMSummaryATMNumberClo");
                    Common.MongodbHelper.Add_List<ATMSummaryATMNumberClo>("table_ATMSummaryATMNumberClo", atmclos);
                    var rowsall = CountATMAll.Distinct(a => new { a.ProjectId, a.province }).OrderBy(a => a.ProjectId).ThenBy(a => a.province);
                    foreach (var item in rowsall)
                    {
                        foreach (var item2 in atmclos)
                        {
                            ATMSummaryATMNumber asan = new ATMSummaryATMNumber();
                            asan.Branch = prolist.FirstOrDefault(a => a.Id == item.ProjectId).Name;
                            asan.Province = Provinces.FirstOrDefault(a => a.Id == item.province) != null ? Provinces.FirstOrDefault(a => a.Id == item.province).GroupName : "";
                            asan.Bank = item2.Bank;
                            asan.IsNon = item2.IsNon;
                            asan.JobMonth = st.Month;
                            asan.JobType = item2.JobType;
                            var num = CountATMAll.Where(a => a.ProjectId == item.ProjectId && a.province == item.province && a.CustomerID == (item2.CustomerID.TogGuid()) && a.IsNon == item2.IsNon && a.jobtype == item2.JobType);
                            asan.Number = num != null ? num.Sum(a => a.cnt) : 0;
                            atmsum.Add(asan);
                        }
                    }
                    var cntsd = atmsum.Count;
                    List<IMongoQuery> list1 = new List<IMongoQuery>();
                    list1.Add(Query.EQ("JobMonth", st.Month));
                    IMongoQuery query = Query.And(list1);
                    Common.MongodbHelper.Remove<ATMSummaryATMNumber>(query, "table_ATMSummaryATMNumber");
                    Common.MongodbHelper.Add_List<ATMSummaryATMNumber>("table_ATMSummaryATMNumber", atmsum);
                    showLog("ATMSummaryATMNumber", string.Format("{0} - {1} Ok . Data Count : {2} ."
                    , st.ToShortDateString(), et.ToShortDateString(), cntsd));
                    insertShowlog("ATMSummaryATMNumber----Count" + cntsd, st, et);
                }
            }
            catch (Exception ex)
            {
                showLog("ATMSummaryATMNumber", "Error:" + ex.Message);
                insertShowlog("ATMSummaryATMNumber----Error" + ex.ToString(), st, et);
            }
            insertShowlog("ATMSummaryATMNumber----End", st, et);
        }

    }
    public class tmpATMCount
    {
        public Guid ProjectId { get; set; }
        public Guid? province { get; set; }
        public Guid CustomerID { get; set; }
        public bool IsNon { get; set; }
        public int jobtype { get; set; }
        public int cnt { get; set; }
    }

    public class ShowLogTraceListener : TraceListener
    {
        //private Form1 frm;
        private IForm frm;     // 不继承 自定义为变量接收也可以
        public ShowLogTraceListener(IForm frm)
        {
            this.frm = frm;
        }
        //public ShowLogTraceListener(Form1 frm)
        //{
        //    this.frm = frm;
        //}
        /// <summary>
        /// Write
        /// </summary>
        public override void Write(string message)
        {
            message = Format(message, "");

            frm.showLog("Trace", message);
        }

        /// <summary>
        /// Write
        /// </summary>
        public override void Write(object obj)
        {
            string message = Format(obj, "");
            frm.showLog("Trace", message);
        }

        /// <summary>
        /// WriteLine
        /// </summary>
        public override void WriteLine(object obj)
        {
            string message = Format(obj, "");
            frm.showLog("Trace", message);
        }

        /// <summary>
        /// WriteLine
        /// </summary>
        public override void WriteLine(string message)
        {
            message = Format(message, "");
            frm.showLog("Trace", message);
        }

        /// <summary>
        /// WriteLine
        /// </summary>
        public override void WriteLine(object obj, string category)
        {
            string message = Format(obj, category);
            frm.showLog("Trace", message);
        }

        /// <summary>
        /// WriteLine
        /// </summary>
        public override void WriteLine(string message, string category)
        {
            message = Format(message, category);
            frm.showLog("Trace", message);
        }

        /// <summary>
        /// Format
        /// </summary>
        private string Format(object obj, string category)
        {
            StringBuilder builder = new StringBuilder();
            if (!string.IsNullOrEmpty(category))
                builder.AppendFormat("[{0}] ", category);
            if (obj is Exception)
            {
                var ex = (Exception)obj;
                builder.Append(ex.Message + "\r\n");
                builder.Append(ex.StackTrace + "\r\n");
            }
            else
            {
                builder.Append(obj.ToString() + "\r\n");
            }

            return builder.ToString();
        }
    }

    public interface IForm  // 转成单一用途接口
    {
        void showLog(string title, string message);
    }
    public class Summary : BaseEntity
    {
        public string Branck { get; set; }
        public string Item { get; set; }

        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Date { get; set; }
        public int Total { get; set; }
        public int Issued { get; set; }
        public int Returned { get; set; }
        public int Damaged { get; set; }
    }

    public class Issuereturn : BaseEntity
    {
        public string Barcode { get; set; }
        public string SerialNumber { get; set; }
        public string Item { get; set; }
        public string Branch { get; set; }
        public string Branchcode { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? IssueTime { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? ReturnTime { get; set; }
        public string Route { get; set; }
        public string Description { get; set; }
        public string CL { get; set; }
        public string CD { get; set; }
        public string CM { get; set; }
        public string ATMID { get; set; }
        public string Name { get; set; }    // Mobile Phone issue  Staff ID
        public string Key { get; set; }
        public string Password { get; set; }
        public string Remark { get; set; }
        public string IMEI { get; set; }
        public string TruckType { get; set; }
        public string CallSign { get; set; }
        public string LicensePlate { get; set; }
        public string Brand { get; set; }
        public string Category { get; set; }
        public string BarcodeKey { get; set; }
        public string ItemBarcode { get; set; }
        public string Number { get; set; }     // IMEI  pad -excel上的
        public string Model { get; set; }    //   pad -excel上的 Brand
        public string Customer { get; set; }
        public string AssetCode { get; set; }

        public string DispatchIssued { get; set; }
        public string DispatchReturned { get; set; }

        public string ATMShortcode { get; set; }
        public string PdaModel { get; set; }    //pad -excel上的model
        public string StaffName { get; set; }
        public string StaffID { get; set; }
        public string KeySparekey { get; set; }
        public string CardNumber { get; set; }
        public string RegisterProvince { get; set; }
    }

    public class RouteTotal : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string RouteName { get; set; }


        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? CrewLeaderScanIn { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? CrewLeaderScanOut { get; set; }
        public string CrewLeader { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? CrewDriverScanIn { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? CrewDriverScanOut { get; set; }

        public string CrewDriver { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? CrewMemberScanIn { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? CrewMemberScanOut { get; set; }

        public string CrewMember { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? FingerScanin { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? FingerScanOut { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Rosteredstart { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Inbaytime { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Outbaytime { get; set; }
        public string Drivetimetotal { get; set; }
        public string Loadingtimetotal { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip1_Depart { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip1_Return { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip2_Depart { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip2_Return { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip3_Depart { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip3_Return { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip4_Depart { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip4_Return { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip5_Depart { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Trip5_Return { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Returnbaytime { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? Runfinish { get; set; }
        public string Runduration { get; set; }
        public string GatetoGate { get; set; }
        public string Unloadtimetotal { get; set; }
        public string Lunch_mins { get; set; }
        public string Jobs_completed { get; set; }
        public string Jobsnotcompleted { get; set; }
        public string Totaljob { get; set; }
        public string Hrsworked { get; set; }
        public string HrsworkedincludingLunch { get; set; }
        public string KPIHrs_hr { get; set; }
        public string KPIJob_hr { get; set; }
        public string TruckNumber { get; set; }
        public string StartKms { get; set; }
        public string FinishKms { get; set; }
        public string Routedkms { get; set; }
        public string Comments { get; set; }
        public string Crewno { get; set; }
        public string Remark { set; get; }
    }

    public class SummaryofOrder : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string Bank { get; set; }
        public int OrderInAdvance { get; set; }
        public int SameDayOrder { get; set; }
        public int CassetteDamage { get; set; }
        public int DropBag { get; set; }
        public int TotalOrder { get { return OrderInAdvance + SameDayOrder + CassetteDamage + DropBag; } }
    }

    public class ResultofOrder : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string Bank { get; set; }
        public int Done { get; set; }
        public int DropBag { get; set; }
        public int BadCassette { get; set; }
        public int Failed { get; set; }
        public int Totalorder { get; set; }
    }

    public class OrderStatusbyCustomer : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string ATMID { get; set; }
        public string Location { get; set; }
        public string Customer { get; set; }
        public string RouteName { get; set; }
        public string OrderStatus { get; set; }
    }
    public class OrderStatusbyRoute : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string RouteName { get; set; }
        public int JobAssigned { get; set; }
        public int JobDone { get; set; }
        public int Pending { get { return JobAssigned - JobDone; } }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? DepatureTime { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? ReturnTime { get; set; }
    }




    //只供查看异常状态
    public class ShowReportlog : BaseEntity
    {
        public string JobDate { get; set; }
        public string Content { get; set; }
    }

    public class FSPResultofOrder : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string Bank { get; set; }
        public int Done { get; set; }
        public int Failed { get; set; }
        //public int Totalorder { get; set; }
        public int Totalorder { get { return Done + Failed; } }
    }

    public class FSPSummaryofOrder : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string Bank { get; set; }
        public int OrderInAdvance { get; set; }
        public int SameDayOrder { get; set; }
        //public int CassetteDamage { get; set; }
        //public int DropBag { get; set; }
        //public int TotalOrder { get { return OrderInAdvance + SameDayOrder + CassetteDamage + DropBag; } }
        public int TotalOrder { get { return OrderInAdvance + SameDayOrder; } }
    }

    public class FSPOrderStatusbyRoute : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string RouteName { get; set; }
        public int JobAssigned { get; set; }
        public int JobDone { get; set; }
        public int Pending { get { return JobAssigned - JobDone; } }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? DepatureTime { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? ReturnTime { get; set; }
    }
    public class FSPOrderStatusbyCustomer : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string ATMID { get; set; }
        public string Location { get; set; }
        public string Customer { get; set; }
        public string RouteName { get; set; }
        public string OrderStatus { get; set; }
    }
    public class ATMSummaryATMOrder : BaseEntity
    {
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime? JobDate { get; set; }
        public string Branch { get; set; }
        public string Bank { get; set; }
        public string JobType { get; set; }  //RM  -  FLM/SLM/PM
        public int Number { get; set; }
    }
    public class ATMSummaryATMNumber : BaseEntity
    {
        public int JobMonth { get; set; }    //月份
        public string Branch { get; set; }    //城市
        public string Bank { get; set; }    //客户
        public string Province { get; set; }    //片区
        public bool IsNon { get; set; }     //是否包车  DV 
        public int JobType { get; set; }      //ATM/RATM
        public int Number { get; set; }
    }
    public class ATMSummaryATMNumberClo : BaseEntity
    {
        public int JobMonth { get; set; }    //月份
        public string Bank { get; set; }    //客户
        public string CustomerID { get; set; }
        public bool IsNon { get; set; }     //是否包车   DV 
        public int JobType { get; set; }      //ATM/RATM
    }
}

 

posted @ 2018-11-08 11:05  ~雨落忧伤~  阅读(112)  评论(0编辑  收藏  举报