using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;

namespace OpenAuth.App
{
    public partial class DroneCaseinfoApp
    {

        #region 用户

        public JToken GetCurrentUser()
        {
            var current = _auth.GetCurrentUser();
            var user = current.User;
            var roles = current.Roles;
            JObject obj = new JObject();

            string currentRoleStr = roles.Select(c => new { id = c.Id, name = c.Name }).ToList().ToJson();
            JToken currentRoleJToken = (JToken)JsonConvert.DeserializeObject(currentRoleStr);

            //用户
            JToken userJtoken = user.ToJson().ToJToken();

            var managerCount = roles.Where(c => c.Name.Contains("管理员")).Count();

            //权限
            int law = 0;

            //案件分发
            int street_manager = 0;
            //案件审核
            int county_manager = 0;
            //案件核销
            int inspect_remove = 0;

            //案件分发
            var streetAuth = roles.Where(c => c.Name == "案件分发").Count();

            //案件审核
            var countyAuth = roles.Where(c => c.Name == "案件审核").Count();

            //案件核销
            var inspectRemoveAuth = roles.Where(c => c.Name == "案件核销").Count();

            int result = 0;

            if (managerCount > 0)
                result = 1;

            if (result == 0 && streetAuth > 0)
                result = 1;

            obj.Add("user", userJtoken);
            obj.Add("auth", result);

            if (streetAuth > 0)
                street_manager = 1;
            if (countyAuth > 0)
                county_manager = 1;
            if (inspectRemoveAuth > 0)
                inspect_remove = 1;

            obj.Add("street_manager", street_manager);
            obj.Add("county_manager", county_manager);
            obj.Add("inspect_remove", inspectRemoveAuth);

            //查询geoserver
            string geoserver = "";

            //string tenantId = HttpContextExt.GetTenantId();
            //if (!string.IsNullOrEmpty(tenantId))
            //{
            //    var tenantModel = _options.Value.TenantList.Where(c => c.id == tenantId).FirstOrDefault();
            //    if (tenantModel != null)
            //    {
            //        geoserver = tenantModel.geoserver;
            //    }
            //}
            obj.Add("geoserver", geoserver);
            obj.Add("roles", currentRoleJToken);

            return obj;

        }
        #endregion

        #region 案件处理
        /// <summary>
        /// 获取要添加的文件列表
        /// </summary>
        /// <param name="req"></param>
        /// <param name="existFiles"></param>
        /// <param name="user"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<DroneFiles> GetFilesList(AddOrUpdateDroneCaseDealReq req, List<DroneFiles> existFiles, SysUser user, DroneCaseDeal model)
        {
            req.video_list = req.video_list.InitListData<string>();

            //视频
            var videoList = req.video_list.InitListData();
            //拆除视频
            var removeVideoList = req.remove_video_list.InitListData();
            //照片
            var picInfoList = req.pic_info_list.InitListData();
            //整改后照片
            var afterPicList = req.after_pic_list.InitListData();
            //合法照片
            var evidenceFileList = req.evidence_file_list.InitListData();
            //处罚通知书
            var punish_pic_list = req.punish_pic_list.InitListData();
            // 交款通知书
            var payment_pic_list = req.payment_pic_list.InitListData();
            // 政府同意完善手续证明
            var agree_checkout_pic_list = req.agree_checkout_pic_list.InitListData();
            // 办理手续
            var checkout_pic_list = req.checkout_pic_list.InitListData();
            // 勘测定界图
            var boundary_pic_list = req.boundary_pic_list.InitListData();

            List<DroneFiles> filesList = new List<DroneFiles>();
            //图片
            for (int i = 0; i < picInfoList.Count; i++)
            {
                var item = picInfoList[i];
                var count = existFiles.Where(c => c.path == item.FilePath).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item.FilePath;
                fileModel.latitude = item.Latitude;
                fileModel.longitude = item.Longitude;
                fileModel.angle = item.Angle;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //整改后照片
            for (int i = 0; i < afterPicList.Count; i++)
            {
                var item = afterPicList[i];
                var count = existFiles.Where(c => c.path == item.FilePath).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item.FilePath;
                fileModel.latitude = item.Latitude;
                fileModel.longitude = item.Longitude;
                fileModel.angle = item.Angle;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = afterPicTag;

                filesList.Add(fileModel);
            }

            //合法材料
            for (int i = 0; i < evidenceFileList.Count; i++)
            {
                var item = evidenceFileList[i];
                var count = existFiles.Where(c => c.path == item.FilePath).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item.FilePath;
                fileModel.latitude = item.Latitude;
                fileModel.longitude = item.Longitude;
                fileModel.angle = item.Angle;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = EvidenceFileTag;

                filesList.Add(fileModel);
            }

            //处罚通知书
            for (int i = 0; i < punish_pic_list.Count; i++)
            {
                var item = punish_pic_list[i];
                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = punishPicTag;

                filesList.Add(fileModel);
            }

            //交款通知书
            for (int i = 0; i < payment_pic_list.Count; i++)
            {
                var item = payment_pic_list[i];
                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = paymentPicTag;

                filesList.Add(fileModel);
            }

            //政府同意完善手续证明
            for (int i = 0; i < agree_checkout_pic_list.Count; i++)
            {
                var item = agree_checkout_pic_list[i];
                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = agreeCheckoutPicTag;

                filesList.Add(fileModel);
            }

            //办理手续
            for (int i = 0; i < checkout_pic_list.Count; i++)
            {
                var item = checkout_pic_list[i];
                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = checkoutPicTag;

                filesList.Add(fileModel);
            }

            //勘测定界图
            for (int i = 0; i < boundary_pic_list.Count; i++)
            {
                var item = boundary_pic_list[i];
                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item;
                fileModel.type = 0;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = boundaryPicTag;

                filesList.Add(fileModel);
            }

            //视频
            for (int i = 0; i < videoList.Count; i++)
            {
                var item = videoList[i];
                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item;
                fileModel.type = 1;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //拆除视频
            for (int i = 0; i < removeVideoList.Count; i++)
            {
                var item = removeVideoList[i];
                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = SnowFlakeSingle.Instance.NextId().ToString();
                fileModel.path = item;
                fileModel.type = 1;
                fileModel.tablename = "drone_case_deal";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;
                fileModel.tag = "remove";

                filesList.Add(fileModel);
            }

            return filesList;
        }

        /// <summary>
        /// 案件核查
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response<bool> AddExamineDeal(AddOrUpdateDroneCaseDealReq req)
        {
            var response = new Response<bool>();

            var user = _auth.GetCurrentUser().User;

            var model = req.info;

            model.Id = model.caseid;
            model.createtime = DateTime.Now;
            model.createuser = user.Id.ToString();
            model.createusername = user.Name;
            model.is_delete = 0;
            model.examiner_id = user.Id.ToString();
            model.examiner_name = user.Name;
            model.examine_time = DateTime.Now;

            using (var uwo = UnitWork.CreateContext())
            {
                var _count = uwo.DroneCaseDeal.Count(c => c.caseid == req.info.caseid);
                if (_count > 0)
                    throw new Exception("已存在此图斑的处理数据");

                var filesList = GetFilesList(req, new List<DroneFiles>(), user, model);


                //新增数据
                uwo.DroneCaseDeal.Insert(model);

                //新增数据
                uwo.DroneFiles.InsertRange(filesList);

                //更新案件状态
                uwo.DroneCaseInfo.UpdateSetColumnsTrue(c => new DroneCaseInfo
                {
                    measure_name = model.measure_name,      //处理措施
                    is_illegal = req.is_illegal,
                }, c => c.Id == model.caseid);


                if (req.is_temp_save == null || req.is_temp_save == 0)
                {
                    var handleStatusName = handleStatusList.Where(c => c.id == 0 && c.is_examine == 1).FirstOrDefault().name;

                    //更新案件状态
                    uwo.DroneCaseInfo.UpdateSetColumnsTrue(c => new DroneCaseInfo
                    {
                        measure_name = model.measure_name,      //处理措施
                        is_illegal = req.is_illegal,
                        is_examine = 1,
                        handle_status_name = handleStatusName,
                        examiner_id = user.Id.ToString(),
                        examiner_name = user.Name,
                        examine_time = DateTime.Now
                    }, c => c.Id == model.caseid);


                    if (req.is_illegal == 2)
                    {
                        //处理状态：默认 1 办理中
                        int? handle_status_id = 1;
                        string handle_status_name = handleStatusList.Where(c => c.id == handle_status_id).FirstOrDefault().name;

                        //查询审核流程，处理后，审核状态设置为第一个节点
                        var verifyModel = uwo.DroneFlowInstance.AsQueryable().Where(c => c.instance_name == "CaseVerify" && c.status == 0).OrderBy(c => c.sort, OrderByType.Asc).First();
                        if (verifyModel == null)
                            throw new Exception("找不到流程");

                        //更新案件状态
                        uwo.DroneCaseInfo.UpdateSetColumnsTrue(c => new DroneCaseInfo
                        {
                            handle_status_id = handle_status_id,
                            handle_status_name = handle_status_name,
                            is_illegal = req.is_illegal,
                            deal_userid = user.Id.ToString(),
                            deal_username = user.Name,
                            deal_time = model.createtime,
                            verifystatus = verifyModel.sort,        //审核状态
                            verifystatusname = verifyModel.name     //审核状态名称
                        }, c => c.Id == model.caseid);
                    }

                    AddDroneCaseLog(new DroneCaseOperationLog { request_data = req.ToJson(), description = "AddExamineDeal", caseid = model.caseid, createuserid = user.Id.ToString(), createusername = user.Name });
                }


                if (req.is_temp_save == null || req.is_temp_save == 0)
                {
                    //发送websocket消息
                    //SendWebSocketMessage("newdeal");
                }


                var flag = uwo.Commit();
                if (flag)
                {
                    response.Message = "处理成功";
                    response.Result = true;
                }
                else
                {
                    response.Message = "处理失败";
                    response.Result = false;
                }
                return response;
            }
        }

        /// <summary>
        /// 案件核查
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response<bool> UpdateExamineDeal(AddOrUpdateDroneCaseDealReq req)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            using (var uwo = UnitWork.CreateContext())
            {
                var model = req.info;

                model.examiner_id = user.Id.ToString();
                model.examiner_name = user.Name;
                model.examine_time = DateTime.Now;

                var existFiles = uwo.DroneFiles.GetList(c => c.relid == req.info.Id && c.tablename == "drone_case_deal");
                var filesList = GetFilesList(req, existFiles, user, model);

                //使用事务提交数据

                //新增数据
                uwo.DroneCaseDeal.Update(model);

                //新增数据
                uwo.DroneFiles.InsertRange(filesList);

                //更新案件状态
                uwo.DroneCaseInfo.UpdateSetColumnsTrue
                (c => new DroneCaseInfo
                {
                    measure_name = model.measure_name,      //处理措施
                    is_illegal = req.is_illegal,
                }, c => c.Id == model.caseid);

                if (req.is_temp_save == null || req.is_temp_save == 0)
                {
                    var handleStatusName = handleStatusList.Where(c => c.id == 0 && c.is_examine == 1).FirstOrDefault().name;

                    //更新案件状态
                    uwo.DroneCaseInfo.UpdateSetColumnsTrue(c => new DroneCaseInfo
                    {
                        measure_name = model.measure_name,      //处理措施
                        is_illegal = req.is_illegal,
                        is_examine = 1,
                        handle_status_name = handleStatusName,
                        examiner_id = user.Id.ToString(),
                        examiner_name = user.Name,
                        examine_time = DateTime.Now
                    }, c => c.Id == model.caseid);


                    if (req.is_illegal == 2)
                    {
                        //处理状态：默认 1 办理中
                        int? handle_status_id = 1;
                        string handle_status_name = handleStatusList.Where(c => c.id == handle_status_id).FirstOrDefault().name;

                        //查询审核流程，处理后，审核状态设置为第一个节点
                        var verifyModel = uwo.DroneFlowInstance.AsQueryable().Where(c => c.instance_name == "CaseVerify" && c.status == 0).OrderBy(c => c.sort, OrderByType.Asc).First();
                        if (verifyModel == null)
                            throw new Exception("找不到流程");

                        //更新案件状态
                        uwo.DroneCaseInfo.UpdateSetColumnsTrue(c => new DroneCaseInfo
                        {
                            handle_status_id = handle_status_id,
                            handle_status_name = handle_status_name,
                            is_illegal = req.is_illegal,
                            deal_userid = user.Id.ToString(),
                            deal_username = user.Name,
                            deal_time = model.createtime,
                            verifystatus = verifyModel.sort,        //审核状态
                            verifystatusname = verifyModel.name     //审核状态名称
                        }, c => c.Id == model.caseid);


                    }

                    AddDroneCaseLog(new DroneCaseOperationLog { request_data = req.ToJson(), description = "UpdateExamineDeal", caseid = model.caseid, createuserid = user.Id.ToString(), createusername = user.Name });
                }


                if (req.is_temp_save == null || req.is_temp_save == 0)
                {
                    //发送websocket消息
                    //SendWebSocketMessage("newdeal");
                }

                var flag = uwo.Commit();
                if (flag)
                {
                    response.Result = true;
                    response.Message = "处理成功";
                }
                else
                {
                    response.Result = false;
                    response.Message = "处理失败";
                }

                return response;
            }
        }

        /// <summary>
        /// 案件处理
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response<bool> AddDroneCaseDeal(AddOrUpdateDroneCaseDealReq req)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            using (var uwo = UnitWork.CreateContext())
            {
                var model = req.info;

                model.Id = model.caseid;
                model.createtime = DateTime.Now;
                model.createuser = user.Id.ToString();
                model.createusername = user.Name;
                model.is_delete = 0;
                model.examiner_id = user.Id.ToString();
                model.examiner_name = user.Name;
                model.examine_time = DateTime.Now;

                //办理人、办理时间
                model.transact_time = DateTime.Now;
                model.transactor_id = user.Id.ToString();
                model.transactor_name = user.Name;

                var _count = uwo.DroneCaseDeal.Count(c => c.caseid == req.info.caseid);
                if (_count > 0)
                    throw new Exception("已存在此图斑的处理数据");

                //处理状态：默认 1 办理中
                int? handle_status_id = 1;
                string handle_status_name = string.Empty;
                if (handle_status_id != null)
                {
                    handle_status_name = handleStatusList.Where(c => c.id == handle_status_id).FirstOrDefault().name;
                }

                List<DroneFiles> filesList = GetFilesList(req, new List<DroneFiles>(), user, model);

                //查询审核流程，处理后，审核状态设置为第一个节点
                var verifyModel = uwo.DroneFlowInstance.AsQueryable().Where(c => c.instance_name == "CaseVerify" && c.status == 0).OrderBy(c => c.sort, OrderByType.Asc).First();
                if (verifyModel == null)
                    throw new Exception("找不到流程");


                //新增数据
                uwo.DroneCaseDeal.Insert(model);

                //新增数据
                uwo.DroneFiles.InsertRange(filesList);

                if (req.is_temp_save == null || req.is_temp_save == 0)
                {
                    //更新案件状态
                    uwo.DroneCaseInfo.UpdateSetColumnsTrue
                    (c => new DroneCaseInfo
                    {
                        handle_status_id = handle_status_id,
                        handle_status_name = handle_status_name,
                        is_illegal = req.is_illegal,
                        deal_userid = user.Id.ToString(),
                        deal_username = user.Name,
                        deal_time = model.createtime,
                        verifystatus = verifyModel.sort,        //审核状态
                        verifystatusname = verifyModel.name     //审核状态名称
                    }, c => c.Id == model.caseid);

                    AddDroneCaseLog(new DroneCaseOperationLog { request_data = req.ToJson(), description = "AddDroneCaseDeal", caseid = model.caseid, createuserid = user.Id.ToString(), createusername = user.Name });
                }


                if (req.is_temp_save == null || req.is_temp_save == 0)
                {
                    //发送websocket消息
                    //SendWebSocketMessage("newdeal");
                }

                var flag = uwo.Commit();

                if (flag)
                {
                    response.Result = true;
                    response.Message = "处理成功";
                }
                else
                {
                    response.Result = false;
                    response.Message = "处理失败";
                }
                return response;
            }
        }

        /// <summary>
        /// 更新案件处理数据
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response<bool> UpdateDroneCaseDeal(AddOrUpdateDroneCaseDealReq req)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            using (var uwo = UnitWork.CreateContext())
            {
                var model = req.info;

                var caseModel = uwo.DroneCaseInfo.GetFirst(c => c.Id == model.caseid);

                //处理状态：默认 1 办理中
                int? handle_status_id = 1;
                string handle_status_name = string.Empty;
                if (handle_status_id != null)
                {
                    handle_status_name = handleStatusList.Where(c => c.id == handle_status_id).FirstOrDefault().name;
                }

                var existFiles = uwo.DroneFiles.GetList(c => c.relid == req.info.Id && c.tablename == "drone_case_deal");

                var filesList = GetFilesList(req, existFiles, user, model);

                //查询审核流程，处理后，审核状态设置为第一个节点
                var verifyModel = uwo.DroneFlowInstance.AsQueryable().Where(c => c.instance_name == "CaseVerify" && c.status == 0).OrderBy(c => c.sort, OrderByType.Asc).First();
                if (verifyModel == null)
                    throw new Exception("找不到流程");

                //更新数据
                if (caseModel.handle_status_id == 0)
                {
                    //如果案件未处理，处理的时候更新时间和用户
                    model.createtime = DateTime.Now;
                    model.createuser = user.Id.ToString();
                    model.createusername = user.Name;

                    //办理人、办理时间
                    model.transact_time = DateTime.Now;
                    model.transactor_id = user.Id.ToString();
                    model.transactor_name = user.Name;
                }
                uwo.DroneCaseDeal.Update(model);

                uwo.DroneFiles.InsertRange(filesList);

                //是否暂存，如果不是暂存，就要设置案件的流程
                if (req.is_temp_save == null || req.is_temp_save == 0)
                {
                    //更新案件状态
                    uwo.DroneCaseInfo.AsUpdateable()
                   .SetColumns(c => new DroneCaseInfo
                   {
                       handle_status_id = handle_status_id,
                       handle_status_name = handle_status_name,
                       is_illegal = req.is_illegal,
                       deal_time = model.createtime,
                       deal_userid = model.createuser,
                       deal_username = model.createusername,
                   })
                   .SetColumnsIF(caseModel.handle_status_id == 0, c => new DroneCaseInfo
                   {
                       verifystatus = verifyModel.sort,         //审核状态
                       verifystatusname = verifyModel.name,     //审核状态名称
                   })
                   .Where(c => c.Id == model.caseid)
                   .ExecuteCommand();

                    //AddDroneCaseLog(db, new Sugar_Drone_case_operation_log { request_data = req.ToJson(), description = "UpdateDroneCaseDeal", caseid = model.caseid, createuserid = user.Id, createusername = user.Name });
                }


                //是否暂存，如果不是暂存，就要发websocket消息
                if ((req.is_temp_save == null || req.is_temp_save == 0) && caseModel.handle_status_id == 0)
                {
                    //发送websocket消息
                    //SendWebSocketMessage("newdeal");
                }

                var flag = uwo.Commit();

                if (flag)
                {
                    response.Result = true;
                    response.Message = "处理成功";
                }
                else
                {
                    response.Result = false;
                    response.Message = "处理失败";
                }
                return response;
            }
        }


        /// <summary>
        /// 处理查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public PageInfo<List<DroneCaseDeal>> LoadDroneCaseDeal(QueryDroneCaseDealReq req)
        {
            var user = _auth.GetCurrentUser().User;

            //总条数
            int totalNumber = 0;
            //关联查询
            var list = client.Queryable<DroneCaseDeal, Sugar_Drone_caseinfo>((c, d) => new JoinQueryInfos(
                     JoinType.Left, c.caseid == d.Id
                 )).Where((c, d) => (c.is_delete == null || c.is_delete == 0) && (d.is_delete == null || d.is_delete == 0) && d.Id != null)
                //是否创建人过滤
                .WhereIF(req.is_report == 1, (c, d) => c.createuser == user.Id.ToString())
                //开始时间
                .WhereIF(req.start_time != null, (c, d) => c.createtime > req.start_time)
                //结束时间
                .WhereIF(req.end_time != null, (c, d) => c.createtime < req.end_time)
                //排序
                .OrderBy(c => c.createtime, OrderByType.Desc)
                //分页
                .ToPageList(req.page, req.limit, ref totalNumber);

            return new PageInfo<List<DroneCaseDeal>>
            {
                Items = list,
                Total = totalNumber
            };
        }

        /// <summary>
        /// 获取处理详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="caseid"></param>
        /// <returns></returns>
        public AddOrUpdateDroneCaseDealReq GetDroneCaseDeal(string id, string caseid)
        {
            AddOrUpdateDroneCaseDealReq res = new AddOrUpdateDroneCaseDealReq();
            res.Init();

            //详情
            var info = client.Queryable<DroneCaseDeal>()
                .WhereIF(!string.IsNullOrEmpty(id), c => c.Id == id)
                .WhereIF(!string.IsNullOrEmpty(caseid), c => c.caseid == caseid)
                .Where(c => c.is_delete == 0 || c.is_delete == null)
                .OrderBy(c => c.createtime, OrderByType.Desc)
                .First();
            if (info == null)
            {
                return res;
            }
            //文件
            var fileList = client.Queryable<DroneFiles>().Where(c => c.relid == info.Id && (c.is_delete == null || c.is_delete == 0) && c.tablename == "drone_case_deal").ToList();

            //图片
            List<PicInfo> picInfoList = fileList.Where(c => c.type == 0 && (c.tag == null || c.tag == "")).Select(c => new PicInfo
            {
                FilePath = c.path,
                Latitude = c.latitude,
                Longitude = c.longitude,
                Angle = c.angle,
            }).ToList();

            //整改后照片
            List<PicInfo> afterPicList = fileList.Where(c => c.type == 0 && c.tag == afterPicTag).Select(c => new PicInfo
            {
                FilePath = c.path,
                Latitude = c.latitude,
                Longitude = c.longitude,
                Angle = c.angle,
            }).ToList();

            //合法材料
            List<PicInfo> evidenceFileList = fileList.Where(c => c.type == 0 && c.tag == EvidenceFileTag).Select(c => new PicInfo
            {
                FilePath = c.path,
                Latitude = c.latitude,
                Longitude = c.longitude,
                Angle = c.angle,
            }).ToList();

            //处罚通知书
            var punish_pic_list = fileList.Where(c => c.type == 0 && c.tag == punishPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //交款通知书
            var payment_pic_list = fileList.Where(c => c.type == 0 && c.tag == paymentPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //政府同意完善手续证明
            var agree_checkout_pic_list = fileList.Where(c => c.type == 0 && c.tag == agreeCheckoutPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //办理手续
            var checkout_pic_list = fileList.Where(c => c.type == 0 && c.tag == checkoutPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //勘测定界图
            var boundary_pic_list = fileList.Where(c => c.type == 0 && c.tag == boundaryPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //视频
            var video_list = fileList.Where(c => c.type == 1 && (c.tag == null || c.tag == "")).GroupBy(c => c.path).Select(c => c.Key).ToList();

            var remove_video_list = fileList.Where(c => c.type == 1 && (c.tag == "remove")).GroupBy(c => c.path).Select(c => c.Key).ToList();
            //详情
            res.info = info;
            //照片
            res.pic_info_list = picInfoList;
            //整改后照片
            res.after_pic_list = afterPicList;
            //合法材料
            res.evidence_file_list = evidenceFileList;
            //处罚通知书
            res.punish_pic_list = punish_pic_list;
            //交款通知书
            res.payment_pic_list = payment_pic_list;
            //政府同意完善手续证明
            res.agree_checkout_pic_list = agree_checkout_pic_list;
            //办理手续
            res.checkout_pic_list = checkout_pic_list;
            //勘测定界图
            res.boundary_pic_list = boundary_pic_list;
            //视频
            res.video_list = video_list;
            //拆除视频
            res.remove_video_list = remove_video_list;

            var caseModel = client.Queryable<Sugar_Drone_caseinfo>()
                .Where(c => c.Id == info.caseid)
                .First();
            res.handle_status_id = caseModel.handle_status_id.Value;
            res.is_illegal = caseModel.is_illegal;

            var current = _auth.GetCurrentUser();
            var roleList = current.Roles;
            //判断是否有审核权限
            var roles = roleList.Select(c => c.Id.ToString()).ToList();
            //查询用户角色绑定的流程有哪些
            var flowList = client.Queryable<DroneRelevance>().Where(c => roles.Contains(c.SecondId) && c.Key == Define.FLOW_ROLE).Select(c => c.FirstId).ToList();
            //查询用户绑定的流程Sort，用于判断用户是否有权限来审核
            var currentFlowList = client.Queryable<DroneFlowInstance>().Where(c => flowList.Contains(c.Id) && c.status == 0 && c.instance_name == "CaseVerify").Select(c => c.sort).ToList();

            //审核状态和处理状态
            var verifystatus = caseModel.verifystatus;
            var handle_status_id = caseModel.handle_status_id;

            //审核
            if (handle_status_id == 1)
            {
                //当前角色绑定的流程
                var count = currentFlowList.Where(c => c == verifystatus).Count();
                var hasVerifyRole = roleList.Where(c => c.Name == "案件审核").Count();
                if (count > 0 && hasVerifyRole > 0)
                {
                    res.can_verify = 1;
                }
            }

            return res;

        }

        /// <summary>
        /// 删除处理
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Response<bool> DeleteDroneCaseDeal(string[] ids)
        {
            var respone = new Response<bool>();
            var flag = client.Updateable<DroneCaseDeal>()
                .SetColumns(c => new DroneCaseDeal { is_delete = 1 })
                .Where(c => ids.Contains(c.Id))
                .ExecuteCommand();

            if (flag > 0)
            {
                respone.Result = true;
                respone.Message = "删除成功";
            }
            else
            {
                respone.Result = false;
                respone.Message = "删除失败";
            }
            return respone;
        }
        #endregion

        #region 案件审核流程相关

        /// <summary>
        /// 查询流程
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public PageInfo<List<DroneFlowInstance>> LoadDroneFlowInstance(QueryDroneFlowInstanceReq req)
        {
            int total = 0;
            var list = client.Queryable<DroneFlowInstance>().WhereIF(!string.IsNullOrEmpty(req.key), c => c.name.Contains(req.key) || c.instance_name.Contains(req.key))
                .OrderBy(c => c.createtime, OrderByType.Desc)
                .ToPageList(req.page, req.limit, ref total);

            return new PageInfo<List<DroneFlowInstance>>
            {
                Items = list,
                Total = total
            };
        }

        /// <summary>
        /// 获取流程详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DroneFlowInstance GetDroneFlowInstance(string id)
        {
            return client.Queryable<DroneFlowInstance>().Where(c => c.Id == id).First();
        }

        /// <summary>
        /// 新增或修改流程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Response<bool> AddDroneFlowInstance([FromBody] DroneFlowInstance model)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            model.Id = SnowFlakeSingle.Instance.getID().ToString();
            model.createtime = DateTime.Now;
            model.createuserid = user.Id.ToString();
            model.createusername = user.Name;

            var flag = client.Insertable(model).ExecuteCommand();

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "添加成功";
            }
            else
            {
                response.Result = false;
                response.Message = "添加失败";
            }
            return response;
        }

        /// <summary>
        /// 新增或修改流程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Response<bool> UpdateDroneFlowInstance([FromBody] DroneFlowInstance model)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            model.updatetime = DateTime.Now;
            model.updateuserid = user.Id.ToString();
            model.updateusername = user.Name;

            var flag = client.Updateable(model).ExecuteCommand();

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "修改成功";
            }
            else
            {
                response.Result = false;
                response.Message = "修改失败";
            }

            return response;
        }

        /// <summary>
        /// 删除流程
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Response<bool> DeleteDroneFlowInstance(string[] ids)
        {
            var response = new Response<bool>();
            var flag = client.Deleteable<DroneFlowInstance>().Where(c => ids.Contains(c.Id)).ExecuteCommand();

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "删除成功";
            }
            else
            {
                response.Result = false;
                response.Message = "删除失败";
            }
            return response;
        }

        /// <summary>
        /// 停用流程
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Response<bool> BlockUpDroneFlowInstance(string[] ids)
        {
            var response = new Response<bool>();
            var flag = client.Updateable<DroneFlowInstance>().SetColumns(c => new DroneFlowInstance()
            {
                status = 1
            }).Where(c => ids.Contains(c.Id)).ExecuteCommand();

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "设置成功";
            }
            else
            {
                response.Result = false;
                response.Message = "设置失败";
            }
            return response;
        }

        /// <summary>
        /// 流程角色绑定
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response<bool> DroneFlowInstanceBindRole(AddOrUpdateDroneFlowBindRoleReq req)
        {
            var response = new Response<bool>();

            List<DroneRelevance> list = new List<DroneRelevance>();

            //遍历角色
            foreach (var roleid in req.roleids)
            {
                DroneRelevance relModel = new DroneRelevance();
                relModel.Id = SnowFlakeSingle.Instance.getID().ToString();

                relModel.Description = "";
                relModel.Key = Define.FLOW_ROLE;
                relModel.Status = 0;
                relModel.OperateTime = DateTime.Now;
                relModel.OperatorId = "";
                relModel.FirstId = req.id;
                relModel.SecondId = roleid;
                relModel.ThirdId = "";
                relModel.ExtendInfo = "";

                list.Add(relModel);
            }

            using (var uwo = UnitWork.CreateContext())
            {
                //先删除绑定关系
                uwo.DroneRelevance.Delete(c => c.FirstId == req.id && c.Key == Define.FLOW_ROLE);
                //再添加绑定关系
                uwo.DroneRelevance.InsertRange(list);

                var flag = uwo.Commit();
                if (flag)
                {
                    response.Result = true;
                    response.Message = "绑定成功";
                }
                else
                {
                    response.Result = false;
                    response.Message = "绑定失败";
                }

                return response;
            }
        }

        /// <summary>
        /// 获取流程角色绑定的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<string> LoadDroneFlowRoleBindData(string id)
        {
            var list = client.Queryable<DroneRelevance>()
                .Where(c => c.FirstId == id && c.Key == Define.FLOW_ROLE)
                .Select(c => c.SecondId)
                .ToList();

            return list;
        }

        /// <summary>
        /// 查询待审核
        /// </summary>
        /// <returns></returns>
        public PageInfo<List<DroneCaseInfo>> LoadWaitToVerifyCaseList([FromQuery] QueryCaseInfoListReq req)
        {
            var currentUser = _auth.GetCurrentUser();
            var user = currentUser.User;
            var roles = currentUser.Roles.Select(c => c.Id.ToString()).ToList();


            //查询用户角色绑定的流程有哪些
            var flowList = client.Queryable<DroneRelevance>().Where(c => roles.Contains(c.SecondId) && c.Key == Define.FLOW_ROLE).Select(c => c.FirstId).ToList();

            //查询用户绑定的流程Sort
            var flowSorts = client.Queryable<DroneFlowInstance>().Where(c => flowList.Contains(c.Id) && c.status == 0 && c.instance_name == "CaseVerify").Select(c => c.sort).ToList();

            int total = 0;

            req.is_intact = 1;
            //根据组织机构过滤
            req.is_dealer = 1;
            //案件处理状态为1：待审核
            req.handle_status_id = 1;

            var list = QueryCaseInfoList((SqlSugarClient)client, req, user, 0)
                //通过用户角色权限过滤，根据角色绑定的流程过滤
                //.Where(c => flowSorts.Contains(c.verifystatus))
                //排序
                .OrderBy(c => c.deal_time, OrderByType.Desc)
                //分页查询
                .ToPageList(req.page, req.limit, ref total);

            var pageInfo = new PageInfo<List<DroneCaseInfo>>
            {
                Items = list,
                Total = total
            };

            return pageInfo;

        }

        /// <summary>
        /// 撤回案件
        /// </summary>
        public Response<bool> RecallCase(string id)
        {
            var response = new Response<bool>();
            DroneCaseInfo caseInfo = client.Queryable<DroneCaseInfo>().Where(c => c.Id == id).First();
            if (null == caseInfo)
            {
                throw new Exception("未获取到图斑信息！");
            }
            if (caseInfo.is_checked == 1 || !string.IsNullOrEmpty(caseInfo.verifyuser))
            {
                response.Message = "不可撤回！";
                response.Result = false;
                return response;
            }

            var handleStatusName = handleStatusList.Where(c => c.id == 0 && c.is_examine == 1).FirstOrDefault().name;

            // 撤回案件，设置处理状态为0
            var flag = client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo()
            {
                handle_status_id = 0,
                handle_status_name = handleStatusName
            }).Where(c => c.Id == id).ExecuteCommand();

            var user = _auth.GetCurrentUser().User;

            AddDroneCaseLog(new DroneCaseOperationLog { request_data = id, description = "RecallCase", caseid = caseInfo.Id, createuserid = user.Id.ToString(), createusername = user.Name });
            if (flag > 0)
            {
                response.Result = true;
                response.Message = "撤回成功!";
            }
            else
            {
                response.Result = false;
                response.Message = "撤回失败";
            }
            return response;
        }

        /// <summary>
        /// 撤回案件到待核查
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Response<bool> RecallCaseToUnCheck(string id)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            DroneCaseInfo caseInfo = client.Queryable<DroneCaseInfo>().Where(c => c.Id == id).First();
            if (null == caseInfo)
            {
                throw new Exception("未获取到图斑信息！");
            }

            if ((caseInfo.handle_status_id == 0 && caseInfo.is_examine == 1 && caseInfo.examiner_id == user.Id.ToString()) ||
                (caseInfo.handle_status_id == 1 && caseInfo.is_illegal == 2 && (caseInfo.is_checked == 0 || caseInfo.is_checked == null) && caseInfo.examiner_id == user.Id.ToString())
                )
            {
                var handleStatusName = handleStatusList.Where(c => c.id == 0 && c.is_examine == 0).FirstOrDefault().name;

                // 撤回案件，设置处理状态为0
                var flag = client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo()
                {
                    handle_status_id = 0,
                    handle_status_name = handleStatusName,
                    is_examine = 0,
                    is_checked = 0,
                }).Where(c => c.Id == id).ExecuteCommand();

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = id, description = "RecallCaseToUnCheck", caseid = caseInfo.Id, createuserid = user.Id.ToString(), createusername = user.Name });

                if (flag > 0)
                {
                    response.Result = true;
                    response.Message = "撤回成功！";
                }
                else
                {
                    response.Result = false;
                    response.Message = "撤回失败";
                }
                return response;
            }
            else
            {
                throw new Exception("不可撤回！");
            }
        }

        /// <summary>
        /// 撤回案件到待办理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Response<bool> RecallCaseToUnDeal(string id)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            DroneCaseInfo caseInfo = client.Queryable<DroneCaseInfo>().Where(c => c.Id == id).First();
            if (null == caseInfo)
            {
                throw new Exception("未获取到图斑信息！");
            }
            if (caseInfo.is_checked == 1 || caseInfo.deal_userid != user.Id.ToString())
            {
                throw new Exception("不可撤回！");
            }

            var handleStatusName = handleStatusList.Where(c => c.id == 0 && c.is_examine == 1).FirstOrDefault().name;

            // 撤回案件，设置处理状态为0
            var flag = client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo()
            {
                handle_status_id = 0,
                handle_status_name = handleStatusName,
            }).Where(c => c.Id == id).ExecuteCommand();

            AddDroneCaseLog(new DroneCaseOperationLog { request_data = id, description = "RecallCaseToUnDeal", caseid = caseInfo.Id, createuserid = user.Id.ToString(), createusername = user.Name });

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "撤回成功！";
            }
            else
            {
                response.Result = false;
                response.Message = "撤回失败";
            }
            return response;
        }

        /// <summary>
        /// 设置案件是否已查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Response<bool> SetCaseChecked(string id)
        {
            var response = new Response<bool>();

            var flag = client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo()
            {
                is_checked = 1
            }).Where(c => c.Id == id).ExecuteCommand();

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "设置查看成功";
            }
            else
            {
                response.Result = false;
                response.Message = "设置查看失败";
            }
            return response;
        }

        /// <summary>
        /// 案件退回
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response<bool> DrawbackCase(DrawBackCaseReq req)
        {
            var response = new Response<bool>();
            string id = req.id;
            string drawbackReason = req.drawbackReason;
            string drawback_type = req.drawback_type;

            DroneCaseInfo caseInfo = client.Queryable<DroneCaseInfo>().Where(c => c.Id == id).First();
            if (null == caseInfo)
            {
                throw new Exception("未获取到图斑信息！");
            }

            if (string.IsNullOrEmpty(caseInfo.deal_userid))
            {
                response.Message = "此图斑未办理，无需退回。";
                response.Result = false;
                return response;
            }

            // 发送通知给各办案人员/案件处理人
            Dictionary<string, string> receiverDic = new Dictionary<string, string>
                {
                    { caseInfo.deal_userid, caseInfo.deal_username }
                };

            var caseVerifyRecord = client.Queryable<DroneCaseVerifyrecord>().Where(c => c.caseid == id).ToList()
                .GroupBy(c => new { c.createuserid, c.createusername })
                .Select(c => new { c.Key.createuserid, c.Key.createusername }).ToList();
            foreach (var item in caseVerifyRecord)
            {
                var _count = receiverDic.Where(c => c.Key == item.createuserid).Count();
                if (_count > 0)
                    continue;
                receiverDic.Add(item.createuserid, item.createusername);
            }

            var currentUser = _auth.GetCurrentUser().User;
            DroneMessage msg = new DroneMessage()
            {
                Id = Guid.NewGuid().ToString(),
                createusername = currentUser.Name,
                createuser = currentUser.Id.ToString(),
                createtime = DateTime.Now,
                is_delete = 0,
                msg_title = "退回图斑，编号：" + caseInfo.case_no,
                msg_content = drawbackReason,
                msg_type = 1,
                case_no = caseInfo.case_no,
                caseid = caseInfo.Id,
            };
            List<DroneMessageRelevance> msgRelList = new List<DroneMessageRelevance>();
            foreach (var item in receiverDic.Keys)
            {
                msgRelList.Add(new DroneMessageRelevance()
                {
                    Id = Guid.NewGuid().ToString(),
                    createtime = DateTime.Now,
                    createuser = currentUser.Id.ToString(),
                    is_delete = 0,
                    is_read = 0,
                    messageid = msg.Id,
                    userid = item,
                    username = receiverDic[item]
                });
            }

            // 存储通知数据
            var transFlag = client.AsTenant().UseTran(() =>
            {
                int drawbackcount = caseInfo.drawbackcount == null || caseInfo.drawbackcount == 0 ? 1 : caseInfo.drawbackcount.Value + 1;
                // 退回案件，重置相应列的值
                client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo()
                {
                    handle_status_id = 0,                       //案件窗体
                    handle_status_name = "待核查",              //案件状态
                    is_examine = 0,                             //是否核查
                    verifyuserid = null,                        //审核人
                    verifyuser = null,                          //审核人
                    verifytime = null,                          //审核时间
                    verifystatus = null,                        //审核状态
                    verifystatusname = null,                    //审核状态
                    is_checked = 0,                             //是否查看
                    is_drawback = 1,                            //是否退回
                    drawbackcount = drawbackcount,
                    back_to_userid = caseInfo.deal_userid,      //退回给谁
                    back_to_username = caseInfo.deal_username,  //退回给谁
                    drawback_type = drawback_type,              //退回给谁
                    drawback_description = drawbackReason,      //退回给谁
                }).Where(c => c.Id == id).ExecuteCommand();

                client.Insertable(msg).ExecuteCommand();
                client.Insertable(msgRelList).ExecuteCommand();
            });

            var user = _auth.GetCurrentUser().User;
            AddDroneCaseLog(new DroneCaseOperationLog { request_data = id, description = "DrawbackCase", caseid = caseInfo.Id, createuserid = user.Id.ToString(), createusername = user.Name });

            if (transFlag.IsSuccess)
            {
                response.Result = true;
                response.Message = "退回成功";
            }
            else
            {
                response.Result = false;
                response.Message = "退回失败";
            }

            return response;

        }

        /// <summary>
        /// 管理员审核功能
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Response<bool> VerfiyCaseData(string id)
        {
            var response = new Response<bool>();

            var currentUser = _auth.GetCurrentUser();
            var user = currentUser.User;
            var roles = currentUser.Roles.Select(c => c.Id.ToString()).ToList();


            //查询用户角色绑定的流程有哪些
            var flowList = client.Queryable<DroneRelevance>().Where(c => roles.Contains(c.SecondId) && c.Key == Define.FLOW_ROLE).Select(c => c.FirstId).ToList();

            //查询用户绑定的流程Sort，用于判断用户是否有权限来审核
            var currentFlowList = client.Queryable<DroneFlowInstance>().Where(c => flowList.Contains(c.Id) && c.status == 0 && c.instance_name == "CaseVerify").Select(c => c.sort).ToList();

            //查询 流程Sort
            var flowSorts = client.Queryable<DroneFlowInstance>().Where(c => c.status == 0 && c.instance_name == "CaseVerify").OrderBy(c => c.sort, OrderByType.Asc).ToList();

            //最后一个节点的编号
            var lastNode = flowSorts.Last().sort;

            //查询案件
            var caseInfo = client.Queryable<Sugar_Drone_caseinfo>().Where(c => c.Id == id).First();

            if (caseInfo.verifystatus == lastNode)
                throw new Exception("已经审核完成，不能重复审核");

            if (caseInfo.handle_status_id != 1)
                throw new Exception("此数据不是待审核数据，无法进行审核");

            //是否最后一个节点
            bool isLastNode = false;

            //下一个节点的状态和名称
            int? nextNode = 0;
            string nextNodeName = string.Empty;

            //如果审核状态是空的，直接默认下个节点
            if (caseInfo.verifystatus == null)
            {
                caseInfo.verifystatus = flowSorts[0].sort;
                caseInfo.verifystatusname = flowSorts[0].name;

                nextNode = flowSorts[1].sort;
                nextNodeName = flowSorts[1].name;
            }
            else
            {
                //遍历寻找下个节点
                for (int i = 0; i < flowSorts.Count; i++)
                {
                    var item = flowSorts[i];
                    if (caseInfo.verifystatus.Value >= item.sort)
                        continue;

                    //下个节点的状态和名称
                    nextNode = item.sort;
                    nextNodeName = item.name;

                    //判断是否最后一个节点
                    if (i == (flowSorts.Count - 1))
                    {
                        isLastNode = true;
                    }

                    break;
                }
            }

            if (user.Account != Define.SYSTEM_USERNAME)
            {
                //判断是否有权限审核此数据
                var _count = currentFlowList.Where(c => c == caseInfo.verifystatus).Count();

                //没有权限审核此数据
                if (_count == 0)
                    throw new Exception("用户没有权限审核此数据");
            }

            //案件审核记录
            var record = new DroneCaseVerifyrecord()
            {
                Id = SnowFlakeSingle.instance.getID().ToString(),
                description = $"【{user.Name}】【{DateTime.Now}】审核了【{caseInfo.case_no}】案件，由【{caseInfo.verifystatusname}】到【{nextNodeName}】",
                status = caseInfo.verifystatus,
                statusname = caseInfo.verifystatusname,
                nextstatus = nextNode,
                nextstatusname = nextNodeName,
                createuserid = user.Id.ToString(),
                createusername = user.Name,
                createtime = DateTime.Now,
                caseid = caseInfo.Id
            };

            var transFlag = client.AsTenant().UseTran(() =>
            {
                var handleStatusName = handleStatusList.Where(c => c.id == 2).FirstOrDefault().name;

                //更新案件的审核状态
                client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo()
                {
                    //审核状态
                    verifystatus = nextNode,
                    verifystatusname = nextNodeName,
                    //审核时间
                    verifytime = DateTime.Now,
                    //审核人
                    verifyuserid = user.Id.ToString(),
                    verifyuser = user.Name
                })
                .SetColumnsIF(isLastNode, c => new DroneCaseInfo()
                {
                    //如果是最后一个节点的话，更新案件处理状态为已办结
                    handle_status_id = 2,
                    handle_status_name = handleStatusName
                })
                .Where(c => c.Id == id).ExecuteCommand();

                //添加审核记录
                client.Insertable(record).ExecuteCommand();
            });

            AddDroneCaseLog(new DroneCaseOperationLog { request_data = id, description = "VerfiyCaseData", caseid = caseInfo.Id, createuserid = user.Id.ToString(), createusername = user.Name });

            if (transFlag.IsSuccess)
            {
                response.Result = true;
                response.Message = "审核成功";
            }
            else
            {
                response.Result = false;
                response.Message = "审核失败";
            }
            return response;
        }

        /// <summary>
        /// 案件核销
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Response<bool> VerificatCase(string[] ids)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            var flag = client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo
            {
                is_verification = 1,
                verification_userid = user.Id.ToString(),
                verification_username = user.Name,
                verification_time = DateTime.Now
            }).Where(c => ids.Contains(c.Id)).ExecuteCommand();

            //添加操作记录
            AddDroneCaseLog(new DroneCaseOperationLog { request_data = JsonConvert.SerializeObject(ids), description = "VerificatCase", caseid = ids[0], createuserid = user.Id.ToString(), createusername = user.Name });

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "核销成功";
            }
            else
            {
                response.Result = false;
                response.Message = "核销异常";
            }
            return response;
        }

        /// <summary>
        /// 暂结案件
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Response<bool> TentativeCase(string id)
        {
            var response = new Response<bool>();
            var user = _auth.GetCurrentUser().User;

            //待审核步骤：暂结的案件流转到正常审核步骤
            int? handleStatusId = 1;
            string handleStatusName = handleStatusList.Where(c => c.id == handleStatusId).FirstOrDefault().name;

            var flag = client.Updateable<DroneCaseInfo>().SetColumns(c => new DroneCaseInfo
            {
                is_tentative_complete = 1,
                tentative_userid = user.Id.ToString(),
                tentative_username = user.Name,
                tentative_time = DateTime.Now,
                handle_status_id = handleStatusId,
                handle_status_name = handleStatusName
            }).Where(c => c.Id == id).ExecuteCommand();

            //添加操作记录
            AddDroneCaseLog(new DroneCaseOperationLog { request_data = id, description = "TentativeCase", caseid = id, createuserid = user.Id.ToString(), createusername = user.Name });

            if (flag > 0)
            {
                response.Result = true;
                response.Message = "核销成功";
            }
            else
            {
                response.Result = false;
                response.Message = "核销异常";
            }
            return response;
        }

        #endregion

        #region 统计
        /// <summary>
        /// APP案件数量查询
        /// </summary>
        /// <returns></returns>
        public CaseProcessStatData GetCaseProcessStatData(QueryCaseProcessStatDataReq req)
        {

            var current = _auth.GetCurrentUser();
            var user = current.User;
            var roles = current.Roles.Select(c => c.Id.ToString()).ToList();

            CaseProcessStatData data = new CaseProcessStatData
            {
                // 核查定性
                proofread_confirm_new = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 0, is_drawback = 0 }, user).Count(),
                proofread_confirm_drawback = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 0, is_drawback = 1 }, user).Count(),
                // 处置办理
                handle_demolish = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 1, measure_name = "拟拆除" }, user).Count(),
                handle_detain = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 1, measure_name = "查处" }, user).Count(),
                handle_perfection = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 1, measure_name = "拟完善手续" }, user).Count(),
                handle_legal = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 0 }, user).Count(),
                // 监督审核
                audit_demolish = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 1, measure_name = "拟拆除", is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_detain = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 1, measure_name = "查处", is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_perfection = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 1, measure_name = "拟完善手续", is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_legal = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 0, is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_fakeChange = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 2, is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                // 归档
                archive_demolish = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 1, measure_name = "拟拆除" }, user).Count(),
                archive_detain = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 1, measure_name = "查处" }, user).Count(),
                archive_perfection = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 1, measure_name = "拟完善手续" }, user).Count(),
                archive_legal = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 0 }, user).Count(),
                archive_fakeChange = QueryCaseInfoList((SqlSugarClient)client, new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 2 }, user).Count()
            };
            return data;

        }

        #endregion

        #region 案件专题

        /// <summary>
        /// 专题分页
        /// </summary>
        /// <param name="pageReq"></param>
        /// <returns></returns>
        public async Task<PageInfo<List<TopicResponse>>> LoadCaseTopic(PageReq pageReq)
        {
            RefAsync<int> total = 0;
            var list = await base.Repository.AsSugarClient().Queryable<SysDataItemDetail>()
                        .WhereIF(!string.IsNullOrEmpty(pageReq.key), a => a.ItemName.Contains(pageReq.key))
                        .Where(a => a.ItemCode == Define.DRONE_CASE_TOPIC)
                        .Select(a => new TopicResponse
                        {
                            TopicId = a.ItemDetailId,
                            TopicName = a.ItemName,
                            CaseTypes = SqlFunc.Subqueryable<DroneRelevance>()
                            .LeftJoin<SysDataItemDetail>((r, d) => r.SecondId == d.ItemDetailId)
                            .Where((r, d) => r.FirstId == a.ItemDetailId && r.Key == Define.TOPIC_CASETYPE)
                            .SelectStringJoin((r, d) => d.ItemName, ","),
                            Roles = SqlFunc.Subqueryable<DroneRelevance>()
                            .LeftJoin<SysRole>((r, role) => r.SecondId == role.Id.ToString())
                            .Where((r, role) => r.FirstId == a.ItemDetailId && r.Key == Define.TOPIC_ROLE)
                            .SelectStringJoin((r, role) => role.Name, ","),
                        })
                        .ToPageListAsync(pageReq.page, pageReq.limit, total);

            return new PageInfo<List<TopicResponse>>
            {
                Items = list,
                Total = total
            };
        }


        public async Task<Response<bool>> AddTopicCaseType(AlloDroneTopic alloDroneTopic)
        {
            var response = new Response<bool>();

            if (alloDroneTopic.RelevanceIds.Count > 0)
            {
                using (var uwo = base.UnitWork.CreateContext())
                {
                    await uwo.DroneRelevance.DeleteAsync(a => a.Key == Define.TOPIC_CASETYPE && a.FirstId == alloDroneTopic.TopicId);

                    var list = alloDroneTopic.RelevanceIds.Select(a => new DroneRelevance
                    {
                        Id = SnowFlakeSingle.Instance.getID().ToString(),
                        Description = "",
                        Key = Define.TOPIC_CASETYPE,
                        Status = 0,
                        OperateTime = DateTime.Now,
                        OperatorId = "",
                        FirstId = alloDroneTopic.TopicId,
                        SecondId = a
                    }).ToList();
                    await uwo.DroneRelevance.InsertRangeAsync(list);

                    var flag = uwo.Commit();
                    if (flag)
                    {
                        response.Result = true;
                        response.Message = "分配成功";
                    }
                    else
                    {
                        response.Result = false;
                        response.Message = "分配失败";
                    }
                }
            }
            else
            {
                response.Result = false;
                response.Message = "暂无图斑类型数据";
            }

            return response;
        }

        public async Task<Response<bool>> AddTopicRole(AlloDroneTopic alloDroneTopic)
        {
            var response = new Response<bool>();

            if (alloDroneTopic.RelevanceIds.Count > 0)
            {
                using (var uwo = base.UnitWork.CreateContext())
                {
                    await uwo.DroneRelevance.DeleteAsync(a => a.Key == Define.TOPIC_ROLE && a.FirstId == alloDroneTopic.TopicId);

                    var list = alloDroneTopic.RelevanceIds.Select(a => new DroneRelevance
                    {
                        Id = SnowFlakeSingle.Instance.getID().ToString(),
                        Description = "",
                        Key = Define.TOPIC_ROLE,
                        Status = 0,
                        OperateTime = DateTime.Now,
                        OperatorId = "",
                        FirstId = alloDroneTopic.TopicId,
                        SecondId = a
                    }).ToList();
                    await uwo.DroneRelevance.InsertRangeAsync(list);

                    var flag = uwo.Commit();
                    if (flag)
                    {
                        response.Result = true;
                        response.Message = "分配成功";
                    }
                    else
                    {
                        response.Result = false;
                        response.Message = "分配失败";
                    }
                }
            }
            else
            {
                response.Result = false;
                response.Message = "暂无角色数据";
            }

            return response;
        }

        /// <summary>
        /// 某专题对应已分配资源
        /// </summary>
        /// <param name="topicId"></param>
        /// <param name="code">TopicCaseType/TopicRole</param>
        /// <returns></returns>
        public async Task<List<string>> LoadTopicRelevance(string topicId, string code)
        {
            return await client.Queryable<DroneRelevance>().Where(a => a.Key == code && a.FirstId == topicId).Select(a => a.SecondId).ToListAsync();
        }
        #endregion
    }
}
