using Castle.Core.Internal;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using Infrastructure;
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using OpenAuth.App.Base;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.DroneCaseInfo.Request;
using OpenAuth.App.ServiceApp.Response;
using OpenAuth.App.SysDatabaseLink.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.App
{
    public partial class DroneCaseinfoApp
    {
        public string AsynchDroneCaseData([FromBody] AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //案件
                var model = req.model;

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var _count = db.Queryable<Sugar_Drone_caseinfo>().Where(c => c.Id == model.Id).Count();

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (_count > 0)
                    {
                        //已存在此数据，修改数据
                        db.Updateable(model).UpdateColumns(c => new
                        {
                            c.case_name,
                            c.case_description,
                            c.address,
                            c.lng,
                            c.lat,
                            c.typeid,
                            c.typename,
                            c.drone_no,
                            c.countyid,
                            c.countyname,
                            c.streetid,
                            c.streetname,
                            c.communityid,
                            c.communityname,
                            c.remark,
                            c.area,
                            c.pre_phase_time,
                            c.later_phase_time,
                            c.pre_phase_img,
                            c.later_phase_img,
                        }).ExecuteCommand();
                    }
                    else
                    {
                        model.handle_status_id = 0;
                        model.handle_status_name = "待核查";
                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        //新增修改图斑
                        //先删除，后新增
                        // db.Deleteable<DroneShpData>().Where(c => c.relid == model.Id).ExecuteCommand();
                        var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                        int _gid = int.Parse(_gidStr);

                        for (int i = 0; i < shps.Count; i++)
                        {
                            var _item = shps[i];
                            _item.gid = _gid + i;

                        }

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });

                //if (_count == 0)
                //{
                //    //发送websocket消息
                //    SendWebSocketMessage(type: "newcase", caseid: model.Id);

                //    var userAccounts = db.Queryable<Sugar_Relevance>()
                //        .LeftJoin<Sugar_Users>((r, u) => r.FirstId == u.Id && r.Key == "UserOrg" && r.SecondId == model.communityid)
                //        .Where((r, u) => !string.IsNullOrEmpty(u.Account))
                //        .Select((r, u) => u.Account)
                //        .ToList();

                //    userAccounts = userAccounts.Distinct().ToList();

                //    _pushService.SendPushNotification(model.case_no, model.case_description, userAccounts);

                //}

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public async Task<string> AsynchDroneCaseDataNew([FromBody] AddOrUpdateAsyncDroneCaseDataReq req)
        {
            string result = "同步成功";
            if (req.model.typename == "部级矿产卫片图斑" || req.model.typename == "省级矿产卫片图斑")
            {
                result = AsynchDroneCaseDataKC(req);
                if (result != "同步成功")
                {
                    return "同步失败";
                }
                var scode = _configuration.GetSection("AppSetting:DroneCaseInfoSatelliteSchemeCode").Value;
                var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                var schemeId = schemeInfo?.SchemeId;
                var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                if (flag.Result)
                {
                    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                }
                return result;
            }
            else if (req.model.typename == "加工" || req.model.typename == "开采")
            {
                result = AsynchDroneCaseDataCK(req);
                if (result != "同步成功")
                {
                    return "同步失败";
                }
                var scode = _configuration.GetSection("AppSetting:DroneCaseInfoMineralsSchemeCode").Value;
                var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                var schemeId = schemeInfo?.SchemeId;
                var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                if (flag.Result)
                {
                    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                }
                return result;
            }
            else if (req.model.typename == "重点问题1类")
            {
                result = AsynchDroneCaseDataZdwt1(req);
                //if (result != "同步成功")
                //{
                //    return "同步失败";
                //}
                //var scode = _configuration.GetSection("AppSetting:DroneCaseInfoZdwt1SchemeCode").Value;
                //var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                //var schemeId = schemeInfo?.SchemeId;
                //var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                //if (flag.Result)
                //{
                //    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                //}
                return result;
            }
            else if (req.model.typename == "重点问题2类")
            {
                result = AsynchDroneCaseDataZdwt2(req);
                //if (result != "同步成功")
                //{
                //    return "同步失败";
                //}
                //var scode = _configuration.GetSection("AppSetting:DroneCaseInfoZdwt2SchemeCode").Value;
                //var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                //var schemeId = schemeInfo?.SchemeId;
                //var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                //if (flag.Result)
                //{
                //    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                //}
                return result;
            }
            else if (req.model.typename == "巡察审计")
            {
                result = AsynchDroneCaseDataXcsj(req);
                if (result != "同步成功")
                {
                    return "同步失败";
                }
                var scode = _configuration.GetSection("AppSetting:DroneCaseInfoXcsjSchemeCode").Value;
                var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                var schemeId = schemeInfo?.SchemeId;
                var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                if (flag.Result)
                {
                    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                }
                return result;
            }
            else if (req.model.typename == "生态修复图斑")
            {
                result = AsynchDroneCaseDataSTXFOld(req);
                if (result != "同步成功")
                {
                    return "同步失败";
                }
                var scode = _configuration.GetSection("AppSetting:DroneCaseInfoSTXFSchemeCode").Value;
                var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                var schemeId = schemeInfo?.SchemeId;
                var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                if (flag.Result)
                {
                    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                }
                return result;
            }
            else if (req.model.typename == "生态保护红线")
            {
                result = AsynchDroneCaseDataSTHXOld(req);
                if (result != "同步成功")
                {
                    return "同步失败";
                }
                var scode = _configuration.GetSection("AppSetting:DroneCaseInfoSTHXSchemeCode").Value;
                var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                var schemeId = schemeInfo?.SchemeId;
                var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                if (flag.Result)
                {
                    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                }
                return result;
            }
            else
            {
                result = AsynchDroneCaseDataWfyd(req);
                if (result != "同步成功")
                {
                    return "同步失败";
                }
                var scode = _configuration.GetSection("AppSetting:SchemeCode").Value;
                var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
                var schemeId = schemeInfo?.SchemeId;
                var flag = await _wfProcessApp.SaveDraftWithUser(req.model.Id, scode, req.model.createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", null, null, null, 0, (req.model.case_description));
                if (flag.Result)
                {
                    var createFlag = await _wfProcessApp.CreateWithUser(req.model.Id, null, req.model.createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + req.model.Id + "\"}", (req.model.case_description));

                }
                return result;

            }
        }
        /// <summary>
        /// 同步违法用地
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataWfyd(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
            {
                throw new Exception("图斑来源不能为空");
            }
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //查询是否存在此数据
                var oldinfo = db.Queryable<DroneCaseInfoSingle>().Where(c => c.Id == req.model.Id).First();
                if (oldinfo != null)
                {
                    return "数据已存在";
                }
                //案件
                var model = req.model.MapTo<DroneCaseInfoSingle>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;
                #region 案件资料处理
                //图斑
                var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                int _gid = int.Parse(_gidStr);
                string geomid = "";
                for (int i = 0; i < shps.Count; i++)
                {
                    var _item = shps[i];
                    _item.gid = _gid + i;
                    geomid += _item.gid + ",";

                }
                model.geomid = geomid.Substring(0, geomid.Length - 1);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? "0" : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                model.nongyongdi_area = req.model.nongyongdi_area == null ? "0" : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                model.gengdi_area = req.model.gengdi_area == null ? "0" : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? "0" : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? "0" : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? "0" : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? "0" : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (oldinfo != null)
                    {
                        //已存在此数据，修改数据 
                        db.Updateable(model).UpdateColumns(c => new
                        {
                            c.case_name,
                            c.case_description,
                            c.address,
                            c.lng,
                            c.lat,
                            c.typeid,
                            c.typename,
                            c.drone_no,
                            c.countyid,
                            c.countyname,
                            c.streetid,
                            c.streetname,
                            c.communityid,
                            c.communityname,
                            c.remark,
                            c.area,
                            c.nongyongdi_area,
                            c.gengdi_area,
                            c.yongjiujibennongtian_area,
                            c.zhongdianquyu_area,
                            c.shengtaibaohuhongxian_area,
                            c.guotukongjianguihua_area,
                            //c.pre_phase_time,
                            //c.later_phase_time,
                            //c.pre_phase_img,
                            //c.later_phase_img,
                            c.geomid,
                            c.casepic
                        }).ExecuteCommand();
                    }
                    else
                    {
                        model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                        model.handle_status_id = 0;
                        model.handle_status_name = "待接收";
                        model.is_illegal = 1;//默认为违法
                        model.original_case_no = req.model.case_no;
                        var prefix = db.Queryable<SysDataItemDetail>()
                                              .Where(r => r.ItemDetailId == req.model.typeid).First()?.Prefix;
                        Random random = new Random();
                        string caseno;
                        bool isUnique;
                        //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        do
                        {
                            caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                            var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
                            isUnique = count == 0;

                        } while (!isUnique);

                        model.case_no = caseno;

                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        //新增修改图斑
                        //先删除，后新增
                        //db.Deleteable<DroneShpData>().Where(c => c.relid == model.Id).ExecuteCommand();
                        //var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                        //int _gid = int.Parse(_gidStr);

                        //for (int i = 0; i < shps.Count; i++)
                        //{
                        //    var _item = shps[i];
                        //    _item.gid = _gid + i;

                        //}

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataWfydNew(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoSingle>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据，根据orgcaseno判断，如果有，并且已经生成流程的，禁止修改
                var oldinfo = db.DroneCaseInfoSingle.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");
                }
                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == model.case_no && a.SubjectKey == "Subject_WFYD");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();


                if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                {
                    model.nongyongdi_area = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var yongjiujibennongtian_area))
                {
                    model.yongjiujibennongtian_area = string.IsNullOrEmpty(yongjiujibennongtian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(yongjiujibennongtian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianquyu_area", out var zhongdianquyu_area))
                {
                    model.zhongdianquyu_area = string.IsNullOrEmpty(zhongdianquyu_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(zhongdianquyu_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var shengtaibaohuhongxian_area))
                {
                    model.shengtaibaohuhongxian_area = string.IsNullOrEmpty(shengtaibaohuhongxian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(shengtaibaohuhongxian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("guotukongjianguihua_area", out var guotukongjianguihua_area))
                {
                    model.guotukongjianguihua_area = string.IsNullOrEmpty(guotukongjianguihua_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(guotukongjianguihua_area.ToString())).ToString();
                }

                //model.synchronoustime = DateTime.Now;
                #endregion
                model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                model.is_illegal = 1;//默认为违法
                model.original_case_no = req.model.case_no;
                //var prefix = db.SysDataItemDetail.AsQueryable().Where(r => r.ItemDetailId == req.model.typeid).First()?.Prefix ?? "FN";
                //Random random = new Random();
                //string caseno;
                //bool isUnique;
                //do
                //{
                //    caseno = "FN" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                //    var count = db.DroneCaseInfoSingle.AsQueryable().Where(c => c.case_no == caseno).Count();
                //    isUnique = count == 0;

                //} while (!isUnique);
                if (oldinfo != null)//如果是复提的案件，图斑不删除，只新增
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    db.DroneCaseInfoSingle.Update(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_WFYD");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    model.case_no = "";
                    //model.case_no = caseno;
                    //新增数据
                    db.DroneCaseInfoSingle.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => { r.caseid = model.Id; });
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {
                    return model.Id;
                }
                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 同步矿产
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataKC(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoSatellite>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.Queryable<DroneCaseInfoSatellite>().Where(c => c.Id == model.Id).First();

                if (oldinfo != null)
                {
                    return "数据已存在";
                    //if (!string.IsNullOrEmpty(oldinfo.geomid))
                    //{
                    //    var geomids = new List<string>(oldinfo.geomid.Split(",")).ConvertAll(r => long.Parse(r));
                    //    db.Deleteable<DroneShpData>().Where(c => geomids.Contains(c.gid)).ExecuteCommand();
                    //}

                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                int _gid = int.Parse(_gidStr);
                string geomid = "";
                for (int i = 0; i < shps.Count; i++)
                {
                    var _item = shps[i];
                    _item.gid = _gid + i;
                    geomid += _item.gid + ",";

                }
                model.geomid = geomid.Substring(0, geomid.Length - 1);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (oldinfo != null)
                    {
                        //已存在此数据，修改数据 
                        db.Updateable(model).UpdateColumns(c => new
                        {
                            c.case_name,
                            c.case_description,
                            c.address,
                            c.lng,
                            c.lat,
                            c.typeid,
                            c.typename,
                            c.drone_no,
                            c.countyid,
                            c.countyname,
                            c.streetid,
                            c.streetname,
                            c.communityid,
                            c.communityname,
                            c.remark,
                            c.area,
                            c.nongyongdi_area,
                            c.gengdi_area,
                            c.yongjiujibennongtian_area,
                            c.zhongdianquyu_area,
                            c.shengtaibaohuhongxian_area,
                            c.guotukongjianguihua_area,
                            //c.pre_phase_time,
                            //c.later_phase_time,
                            //c.pre_phase_img,
                            //c.later_phase_img,
                            c.geomid,
                            c.casepic
                        }).ExecuteCommand();
                    }
                    else
                    {
                        model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                        model.handle_status_id = 0;
                        model.handle_status_name = "待接收";
                        model.is_illegal = 1;//默认为违法
                        model.original_case_no = req.model.case_no;
                        var prefix = db.Queryable<SysDataItemDetail>()
                                              .Where(r => r.ItemName == req.model.typename).First()?.Prefix;
                        Random random = new Random();
                        string caseno;
                        bool isUnique;
                        //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        do
                        {
                            caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                            var count = db.Queryable<DroneCaseInfoSatellite>().Where(c => c.case_no == caseno).Count();
                            isUnique = count == 0;

                        } while (!isUnique);

                        model.case_no = caseno;

                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        //新增修改图斑
                        //先删除，后新增
                        //db.Deleteable<DroneShpData>().Where(c => c.relid == model.Id).ExecuteCommand();
                        //var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                        //int _gid = int.Parse(_gidStr);

                        //for (int i = 0; i < shps.Count; i++)
                        //{
                        //    var _item = shps[i];
                        //    _item.gid = _gid + i;

                        //}

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });
                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataKCNew(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoSatellite>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoSatellite.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                model.is_illegal = 1;//默认为违法
                model.original_case_no = req.model.case_no;
                //var prefix = db.SysDataItemDetail.AsQueryable().Where(r => r.ItemName == req.model.typename).First()?.Prefix ?? "KC";
                Random random = new Random();
                string caseno;
                bool isUnique;
                do
                {
                    caseno = "FN" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoSatellite.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);


                if (oldinfo != null)//如果是复提的案件，图斑不删除，只新增
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    db.DroneCaseInfoSatellite.Update(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }
                else
                {
                    model.case_no = caseno;
                    //新增数据
                    db.DroneCaseInfoSatellite.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataCK(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoMinerals>();
                model.centerlng_base = req.model.lng.ToString();
                model.centerlat_base = req.model.lat.ToString();
                //model.weifaarea_base = req.model.area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                model.weifaarea_base = req.model.area;
                model.gengdi_area = req.model.gengdi_area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                model.jbntarea_base = req.model.yongjiujibennongtian_area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                model.qianshixiang_base = req.model.pre_phase_img == null ? "" : req.model.pre_phase_img.ToString();
                model.houshixiang_base = req.model.later_phase_img == null ? "" : req.model.later_phase_img.ToString();
                model.stbhhxarea_base = req.model.shengtaibaohuhongxian_area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                model.original_case_no = req.model.case_no;
                var mininfo = Newtonsoft.Json.JsonConvert.DeserializeObject<MineralsInfo>(req.model.mineralsinfo);
                model.kaicaizhuti_kcfill = mininfo.kaicaizhuti_kcfill;
                model.syear_base = mininfo.syear_base;
                model.danweiname_jgzhg = mininfo.danweiname_jgzhg;
                //model.zhongdianflag_base = mininfo.zhongdianflag_base;
                //model.ziranbaohuflag_base = mininfo.ziranbaohuflag_base;
                //model.ziranbaohuname_base = mininfo.ziranbaohuname_base;
                //model.weifakaicaiarea_base = mininfo.weifakaicaiarea_base == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(mininfo.weifakaicaiarea_base)).ToString();
                //model.cskfbjarea_base = mininfo.cskfbjarea_base == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(mininfo.cskfbjarea_base)).ToString();
                //model.tudiliyongflag_base = mininfo.tudiliyongflag_base;
                //model.shejichanneng_base = mininfo.shejichanneng_base;
                //model.weifazhandiarea_base = mininfo.weifazhandiarea_base == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(mininfo.weifazhandiarea_base)).ToString();
                //model.chulishixian_base = mininfo.chulishixian_base;
                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.Queryable<DroneCaseInfoMinerals>().Where(c => c.Id == model.Id).First();

                if (oldinfo != null)
                {
                    return "数据已存在";

                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                int _gid = int.Parse(_gidStr);
                string geomid = "";
                for (int i = 0; i < shps.Count; i++)
                {
                    var _item = shps[i];
                    _item.gid = _gid + i;
                    geomid += _item.gid + ",";

                }
                model.geomid = string.IsNullOrEmpty(geomid) ? "" : geomid.Substring(0, geomid.Length - 1);
                model.xiafatime_base = DateTime.Now;
                //图片
                model.tubanpic_base = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                ////平方米转化
                //model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                //model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (oldinfo != null)
                    {
                    }
                    else
                    {
                        //model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                        model.handle_status_id = 1;
                        //model.handle_status_name = "待接收";
                        //model.is_illegal = 1;//默认为违法 
                        //model.original_case_no = req.model.case_no;
                        var prefix = db.Queryable<SysDataItemDetail>()
                                              .Where(r => r.ItemName == req.model.typename).First()?.Prefix;
                        Random random = new Random();
                        string caseno;
                        bool isUnique;
                        //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        do
                        {
                            caseno = (string.IsNullOrEmpty(prefix) ? "KC" : prefix) + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                            var count = db.Queryable<DroneCaseInfoMinerals>().Where(c => c.case_no == caseno).Count();
                            isUnique = count == 0;

                        } while (!isUnique);

                        model.case_no = caseno;

                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        //新增修改图斑
                        //先删除，后新增
                        //db.Deleteable<DroneShpData>().Where(c => c.relid == model.Id).ExecuteCommand();
                        //var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                        //int _gid = int.Parse(_gidStr);

                        //for (int i = 0; i < shps.Count; i++)
                        //{
                        //    var _item = shps[i];
                        //    _item.gid = _gid + i;

                        //}

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });
                //需要放开
                //AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid =  model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 采矿
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataCKNew(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoMinerals>();
                model.centerlng_base = req.model.lng.ToString();
                model.centerlat_base = req.model.lat.ToString();
                model.weifaarea_base = req.model.area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                // model.gengdi_area = req.model.gengdi_area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                // model.jbntarea_base = req.model.yongjiujibennongtian_area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                model.qianshixiang_base = req.model.pre_phase_img == null ? "" : req.model.pre_phase_img.ToString();
                model.houshixiang_base = req.model.later_phase_img == null ? "" : req.model.later_phase_img.ToString();
                //model.stbhhxarea_base = req.model.shengtaibaohuhongxian_area == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                model.original_case_no = req.model.case_no;
                model.typename = null;
                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    if (string.IsNullOrEmpty(gengdi_area?.ToString()))
                    {
                        model.gengdi_area = "0.00";
                    }
                    else
                    {
                        model.gengdi_area = ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                    }
                    // model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString()) == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.extra_info["gengdi_area"].ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var jbntarea_base))
                {
                    if (string.IsNullOrEmpty(jbntarea_base?.ToString()))
                    {
                        model.jbntarea_base = "0.00";
                    }
                    else
                    {
                        model.jbntarea_base = ConvertSquareMetersToMu(double.Parse(jbntarea_base.ToString())).ToString();
                    }
                }
                //if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                //{
                //    model.jbntarea_base = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                //        ? "0.00"
                //        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                //}
                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var stbhhxarea_base))
                {
                    if (string.IsNullOrEmpty(stbhhxarea_base?.ToString()))
                    {
                        model.stbhhxarea_base = "0.00";
                    }
                    else
                    {
                        model.stbhhxarea_base = ConvertSquareMetersToMu(double.Parse(stbhhxarea_base.ToString())).ToString();
                    }
                    //model.stbhhxarea_base = stbhhxarea_base == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.extra_info["stbhhxarea_base"].ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("kaicaizhuti_kcfill", out var kcfill))
                {
                    model.kaicaizhuti_kcfill = kcfill == null ? null : kcfill.ToString();
                }
                if (req.model.extra_info.TryGetValue("syear_base", out var syearBase))
                {
                    model.syear_base = syearBase == null ? DateTime.Now.Year.ToString() : syearBase.ToString();
                }

                if (req.model.extra_info.TryGetValue("danweiname_jgzhg", out var danweiName))
                {
                    model.danweiname_jgzhg = danweiName == null ? null : danweiName.ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianflag_base", out var zhongdianFlag))
                {
                    model.zhongdianflag_base = zhongdianFlag == null ? null : zhongdianFlag.ToString();
                }

                if (req.model.extra_info.TryGetValue("ziranbaohuflag_base", out var ziranbaohuFlag))
                {
                    model.ziranbaohuflag_base = ziranbaohuFlag == null ? null : ziranbaohuFlag.ToString();
                }

                if (req.model.extra_info.TryGetValue("ziranbaohuname_base", out var ziranbaohuName))
                {
                    model.ziranbaohuname_base = ziranbaohuName == null ? null : ziranbaohuName.ToString();
                }

                if (req.model.extra_info.TryGetValue("weifakaicaiarea_base", out var weifaKaicaiarea))
                {
                    if (string.IsNullOrEmpty(weifaKaicaiarea?.ToString()))
                    {
                        model.weifakaicaiarea_base = "0.00";
                    }
                    else
                    {
                        model.weifakaicaiarea_base = ConvertSquareMetersToMu(double.Parse(weifaKaicaiarea.ToString())).ToString();
                    }
                    //model.weifakaicaiarea_base = weifaKaicaiarea == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.extra_info["weifakaicaiarea_base"].ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("cskfbjarea_base", out var cskfbjArea))
                {
                    if (string.IsNullOrEmpty(cskfbjArea?.ToString()))
                    {
                        model.cskfbjarea_base = "0.00";
                    }
                    else
                    {
                        model.cskfbjarea_base = ConvertSquareMetersToMu(double.Parse(cskfbjArea.ToString())).ToString();
                    }
                    //model.cskfbjarea_base = cskfbjArea == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.extra_info["cskfbjarea_base"].ToString())).ToString(); ;
                }

                if (req.model.extra_info.TryGetValue("tudiliyongflag_base", out var tudiliyongFlag))
                {
                    model.tudiliyongflag_base = tudiliyongFlag == null ? null : tudiliyongFlag.ToString();
                }

                if (req.model.extra_info.TryGetValue("shejichanneng_base", out var shejiChanneng))
                {
                    model.shejichanneng_base = shejiChanneng == null ? null : decimal.Parse(req.model.extra_info["shejichanneng_base"].ToString());
                }

                if (req.model.extra_info.TryGetValue("weifazhandiarea_base", out var weifazhandiArea))
                {
                    if (string.IsNullOrEmpty(weifazhandiArea?.ToString()))
                    {
                        model.weifazhandiarea_base = "0.00";
                    }
                    else
                    {
                        model.weifazhandiarea_base = ConvertSquareMetersToMu(double.Parse(weifazhandiArea.ToString())).ToString();
                    }
                    //model.weifazhandiarea_base = weifazhandiArea == null ? "0.00" : ConvertSquareMetersToMu(double.Parse(req.model.extra_info["weifazhandiarea_base"].ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("chulishixian_base", out var chulishiXian))
                {
                    model.chulishixian_base = chulishiXian == null ? null : DateTime.Parse(req.model.extra_info["chulishixian_base"].ToString());
                }
                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoMinerals.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");

                }
                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == model.case_no && a.SubjectKey == "Subject_FFCK");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }

                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                model.geomid = ProcessShps(shps);
                model.xiafatime_base = DateTime.Now;
                //图片
                model.tubanpic_base = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                ////平方米转化
                //model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                //model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                //model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                model.handle_status_id = 1;
                //model.handle_status_name = "待接收";
                //model.is_illegal = 1;//默认为违法
                //model.original_case_no = req.model.case_no;
                // var prefix = db.SysDataItemDetail.AsQueryable().Where(r => r.ItemName == req.model.typename).First()?.Prefix;
                Random random = new Random();
                string caseno;
                bool isUnique;
                do
                {
                    caseno = "KC" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoMinerals.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);

                model.case_no = caseno;
                if (oldinfo != null)
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    db.DroneCaseInfoMinerals.Update(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_FFCK");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    //新增数据
                    db.DroneCaseInfoMinerals.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_user, createusername = model.identification_user });
                if (db.Commit())
                {
                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 重点问题1
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataZdwt1(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoZdwt1>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.Queryable<DroneCaseInfoZdwt1>().Where(c => c.Id == model.Id).First();
                if (oldinfo != null)
                {
                    return "数据已存在";

                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                int _gid = int.Parse(_gidStr);
                string geomid = "";
                for (int i = 0; i < shps.Count; i++)
                {
                    var _item = shps[i];
                    _item.gid = _gid + i;
                    geomid += _item.gid + ",";

                }
                model.geomid = geomid.Substring(0, geomid.Length - 1);
                model.original_case_no = req.model.case_no;
                model.synchronoustime = null;
                //图片
                //model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                ////平方米转化
                //model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                //model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (oldinfo != null)
                    {
                    }
                    else
                    {
                        model.handle_status_id = 0;
                        model.handle_status_name = "待接收";
                        //var prefix = db.Queryable<SysDataItemDetail>()
                        //                      .Where(r => r.ItemDetailId == req.model.typeid).First()?.Prefix;
                        Random random = new Random();
                        string caseno;
                        bool isUnique;
                        //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        do
                        {
                            caseno = "WJ" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                            var count = db.Queryable<DroneCaseInfoZdwt1>().Where(c => c.case_no == caseno).Count();
                            isUnique = count == 0;

                        } while (!isUnique);

                        model.case_no = caseno;

                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataZdwt1New(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoZdwt1>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoZdwt1.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");
                }
                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == model.case_no && a.SubjectKey == "Subject_ZDWT1");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                model.original_case_no = req.model.case_no;
                model.typename = "重点问题Ⅰ类";
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();

                if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                {
                    model.nongyongdi_area = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var yongjiujibennongtian_area))
                {
                    model.yongjiujibennongtian_area = string.IsNullOrEmpty(yongjiujibennongtian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(yongjiujibennongtian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianquyu_area", out var zhongdianquyu_area))
                {
                    model.zhongdianquyu_area = string.IsNullOrEmpty(zhongdianquyu_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(zhongdianquyu_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var shengtaibaohuhongxian_area))
                {
                    model.shengtaibaohuhongxian_area = string.IsNullOrEmpty(shengtaibaohuhongxian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(shengtaibaohuhongxian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("guotukongjianguihua_area", out var guotukongjianguihua_area))
                {
                    model.guotukongjianguihua_area = string.IsNullOrEmpty(guotukongjianguihua_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(guotukongjianguihua_area.ToString())).ToString();
                }


                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion


                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                Random random = new Random();
                string caseno;
                bool isUnique;
                do
                {
                    caseno = "WJ" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoZdwt1.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);
                model.case_no = caseno;
                if (oldinfo != null)
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    //新增数据
                    db.DroneCaseInfoZdwt1.Update(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_ZDWT1");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    //新增数据
                    db.DroneCaseInfoZdwt1.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }


                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 重点问题2
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataZdwt2(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoZdwt2>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.Queryable<DroneCaseInfoZdwt2>().Where(c => c.Id == model.Id).First();
                if (oldinfo != null)
                {
                    return "数据已存在";

                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                int _gid = int.Parse(_gidStr);
                string geomid = "";
                for (int i = 0; i < shps.Count; i++)
                {
                    var _item = shps[i];
                    _item.gid = _gid + i;
                    geomid += _item.gid + ",";

                }
                model.geomid = geomid.Substring(0, geomid.Length - 1);
                model.original_case_no = req.model.case_no;
                //图片
                //model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                ////平方米转化
                //model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (oldinfo != null)
                    {
                    }
                    else
                    {
                        model.handle_status_id = 0;
                        model.handle_status_name = "待接收";
                        Random random = new Random();
                        string caseno;
                        bool isUnique;
                        //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        do
                        {
                            caseno = "WJ" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                            var count = db.Queryable<DroneCaseInfoZdwt1>().Where(c => c.case_no == caseno).Count();
                            isUnique = count == 0;

                        } while (!isUnique);

                        model.case_no = caseno;

                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataZdwt2New(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoZdwt2>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoZdwt2.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");
                }
                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == model.case_no && a.SubjectKey == "Subject_ZDWT2");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                model.original_case_no = req.model.case_no;
                model.typename = "重点问题Ⅱ类";
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();


                if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                {
                    model.nongyongdi_area = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var yongjiujibennongtian_area))
                {
                    model.yongjiujibennongtian_area = string.IsNullOrEmpty(yongjiujibennongtian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(yongjiujibennongtian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianquyu_area", out var zhongdianquyu_area))
                {
                    model.zhongdianquyu_area = string.IsNullOrEmpty(zhongdianquyu_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(zhongdianquyu_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var shengtaibaohuhongxian_area))
                {
                    model.shengtaibaohuhongxian_area = string.IsNullOrEmpty(shengtaibaohuhongxian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(shengtaibaohuhongxian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("guotukongjianguihua_area", out var guotukongjianguihua_area))
                {
                    model.guotukongjianguihua_area = string.IsNullOrEmpty(guotukongjianguihua_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(guotukongjianguihua_area.ToString())).ToString();
                }



                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                Random random = new Random();
                string caseno;
                bool isUnique;
                //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                do
                {
                    caseno = "WJ" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoZdwt2.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);

                model.case_no = caseno;
                if (oldinfo != null)
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    //新增数据
                    db.DroneCaseInfoZdwt2.Update(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_ZDWT2");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    //新增数据
                    db.DroneCaseInfoZdwt2.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }


                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 巡察审计
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataXcsj(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoXcsj>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.Queryable<DroneCaseInfoXcsj>().Where(c => c.Id == model.Id).First();
                if (oldinfo != null)
                {
                    return "数据已存在";
                    //if (!string.IsNullOrEmpty(oldinfo.geomid))
                    //{
                    //    var geomids = new List<string>(oldinfo.geomid.Split(",")).ConvertAll(r => long.Parse(r));
                    //    db.Deleteable<DroneShpData>().Where(c => geomids.Contains(c.gid)).ExecuteCommand();
                    //}

                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                int _gid = int.Parse(_gidStr);
                string geomid = "";
                for (int i = 0; i < shps.Count; i++)
                {
                    var _item = shps[i];
                    _item.gid = _gid + i;
                    geomid += _item.gid + ",";

                }
                model.geomid = geomid.Substring(0, geomid.Length - 1);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (oldinfo != null)
                    {

                    }
                    else
                    {
                        model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                        model.handle_status_id = 0;
                        model.handle_status_name = "待接收";

                        model.original_case_no = req.model.case_no;
                        model.case_no = req.model.case_no;
                        //var prefix = db.Queryable<SysDataItemDetail>()
                        //                      .Where(r => r.ItemDetailId == req.model.typeid).First()?.Prefix;
                        //Random random = new Random();
                        //string caseno;
                        //bool isUnique;
                        ////string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        //do
                        //{
                        //    caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        //    var count = db.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == caseno).Count();
                        //    isUnique = count == 0;

                        //} while (!isUnique);

                        //model.case_no = caseno;

                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        //新增修改图斑
                        //先删除，后新增
                        //db.Deleteable<DroneShpData>().Where(c => c.relid == model.Id).ExecuteCommand();
                        //var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                        //int _gid = int.Parse(_gidStr);

                        //for (int i = 0; i < shps.Count; i++)
                        //{
                        //    var _item = shps[i];
                        //    _item.gid = _gid + i;

                        //}

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataXcsjNew(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoXcsj>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoXcsj.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");
                }
                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == model.case_no && a.SubjectKey == "Subject_XCSJ");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                model.typename = "巡察审计";
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();

                if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                {
                    model.nongyongdi_area = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var yongjiujibennongtian_area))
                {
                    model.yongjiujibennongtian_area = string.IsNullOrEmpty(yongjiujibennongtian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(yongjiujibennongtian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianquyu_area", out var zhongdianquyu_area))
                {
                    model.zhongdianquyu_area = string.IsNullOrEmpty(zhongdianquyu_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(zhongdianquyu_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var shengtaibaohuhongxian_area))
                {
                    model.shengtaibaohuhongxian_area = string.IsNullOrEmpty(shengtaibaohuhongxian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(shengtaibaohuhongxian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("guotukongjianguihua_area", out var guotukongjianguihua_area))
                {
                    model.guotukongjianguihua_area = string.IsNullOrEmpty(guotukongjianguihua_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(guotukongjianguihua_area.ToString())).ToString();
                }

                model.synchronoustime = DateTime.Now;
                //model.tubanlaiyuan = string.IsNullOrEmpty(req.model.tubanlaiyuan) ? "全域巡查" : req.model.tubanlaiyuan;
                #endregion


                model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                model.handle_status_id = 0;
                model.handle_status_name = "待接收";

                model.original_case_no = req.model.case_no;
                //model.case_no = req.model.case_no;
                //var prefix = db.Queryable<SysDataItemDetail>()
                //                      .Where(r => r.ItemDetailId == req.model.typeid).First()?.Prefix;
                Random random = new Random();
                string caseno;
                bool isUnique;
                //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                do
                {
                    caseno = req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoXcsj.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);
                model.case_no = caseno;
                if (oldinfo != null)
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    //新增数据
                    db.DroneCaseInfoXcsj.Update(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_XCSJ");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    //新增数据
                    db.DroneCaseInfoXcsj.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataSTXFOld(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoSTXF>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;


                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                model.original_case_no = req.model.case_no;
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area;


                model.synchronoustime = DateTime.Now;
                #endregion

                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                Random random = new Random();
                string caseno;
                bool isUnique;
                do
                {
                    caseno = req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoSTXF.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);

                model.case_no = caseno;
                //新增数据
                db.DroneCaseInfoSTXF.Insert(model);
                if (!string.IsNullOrEmpty(model.Id))
                {
                    shps.ForEach(r => r.relid = model.Id);
                    db.DroneShpData.InsertRange(shps);
                    //新增修改图片
                    files.ForEach(r => { r.relid = model.Id; });
                    db.DroneFiles.InsertRange(files);
                }

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 同步非粮化
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataFLH([FromBody] AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoFLH>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.Queryable<DroneCaseInfoFLH>().Where(c => c.Id == model.Id).First();

                if (oldinfo != null)
                {
                    if (!string.IsNullOrEmpty(oldinfo.geomid))
                    {
                        var geomids = new List<string>(oldinfo.geomid.Split(",")).ConvertAll(r => long.Parse(r));
                        db.Deleteable<DroneShpData>().Where(c => geomids.Contains(c.gid)).ExecuteCommand();
                    }

                }

                #region 案件资料处理
                //图斑
                var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                int _gid = int.Parse(_gidStr);
                string geomid = "";
                for (int i = 0; i < shps.Count; i++)
                {
                    var _item = shps[i];
                    _item.gid = _gid + i;
                    geomid += _item.gid + ",";

                }
                model.geomid = geomid.Substring(0, geomid.Length - 1);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                model.tubanlaiyuan = "全域巡查";

                #endregion

                //使用事务提交数据
                var transFlag = db.UseTran(() =>
                {
                    if (oldinfo != null)
                    {
                        //已存在此数据，修改数据 
                        db.Updateable(model).UpdateColumns(c => new
                        {
                            c.case_name,
                            c.case_description,
                            c.address,
                            c.lng,
                            c.lat,
                            c.typeid,
                            c.typename,
                            c.drone_no,
                            c.countyid,
                            c.countyname,
                            c.streetid,
                            c.streetname,
                            c.communityid,
                            c.communityname,
                            c.remark,
                            c.area,
                            c.nongyongdi_area,
                            c.gengdi_area,
                            c.yongjiujibennongtian_area,
                            c.zhongdianquyu_area,
                            c.shengtaibaohuhongxian_area,
                            c.guotukongjianguihua_area,
                            //c.pre_phase_time,
                            //c.later_phase_time,
                            //c.pre_phase_img,
                            //c.later_phase_img,
                            c.geomid,
                            c.casepic
                        }).ExecuteCommand();
                    }
                    else
                    {
                        model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                        model.handle_status_id = 0;
                        model.handle_status_name = "待接收";
                        model.is_illegal = 1;//默认为违法
                        model.original_case_no = req.model.case_no;
                        var prefix = db.Queryable<SysDataItemDetail>()
                                              .Where(r => r.ItemDetailId == req.model.typeid).First()?.Prefix;
                        Random random = new Random();
                        string caseno;
                        bool isUnique;
                        //string caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                        do
                        {
                            caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                            var count = db.Queryable<DroneCaseInfoFLH>().Where(c => c.case_no == caseno).Count();
                            isUnique = count == 0;

                        } while (!isUnique);

                        model.case_no = caseno;

                        //新增数据
                        db.Insertable(model).ExecuteCommand();
                    }

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        //新增修改图斑
                        //先删除，后新增
                        //db.Deleteable<DroneShpData>().Where(c => c.relid == model.Id).ExecuteCommand();
                        //var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
                        //int _gid = int.Parse(_gidStr);

                        //for (int i = 0; i < shps.Count; i++)
                        //{
                        //    var _item = shps[i];
                        //    _item.gid = _gid + i;

                        //}

                        db.Insertable(shps).ExecuteCommand();

                        //新增修改图片
                        //先删除，后新增
                        db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                        db.Insertable(files).ExecuteCommand();


                        //关联案件
                        db.Deleteable<DroneCaseInfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                        db.Insertable(relations).ExecuteCommand();

                        //案件标签
                        db.Deleteable<DroneCaseInfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                        db.Insertable(tags).ExecuteCommand();
                    }
                });
                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (transFlag.IsSuccess)
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        public string AsynchDroneCaseDataFLHNew([FromBody] AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoFLH>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoFLH.AsQueryable().Where(c => c.original_case_no == model.case_no).First();

                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");

                }

                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == model.case_no && a.SubjectKey == "Subject_GDFLH");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();
                //model.nongyongdi_area = req.model.nongyongdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.nongyongdi_area)).ToString();
                //model.gengdi_area = req.model.gengdi_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.gengdi_area)).ToString();
                //model.yongjiujibennongtian_area = req.model.yongjiujibennongtian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.yongjiujibennongtian_area)).ToString();
                //model.zhongdianquyu_area = req.model.zhongdianquyu_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.zhongdianquyu_area)).ToString();
                //model.shengtaibaohuhongxian_area = req.model.shengtaibaohuhongxian_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.shengtaibaohuhongxian_area)).ToString();
                //model.guotukongjianguihua_area = req.model.guotukongjianguihua_area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.guotukongjianguihua_area)).ToString();
                if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                {
                    model.nongyongdi_area = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var yongjiujibennongtian_area))
                {
                    model.yongjiujibennongtian_area = string.IsNullOrEmpty(yongjiujibennongtian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(yongjiujibennongtian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianquyu_area", out var zhongdianquyu_area))
                {
                    model.zhongdianquyu_area = string.IsNullOrEmpty(zhongdianquyu_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(zhongdianquyu_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var shengtaibaohuhongxian_area))
                {
                    model.shengtaibaohuhongxian_area = string.IsNullOrEmpty(shengtaibaohuhongxian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(shengtaibaohuhongxian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("guotukongjianguihua_area", out var guotukongjianguihua_area))
                {
                    model.guotukongjianguihua_area = string.IsNullOrEmpty(guotukongjianguihua_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(guotukongjianguihua_area.ToString())).ToString();
                }
                #endregion
                model.address = model.countyname + " " + model.streetname + " " + model.communityname;
                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                model.is_illegal = 1;//默认为违法
                model.original_case_no = req.model.case_no;
                model.synchronoustime = DateTime.Now;
                //var prefix = db.SysDataItemDetail.AsQueryable().Where(r => r.ItemDetailId == req.model.typeid).First()?.Prefix ?? "FN";
                //Random random = new Random();
                //string caseno;
                //bool isUnique;
                //do
                //{
                //    caseno = prefix + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                //    var count = db.DroneCaseInfoFLH.AsQueryable().Where(c => c.case_no == caseno).Count();
                //    isUnique = count == 0;

                //} while (!isUnique);
                //model.case_no = caseno;

                if (oldinfo != null)
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    //新增数据
                    db.DroneCaseInfoFLH.Update(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_GDFLH");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    model.case_no = "";
                    //新增数据
                    db.DroneCaseInfoFLH.Insert(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }

        public string AsynchDroneCaseDataSTHXOld(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoSTHX>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;


                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                model.original_case_no = req.model.case_no;
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area;
                model.synchronoustime = DateTime.Now;
                #endregion

                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                Random random = new Random();
                string caseno;
                bool isUnique;
                do
                {
                    caseno = "STHX" + req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoSTHX.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);

                model.case_no = caseno;
                //新增数据
                db.DroneCaseInfoSTHX.Insert(model);
                if (!string.IsNullOrEmpty(model.Id))
                {
                    shps.ForEach(r => r.relid = model.Id);
                    db.DroneShpData.InsertRange(shps);
                    //新增修改图片
                    //files.ForEach(r => { r.relid = model.Id; });
                    //db.DroneFiles.InsertRange(files);
                }

                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 生态红线
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataSTHX(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoSTHX>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoSTHX.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");
                }
                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == req.model.case_no && a.SubjectKey == "Subject_STBHHXJG");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                model.original_case_no = req.model.case_no;
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();

                if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                {
                    model.nongyongdi_area = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var yongjiujibennongtian_area))
                {
                    model.yongjiujibennongtian_area = string.IsNullOrEmpty(yongjiujibennongtian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(yongjiujibennongtian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianquyu_area", out var zhongdianquyu_area))
                {
                    model.zhongdianquyu_area = string.IsNullOrEmpty(zhongdianquyu_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(zhongdianquyu_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var shengtaibaohuhongxian_area))
                {
                    model.shengtaibaohuhongxian_area = string.IsNullOrEmpty(shengtaibaohuhongxian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(shengtaibaohuhongxian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("guotukongjianguihua_area", out var guotukongjianguihua_area))
                {
                    model.guotukongjianguihua_area = string.IsNullOrEmpty(guotukongjianguihua_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(guotukongjianguihua_area.ToString())).ToString();
                }
                model.synchronoustime = DateTime.Now;
                #endregion

                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                Random random = new Random();
                string caseno;
                bool isUnique;
                do
                {
                    caseno = req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoSTHX.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);

                model.case_no = caseno;
                if (oldinfo != null)
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    //新增数据
                    db.DroneCaseInfoSTHX.Update(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_ZDWT2");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    //新增数据
                    db.DroneCaseInfoSTHX.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }
                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        /// <summary>
        /// 生态修复
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string AsynchDroneCaseDataSTXF(AddOrUpdateAsyncDroneCaseDataReq req)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                //案件
                var model = req.model.MapTo<DroneCaseInfoSTXF>();

                //文件
                var files = req.files;

                //shp
                var shps = req.shps;

                //关联案件
                var relations = req.relations;

                //案件标签
                var tags = req.tags;

                //查询是否存在此数据
                var oldinfo = db.DroneCaseInfoSTXF.AsQueryable().Where(c => c.original_case_no == model.case_no).First();
                if (oldinfo != null && db.WFProcess.AsQueryable().Where(r => r.Id == oldinfo.Id).Count() > 0)
                {
                    throw new Exception("数据已存在");
                }
                //存在旧数据并且复提表中没有复提数据，不允许复提
                var resubmitInfo = db.ReSubmit.GetFirst(a => a.CaseNo == req.model.case_no && a.SubjectKey == "Subject_STXF");
                if (oldinfo != null && resubmitInfo == null)
                {
                    throw new Exception("未发现复提请求");
                }
                if (string.IsNullOrEmpty(req.model.tubanlaiyuan))
                {
                    throw new Exception("图斑来源不能为空");
                }

                #region 案件资料处理
                model.original_case_no = req.model.case_no;
                //图斑
                model.geomid = ProcessShps(shps);
                //图片
                model.casepic = files != null ? string.Join(',', files.Select(r => r.path)) : null;
                //平方米转化
                model.area = req.model.area == null ? null : ConvertSquareMetersToMu(double.Parse(req.model.area)).ToString();

                if (req.model.extra_info.TryGetValue("nongyongdi_area", out var nongyongdi_area))
                {
                    model.nongyongdi_area = string.IsNullOrEmpty(nongyongdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(nongyongdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("gengdi_area", out var gengdi_area))
                {
                    model.gengdi_area = string.IsNullOrEmpty(gengdi_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(gengdi_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("yongjiujibennongtian_area", out var yongjiujibennongtian_area))
                {
                    model.yongjiujibennongtian_area = string.IsNullOrEmpty(yongjiujibennongtian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(yongjiujibennongtian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("zhongdianquyu_area", out var zhongdianquyu_area))
                {
                    model.zhongdianquyu_area = string.IsNullOrEmpty(zhongdianquyu_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(zhongdianquyu_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("shengtaibaohuhongxian_area", out var shengtaibaohuhongxian_area))
                {
                    model.shengtaibaohuhongxian_area = string.IsNullOrEmpty(shengtaibaohuhongxian_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(shengtaibaohuhongxian_area.ToString())).ToString();
                }

                if (req.model.extra_info.TryGetValue("guotukongjianguihua_area", out var guotukongjianguihua_area))
                {
                    model.guotukongjianguihua_area = string.IsNullOrEmpty(guotukongjianguihua_area?.ToString())
                        ? "0.00"
                        : ConvertSquareMetersToMu(double.Parse(guotukongjianguihua_area.ToString())).ToString();
                }
                model.synchronoustime = DateTime.Now;
                #endregion

                model.handle_status_id = 0;
                model.handle_status_name = "待接收";
                Random random = new Random();
                string caseno;
                bool isUnique;
                do
                {
                    caseno = req.model.countyid + DateTime.Now.ToString("yyyyMMdd") + random.Next(1000, 9999).ToString();
                    var count = db.DroneCaseInfoSTXF.AsQueryable().Where(c => c.case_no == caseno).Count();
                    isUnique = count == 0;

                } while (!isUnique);

                model.case_no = caseno;
                if (oldinfo != null)
                {
                    model.Id = oldinfo.Id;
                    model.case_no = oldinfo.case_no;
                    //新增数据
                    db.DroneCaseInfoSTXF.Update(model);

                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        relations.ForEach(r => r.caseid = model.Id);
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneShpData.Delete(c => c.relid == model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增及删除图片 
                        db.DroneFiles.Delete(r => r.relid == model.Id);
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        db.DroneCaseInfoRelation.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        db.DroneCaseInfoTag.Delete(r => r.caseid == model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                        //删除复提数据
                        db.ReSubmit.Delete(r => r.CaseNo == model.original_case_no && r.SubjectKey == "Subject_ZDWT2");
                    }
                }
                else
                {
                    model.Id = Guid.NewGuid().ToString();
                    //新增数据
                    db.DroneCaseInfoSTXF.Insert(model);
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        shps.ForEach(r => r.relid = model.Id);
                        db.DroneShpData.InsertRange(shps);
                        //新增修改图片
                        files.ForEach(r => { r.relid = model.Id; r.Id = Guid.NewGuid().ToString(); });
                        db.DroneFiles.InsertRange(files);
                        //关联案件
                        relations.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoRelation.InsertRange(relations);
                        //案件标签
                        tags.ForEach(r => r.caseid = model.Id);
                        db.DroneCaseInfoTag.InsertRange(tags);
                    }
                }
                AddDroneCaseLog(new DroneCaseOperationLog { request_data = Json.ToJson(req), description = "AsynchDroneCaseData", caseid = model.Id, createuserid = model.identification_userid, createusername = model.identification_user });
                if (db.Commit())
                {

                    return "同步成功";
                }

                else
                    throw new Exception("同步失败");
            }
        }
        static double ConvertSquareMetersToMu(double squareMeters)
        {
            // 1 亩 = 666.6667 平方米
            double mu = squareMeters * 0.0015;

            // 四舍五入保留两位小数
            return Math.Round(mu, 2);
        }
        private string ProcessShps(List<DroneShpData> shps)
        {
            var _gidStr = _commonDataManager.GetMaxKeyVal("gid", "drone_shp_data", 1);
            int _gid = int.Parse(_gidStr);
            var geomid = string.Join(",", shps.Select((item, index) =>
            {
                item.gid = _gid + index;
                return item.gid.ToString();
            }));

            return geomid;
        }

        #region 查询未发起流程的案件信息
        public Response<List<View_CaseNoProcess>> LoadNoProcess()
        {
            var caseList = client.Queryable<View_CaseNoProcess>().ToList();
            return new Response<List<View_CaseNoProcess>>()
            {
                Code = 200,
                Result = caseList
            };
        }
        #endregion


        #region 新版数据同步
        public async Task<string> AsynchDroneCaseDataLast([FromBody] AddOrUpdateAsyncDroneCaseDataReq req)
        {
            string result = "同步成功";
            string fail = "";
            foreach (var s in req.subjects)
            {
                if (!string.IsNullOrEmpty(s.Key))
                {
                    switch (s.Key)
                    {
                        case "Subject_WFYD":
                            //drone_caseinfo_single
                            var wfydid = AsynchDroneCaseDataWfydNew(req);
                            if (!string.IsNullOrEmpty(wfydid))
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:SchemeCode", wfydid, req.model.createusername, req.model.case_description))
                                {
                                    fail += "违法用地专题,";
                                }
                            }
                            else
                            {
                                fail += "违法用地专题,";
                            }
                            break;
                        case "Subject_GDFLH":
                            //drone_caseinfo_gdflh
                            var flhid = AsynchDroneCaseDataFLHNew(req);
                            if (!string.IsNullOrEmpty(flhid))
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:DroneCaseInfoNonFoodSchemeCode", flhid, req.model.createusername, req.model.case_description))
                                {
                                    fail += "耕地非粮化专题,";
                                }
                            }
                            else
                            {
                                fail += "耕地非粮化专题,";
                            }
                            break;
                        case "Subject_FFCK":
                            //drone_caseinfo_minerals
                            var ffckid = AsynchDroneCaseDataCKNew(req);
                            if (!string.IsNullOrEmpty(ffckid))
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:DroneCaseInfoMineralsSchemeCode", ffckid, req.model.createusername, req.model.case_description))
                                {
                                    fail += "非法采矿专题,";
                                }
                            }
                            else
                            {
                                fail += "非法采矿专题,";
                            }
                            break;

                        case "Subject_XCSJ":
                            //drone_caseinfo_xcsj
                            var xcsjid = AsynchDroneCaseDataXcsjNew(req);
                            if (!string.IsNullOrEmpty(xcsjid))
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:DroneCaseInfoXcsjSchemeCode", xcsjid, req.model.createusername, req.model.case_description))
                                {
                                    fail += "巡察审计专题,";
                                }
                            }
                            else
                            {
                                fail += "巡察审计专题,";
                            }
                            break;

                        case "Subject_ZDWT1":
                            //drone_caseinfo_zdwt1
                            var zdwt1id = AsynchDroneCaseDataZdwt1New(req);
                            if (!string.IsNullOrEmpty(zdwt1id))
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:DroneCaseInfoZdwt1SchemeCode", zdwt1id, req.model.createusername, req.model.case_description))
                                {
                                    fail += "重点问题Ⅰ类专题,";
                                }
                            }
                            else
                            {
                                fail += "重点问题Ⅰ类专题,";
                            }
                            break;

                        case "Subject_ZDWT2":
                            //drone_caseinfo_zdwt2
                            var zdwt2id = AsynchDroneCaseDataZdwt2New(req);
                            if (!string.IsNullOrEmpty(zdwt2id))
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:DroneCaseInfoZdwt2SchemeCode", zdwt2id, req.model.createusername, req.model.case_description))
                                {
                                    fail += "重点问题Ⅱ类专题,";
                                }
                            }
                            else
                            {
                                fail += "重点问题Ⅱ类专题,";
                            }
                            break;
                        case "Subject_STBHHXJG":
                            //drone_caseinfo_sthx
                            if (AsynchDroneCaseDataSTHX(req) == "同步成功")
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:DroneCaseInfoSTHXSchemeCode", req.model.Id, req.model.createusername, req.model.case_description))
                                {
                                    fail += "生态保护红线专题,";
                                }
                            }
                            else
                            {
                                fail += "生态保护红线专题,";
                            }
                            break;
                        case "Subject_STXF":
                            //drone_caseinfo_stxf
                            if (AsynchDroneCaseDataSTXF(req) == "同步成功")
                            {
                                if (s.IsAutoProcess == true && !await CreateProcess("AppSetting:DroneCaseInfoSTXFSchemeCode", req.model.Id, req.model.createusername, req.model.case_description))
                                {
                                    fail += "生态修复专题,";
                                }
                            }
                            else
                            {
                                fail += "生态修复专题,";
                            }
                            break;
                    }
                }
            }

            // 如果 fail 不为空，返回失败信息，否则返回 "同步成功"
            if (!string.IsNullOrEmpty(fail))
            {
                result = $"同步失败，以下专题失败: {fail.TrimEnd(',')}";
            }
            return result;
        }


        private async Task<bool> CreateProcess(string schemecode, string id, string createusername, string casedec)
        {
            var scode = _configuration.GetSection(schemecode).Value;
            var schemeInfo = await client.Queryable<WFSchemeInfo>().FirstAsync(a => a.Code == scode);
            var schemeId = schemeInfo?.SchemeId;
            var flag = await _wfProcessApp.SaveDraftWithUser(id, scode, createusername, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + id + "\"}", null, null, null, 0, (casedec));
            if (flag.Result)
            {
                var createFlag = await _wfProcessApp.CreateWithUser(id, null, createusername, null, "{\"schemeId\":\"" + schemeId + "\",\"pkey\":\"Id\",\"pkeyValue\":\"" + id + "\"}", (casedec));
                if (createFlag.Result)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

    }
}
