using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ASHermed.SinoInterface.Api.ContractModel.Quest;
using ASHermed.SinoInterface.Api.IRepository.Quest;
using ASHermed.SinoInterface.Api.IService.Quest;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Tools;
using PoJun.Util.Maps;
using Newtonsoft.Json;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.ContractModel.App.Model;
using ASHermed.SinoInterface.Api.IService;
using Microsoft.Extensions.Logging;

namespace ASHermed.SinoInterface.Api.Service.Quest
{
    public class QuestService : BaseService, IQuestService
    {
        private readonly IPubQuestInfoRepository _pubQuestInfoRepository;
        private readonly IPubQuestFieIdRepository _pubQuestFieIdRepository;
        private readonly IPubQuestOptionRepository _pubQuestOptionRepository;
        private readonly IPubQuestCategoryRepository _pubQuestCategoryRepository;
        private readonly IPubQuestReleaseRepository _pubQuestReleaseRepository;
        private readonly IPubQuestDataRepository _pubQuestDataRepository;
        private readonly IPubQuestDataDetailRepository _pubQuestDataDetailRepository;
        private readonly IPubPatInfoRepository _pubPatInfoRepository;
        private readonly IFileRepository _fileRepository;
        private readonly ITCService _tCService;
        private readonly ILogger<QuestService> _logger;
        private readonly IOutAptInfoRepository _outAptInfoRepository;
        public QuestService(IPubQuestInfoRepository pubQuestInfoRepository, IPubQuestFieIdRepository pubQuestFieIdRepository, IPubQuestOptionRepository pubQuestOptionRepository, IPubQuestCategoryRepository pubQuestCategoryRepository, IPubQuestReleaseRepository pubQuestReleaseRepository, IPubQuestDataRepository pubQuestDataRepository, IPubQuestDataDetailRepository pubQuestDataDetailRepository, IPubPatInfoRepository pubPatInfoRepository, IFileRepository fileRepository, ITCService tCService, ILogger<QuestService> logger, IOutAptInfoRepository outAptInfoRepository)
        {
            _pubQuestInfoRepository = pubQuestInfoRepository;
            _pubQuestFieIdRepository = pubQuestFieIdRepository;
            _pubQuestOptionRepository = pubQuestOptionRepository;
            _pubQuestCategoryRepository = pubQuestCategoryRepository;
            _pubQuestReleaseRepository = pubQuestReleaseRepository;
            _pubQuestDataRepository = pubQuestDataRepository;
            _pubQuestDataDetailRepository = pubQuestDataDetailRepository;
            _pubPatInfoRepository = pubPatInfoRepository;
            _fileRepository = fileRepository;
            _tCService = tCService;
            _logger = logger;
            _outAptInfoRepository = outAptInfoRepository;
        }

        public async Task<BaseResponse<bool>> CreateQuestInfo(QuestInfo questInfo)
        {
            var user = GetBaseUserInfo();
            questInfo.PubQuestInfo.CreateTime = DateTime.Now;
            questInfo.PubQuestInfo.CreateUser = user.ID.ToString();
            questInfo.PubQuestInfo.Version = 1.0M;

            BaseResponse<bool> response = new BaseResponse<bool>();
            questInfo.PubQuestInfo.Id = await _pubQuestInfoRepository.InsertAnReturnIdAsync(questInfo.PubQuestInfo);
            await _pubQuestInfoRepository.InsertConfig(new Pub_Quest_Config { DeptId = questInfo.PubQuestInfo.DeptId, DeptName = questInfo.PubQuestInfo.DeptName, HosId = questInfo.PubQuestInfo.HosId, HosName = questInfo.PubQuestInfo.HosName, InfoId = questInfo.PubQuestInfo.Id });
            foreach (var item in questInfo.QuestCategorie)
            {
                item.InfoId = questInfo.PubQuestInfo.Id;
                await CreateQuestCategory(item);
            }
            response.Data = true;
            return response;
        }

        public async Task<int> CreateQuestCategory(QuestCategory questCategory)
        {
            var catesort = await _pubQuestCategoryRepository.GetCategorieForInfoId(questCategory.InfoId);
            questCategory.Sort = catesort.Max(m => m.Sort) + 1;
            questCategory.CreateTime = DateTime.Now;
            questCategory.CreateUser = "admin";
            if (questCategory.Id == 0)
            {
                questCategory.Id = await _pubQuestCategoryRepository.InsertAndReturnIdAsync(questCategory);
            }
            foreach (var item in questCategory.QuestFieId)
            {
                item.CategoryId = questCategory.Id;
                await CreateQuestFieId(item);
            }
            return questCategory.Id;
        }


        public async Task<int> CreateQuestFieId(QuestFieId questFieId)
        {
            List<int> fiedids = new List<int>(); fiedids.Add(questFieId.CategoryId);
            var fiedsort = await _pubQuestFieIdRepository.GetFieIdForCateId(fiedids);
            if (fiedsort.Any())
            {
                questFieId.Sort = fiedsort.Max(m => m.Sort) + 1;
            }
            questFieId.CreateTime = DateTime.Now;
            questFieId.CreateUser = "admin";
            questFieId.Id = await _pubQuestFieIdRepository.InsertAndReturnIdAsync(questFieId);
            foreach (var item in questFieId.QuestOptionList)
            {
                item.FieldId = questFieId.Id;
                await CreateQuestOption(item);
            }
            return questFieId.Id;
        }

        public async Task<int> CreateQuestOption(QuestOption questOption)
        {
            List<int> optionids = new List<int>(); optionids.Add(questOption.FieldId);
            var optionsort = await _pubQuestOptionRepository.GetOptionForFiedid(optionids);
            if (optionsort.Any())
            {
                questOption.Sort = optionsort.Max(m => m.Sort) + 1;
            }
            questOption.CreateTime = DateTime.Now;
            questOption.CreateUser = "admin";
            questOption.Id = await _pubQuestOptionRepository.InsertAndReturnIdAsync(questOption);
            return questOption.Id;
        }





        public async Task<QuestInfo> GetQuestInfo(int questId)
        {
            var questinfo = await _pubQuestInfoRepository.GetByIdAsync(questId);
            var config = await _pubQuestInfoRepository.GetConfig(questId);
            var questCate = await _pubQuestCategoryRepository.GetCategorieForInfoId(questinfo.Id);
            var questFiedid = await _pubQuestFieIdRepository.GetFieIdForCateId(questCate.Select(f => f.Id).ToList());
            var questOption = await _pubQuestOptionRepository.GetOptionForFiedid(questFiedid.Select(f => f.Id).ToList());

            QuestInfo response = new QuestInfo();
            questinfo.HosId = config.HosId;
            questinfo.HosName = config.HosName;
            questinfo.DeptId = config.DeptId;
            questinfo.DeptName = config.DeptName;
            response.PubQuestInfo = questinfo;

            foreach (var item in questCate.OrderBy(o => o.Sort))
            {
                var cate = item.MapTo<QuestCategory>();
                cate.QuestFieId = GetFieId(item.Id, questFiedid, questOption);
                response.QuestCategorie.Add(cate);
            }
            return response;
        }

        public List<QuestFieId> GetFieId(int cateId, List<Pub_Quest_FieId> questFieId, List<Pub_Quest_Option> questOption)
        {
            List<QuestFieId> res = new List<QuestFieId>();
            foreach (var item in questFieId.Where(w => w.CategoryId == cateId).OrderBy(o => o.Sort))
            {
                var fieid = item.MapTo<QuestFieId>();
                fieid.QuestOptionList = GetOption(item.Id, questOption);
                res.Add(fieid);
            }
            return res;
        }

        public List<QuestOption> GetOption(int fieId, List<Pub_Quest_Option> questOption)
        {
            List<QuestOption> res = new List<QuestOption>();
            foreach (var item in questOption.Where(w => w.FieldId == fieId).OrderBy(o => o.Sort))
            {
                var option = item.MapTo<QuestOption>();
                res.Add(option);
            }
            return res;
        }





        public async Task<int> ReleaseQuest(int questInfoId)
        {
            var user = GetBaseUserInfo();
            var questInfo = await GetQuestInfo(questInfoId);
            var version = questInfo.PubQuestInfo.Version + 1;
            questInfo.PubQuestInfo.Version = version;
            return await _pubQuestReleaseRepository.InsertAnReturnIdAsync(new Pub_Quest_Release
            {
                Content = questInfo.ToJson(),
                CreateTime = DateTime.Now,
                CreateUser = user.ID.ToString(),
                QuestInfoId = questInfoId,
                QuestInfoName = questInfo.PubQuestInfo.Name,
                QuestInfoNameEN = questInfo.PubQuestInfo.NameEN,
                QuestInfoNameGE = questInfo.PubQuestInfo.NameGE,
                Version = version
            });
        }

        public async Task<QuestInfo> GetQuestInfoRelease(int questInfoId, int languege, decimal version, string pid)
        {
            if (pid.ToLower() == "NULL".ToLower())
            {
                pid = "";
            }
            QuestInfo res = new QuestInfo();
            var questInfo = await _pubQuestInfoRepository.GetByIdAsync(questInfoId);
            var releaseInfo = await _pubQuestReleaseRepository.GetByIdAsync(questInfoId, version == 0M ? questInfo.Version : version);
            res = JsonConvert.DeserializeObject<QuestInfo>(releaseInfo.Content);
            //体检问卷
            if (questInfoId == 1)
            {
                if (!string.IsNullOrEmpty(pid))
                {
                    var pat = _tCService.GetPatient(pid, string.Empty, string.Empty);
                    var fieidls = new List<QuestFieId>();
                    res.QuestCategorie.ForEach(w => { fieidls.AddRange(w.QuestFieId); });
                    var any = fieidls.Where(w => w.Name == "请选择您的性别").FirstOrDefault();
                    if (any != null)
                    {
                        List<Pub_Quest_DataDetail> datadetail = new List<Pub_Quest_DataDetail>();
                        if (pat.FirstOrDefault().PAPERSex == "女 Female")
                        {
                            datadetail.Add(new Pub_Quest_DataDetail { CategoryId = any.CategoryId, InfoId = questInfoId, FieIdId = any.Id, FieIdOptionIds = any.QuestOptionList.Where(w => w.Name == "女").FirstOrDefault().Id.ToString() });
                        }
                        else
                        {
                            datadetail.Add(new Pub_Quest_DataDetail { CategoryId = any.CategoryId, InfoId = questInfoId, FieIdId = any.Id, FieIdOptionIds = any.QuestOptionList.Where(w => w.Name == "男").FirstOrDefault().Id.ToString() });
                        }
                        res.PubQuestInfo.Config = datadetail.ToJson();
                        if (!datadetail.Any())
                        {
                            res.PubQuestInfo.Config = "[]";
                        }
                    }
                }
            }
            if (questInfoId == 3)
            {
                List<Pub_Quest_DataDetail> datadetail = new List<Pub_Quest_DataDetail>();
                if (!string.IsNullOrEmpty(pid))
                {
                    var pat = _tCService.GetPatient(pid, string.Empty, string.Empty);
                    var fieidls = new List<QuestFieId>();
                    res.QuestCategorie.ForEach(w => { fieidls.AddRange(w.QuestFieId); });
                    var any = fieidls.Where(w => w.Name == "您的姓名").FirstOrDefault();
                    if (any != null)
                    {
                        datadetail.Add(new Pub_Quest_DataDetail
                        {
                            CategoryId = any.CategoryId,
                            InfoId = questInfoId,
                            FieIdId = any.Id,
                            FieIdOptionIds = any.QuestOptionList.FirstOrDefault().Id.ToString(),
                            Value = pat.FirstOrDefault().PAPERName + pat.FirstOrDefault().PAPERName2
                        });
                    }
                    var any1 = fieidls.Where(w => w.Name == "您的手机号码").FirstOrDefault();
                    if (any1 != null)
                    {
                        datadetail.Add(new Pub_Quest_DataDetail
                        {
                            CategoryId = any1.CategoryId,
                            InfoId = questInfoId,
                            FieIdId = any1.Id,
                            FieIdOptionIds = any1.QuestOptionList.FirstOrDefault().Id.ToString(),
                            Value = pat.FirstOrDefault().PAPERMobPhone
                        });
                    }

                    res.PubQuestInfo.Config = datadetail.ToJson();
                    if (!datadetail.Any())
                    {
                        res.PubQuestInfo.Config = "[]";
                    }
                }
            }
            if (!string.IsNullOrEmpty(pid))
            {
                res.PatInfo = _pubPatInfoRepository.SelectByMrn(pid);
            }
            ChangeLanguege(res, languege);
            return res;
        }

        public async Task<int> QuestAnswer(QuestAnswer questAnswer, bool isToken)
        {
            List<Pub_Quest_DataDetail> details = new List<Pub_Quest_DataDetail>();
            questAnswer.CreateTime = DateTime.Now;
            if (isToken)
            {
                questAnswer.UserId = GetBaseUserInfo().ID;
                questAnswer.CreateUser = GetBaseUserInfo().ID.ToString();
            }
            var dataId = await _pubQuestDataRepository.InsertAndReturnIdAsync(questAnswer);
            questAnswer.DataDetail.ForEach(w =>
            {
                w.DataId = dataId;
                w.InfoId = questAnswer.InfoId;
                List<Pub_Quest_Option> options = JsonConvert.DeserializeObject<List<Pub_Quest_Option>>(w.OtherTxt);
                foreach (var item in w.FieIdOptionIds.Split(','))
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        w.FieIdOptionId = int.Parse(item);
                        Pub_Quest_DataDetail m = w.MapTo<Pub_Quest_DataDetail>();
                        m.OtherTxt = options.Where(f => f.Id == int.Parse(item)).FirstOrDefault() == null ? "[]" : options.Where(f => f.Id == int.Parse(item)).FirstOrDefault().Value;
                        m.IsDelete = false;
                        details.Add(m);
                    }
                }
            });
            var res = await _pubQuestDataDetailRepository.InsertAsync(details);
            if (questAnswer.InfoId == 1)
            {
                if (!string.IsNullOrEmpty(questAnswer.FilePath))
                {
                    var file = _fileRepository.GetFilesContentForId(int.Parse(questAnswer.FilePath));
                    var pat = _pubPatInfoRepository.SelectByMrn(questAnswer.PID);
                    var pName = file.FileUrl.Split('\\')?.LastOrDefault().Split('.').LastOrDefault();
                    if (pat != null)
                    {
                        var picParRef = _tCService.GetEpisodesForPatient(pat.Pat_MRN);
                        if (picParRef.Any())
                        {
                            var tcres = _tCService.CustomCRMMRPictures(picParRef.FirstOrDefault().PAADMMainMRADMDR, "健康评估问卷", pat.Pat_Name + "健康评估Health Evaluation" + DateTime.Now.ToString("yyyy-MM-dd") + "." + pName, file.Content);
                            _logger.LogInformation("SendFileToTcQuest:" + file.Id + "   reb:" + tcres);
                        }
                    }
                }
            }
            if (questAnswer.InfoId == 3)
            {
                var questOutApt = _outAptInfoRepository.GetOutAptForQuest(questAnswer.PatId);
                _outAptInfoRepository.UpdateOutAptForQuestId(questOutApt.Select(w => w.Id).ToList(), dataId);
            }
            if (res > 0)
            {
                return dataId;
            }
            return 0;
        }

        public async Task<bool> EditQuestAnswer(QuestAnswer questAnswer)
        {
            List<Pub_Quest_DataDetail> details = new List<Pub_Quest_DataDetail>();
            await _pubQuestDataDetailRepository.DeleteAsync(questAnswer.Id);
            questAnswer.DataDetail.ForEach(w =>
            {
                w.DataId = questAnswer.Id;
                w.InfoId = questAnswer.InfoId;
                List<Pub_Quest_Option> options = JsonConvert.DeserializeObject<List<Pub_Quest_Option>>(w.OtherTxt);
                foreach (var item in w.FieIdOptionIds.Split(','))
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        w.FieIdOptionId = int.Parse(item);
                        Pub_Quest_DataDetail m = w.MapTo<Pub_Quest_DataDetail>();
                        m.OtherTxt = options.Where(f => f.Id == int.Parse(item)).FirstOrDefault() == null ? "[]" : options.Where(f => f.Id == int.Parse(item)).FirstOrDefault().Value;
                        m.IsDelete = false;
                        details.Add(m);
                    }
                }
            });
            var res = await _pubQuestDataDetailRepository.InsertAsync(details);
            if (res > 0)
            {
                return true;
            }
            return false;
        }

        public async Task<BaseResponse<QuestAnswer>> EchoAnswer(int infoId, string pid = "", int patId = 0)
        {
            BaseResponse<QuestAnswer> response = new BaseResponse<QuestAnswer>();
            var userId = GetBaseUserInfo()?.ID;
            var datals = await _pubQuestDataRepository.GetByUserIdAsync(userId, patId, infoId, pid);
            if (!datals.Any())
            {
                response.Code = 0;
                response.Msg = "暂无数据";
                return response;
            }
            var data = datals.OrderByDescending(o => o.Version).ToList().FirstOrDefault();
            var dataid = data != null ? data.Id : 0;
            var datadetail = await _pubQuestDataDetailRepository.GetByDataIdAsync(dataid);
            if (!datadetail.Any())
            {
                response.Code = 0;
                response.Msg = "暂无数据";
                return response;
            }
            response.Data = data.MapTo<QuestAnswer>();
            response.Data.DataDetail = GetDatDetail(datadetail);
            response.Code = 1;
            response.Msg = "成功";
            return response;
        }

        public async Task<object> EchoAnswerForId(int id)
        {
            QuestAnswer response = new QuestAnswer();
            var data = await _pubQuestDataRepository.GetByIdAsync(id);
            if (data == null)
            {
                return new { Data = "", DetailedStatus = 0, DetailedMessage = "暂无数据" };
            }
            var datadetail = await _pubQuestDataDetailRepository.GetByDataIdAsync(data.Id);
            if (!datadetail.Any())
            {
                return new { Data = "", DetailedStatus = 0, DetailedMessage = "暂无数据" };
            }
            response = data.MapTo<QuestAnswer>();
            response.DataDetail = GetDatDetail(datadetail);
            return new { Data = response, DetailedStatus = 1, DetailedMessage = "成功" };
        }

        public async Task<BaseResponse<QuestAnswer>> EchoAnswerFor3(int patId)
        {
            BaseResponse<QuestAnswer> response = new BaseResponse<QuestAnswer>();
            if (patId == 0)
            {
                return response;
            }
            var datals = await _pubQuestDataRepository.GetByPatId3Async(patId, 3);
            if (!datals.Any())
            {
                response.Code = 0;
                response.Msg = "暂无数据";
                return response;
            }
            var data = datals.OrderByDescending(o => o.CreateTime).ToList().FirstOrDefault();
            var dataid = data != null ? data.Id : 0;
            var datadetail = await _pubQuestDataDetailRepository.GetByDataIdAsync(dataid);
            if (!datadetail.Any())
            {
                response.Code = 0;
                response.Msg = "暂无数据";
                return response;
            }
            response.Data = data.MapTo<QuestAnswer>();
            response.Data.DataDetail = GetDatDetail(datadetail);
            response.Code = 1;
            response.Msg = "成功";
            return response;
        }

        public async Task<BaseResponse<QuestAnswer>> EchoAnswerFor3Count(int patId)
        {
            BaseResponse<QuestAnswer> response = new BaseResponse<QuestAnswer>();
            if (patId == 0)
            {
                response.Msg = "患者ID不能为空";
                return response;
            }
            var datals = await _pubQuestDataRepository.GetByPatId3Async(patId, 3);
            if (!datals.Any())
            {
                response.Code = 1;
                response.Msg = "暂无数据";
                return response;
            }
            var data = datals.OrderByDescending(o => o.CreateTime).ToList().FirstOrDefault();
            var dataid = data != null ? data.Id : 0;
            var datadetail = await _pubQuestDataDetailRepository.GetByDataIdAsync(dataid);
            if (!datadetail.Any())
            {
                response.Code = 1;
                response.Msg = "暂无数据";
                return response;
            }
            response.Data = data.MapTo<QuestAnswer>();
            response.Data.DataDetail = GetDatDetail(datadetail);
            response.Code = 1;
            response.Msg = "成功";
            return response;
        }

        public List<Pub_Quest_DataDetail> GetDatDetail(List<Pub_Quest_DataDetail> detail)
        {
            List<Pub_Quest_DataDetail> res = new List<Pub_Quest_DataDetail>();
            foreach (var item in detail)
            {
                var online = res.Where(w => w.InfoId == item.InfoId && w.CategoryId == item.CategoryId && w.FieIdId == item.FieIdId).ToList();
                if (online.Any())
                {
                    var onlinefi = online.FirstOrDefault();
                    onlinefi.FieIdOptionIds = onlinefi.FieIdOptionIds += "," + item.FieIdOptionId;
                    List<Pub_Quest_Option> options = JsonConvert.DeserializeObject<List<Pub_Quest_Option>>(onlinefi.OtherTxt);
                    if (!string.IsNullOrEmpty(item.OtherTxt) && item.OtherTxt != "[]")
                    {
                        options.Add(new Pub_Quest_Option { Id = item.FieIdOptionId, Value = item.OtherTxt });
                    }
                    onlinefi.OtherTxt = JsonConvert.SerializeObject(options);
                }
                else
                {
                    item.FieIdOptionIds = item.FieIdOptionId.ToString();
                    List<Pub_Quest_Option> options = new List<Pub_Quest_Option>();
                    try
                    {
                        JsonConvert.DeserializeObject<List<Pub_Quest_Option>>(item.OtherTxt);
                    }
                    catch (System.Exception e) { }
                    if (!string.IsNullOrEmpty(item.OtherTxt) && item.OtherTxt != "[]")
                    {
                        options.Add(new Pub_Quest_Option { Id = item.FieIdOptionId, Value = item.OtherTxt });
                    }
                    item.OtherTxt = JsonConvert.SerializeObject(options);
                    res.Add(item);
                }
            }
            return res;
        }

        public QuestInfo ChangeLanguege(QuestInfo info, int languege)
        {
            if (languege == 2)
            {
                info.PubQuestInfo.Name = info.PubQuestInfo.NameEN;
                foreach (var item in info.QuestCategorie)
                {
                    item.Name = item.NameEN;
                    foreach (var item1 in item.QuestFieId)
                    {
                        item1.Name = item1.NameEN;
                        item1.PlaceHolder = item1.PlaceHolderEN;
                        foreach (var item2 in item1.QuestOptionList)
                        {
                            item2.Name = item2.NameEN;
                            item2.OtherPlaceHolder = item2.OtherPlaceHolderEN;
                        }
                    }
                }
            }
            else if (languege == 3)
            {
                info.PubQuestInfo.Name = info.PubQuestInfo.NameGE;
                foreach (var item in info.QuestCategorie)
                {
                    item.Name = item.NameGE;
                    foreach (var item1 in item.QuestFieId)
                    {
                        item1.Name = item1.NameGE;
                        item1.PlaceHolder = item1.PlaceHolderGE;
                        foreach (var item2 in item1.QuestOptionList)
                        {
                            item2.Name = item2.NameGE;
                            item2.OtherPlaceHolder = item2.OtherPlaceHolderGE;
                        }
                    }
                }
            }
            return info;
        }


        public async Task<BaseResponse<List<QuestPat>>> GetQuestPat(string phone)
        {
            BaseResponse<List<QuestPat>> response = new BaseResponse<List<QuestPat>>();
            var pat = await _pubQuestInfoRepository.GetQuestPat(phone);
            var questdata = await _pubQuestDataRepository.GetByAptId(pat.Select(w => w.OutAptId).ToList());
            foreach (var item in pat)
            {
                item.Phone_NO = item.Phone_NO.PhoneDesensitization();
                item.Pat_Name = item.Pat_Name.NameDesensitization();
                var answer = questdata.Where(w => w.AptId == item.OutAptId).FirstOrDefault();
                if (answer != null)
                {
                    item.InfoId = answer.InfoId;
                    item.IsQuestAnswer = true;
                }
            }
            response.Data = pat;
            response.Code = 1;
            response.Msg = "success";
            return response;
        }

        public async Task<int> Synchronization(int infoId)
        {
            var release = await _pubQuestReleaseRepository.GetByIdAsync(infoId, 1M);
            var res = JsonConvert.DeserializeObject<QuestInfo>(release.Content);

            var info = await _pubQuestInfoRepository.GetByIdAsync(res.PubQuestInfo.Id);
            var one = await _pubQuestInfoRepository.UpdateInfo(res.PubQuestInfo);

            var cates = await _pubQuestCategoryRepository.GetCategorieForInfoId(infoId);
            var fieds = await _pubQuestFieIdRepository.GetFieIdForCateId(cates.Select(w => w.Id).ToList());
            var options = await _pubQuestOptionRepository.GetOptionForFiedid(fieds.Select(w => w.Id).ToList());
            foreach (var item in res.QuestCategorie)
            {
                var cate = cates.Where(w => w.Id == item.Id).FirstOrDefault();
                if (cate != null)
                {
                    var two = await _pubQuestCategoryRepository.UpdateCate(item);
                }
                else
                {

                }
                foreach (var itemfieid in item.QuestFieId)
                {
                    var fied = fieds.Where(w => w.Id == itemfieid.Id).FirstOrDefault();
                    if (fied != null)
                    {
                        var thrr = await _pubQuestFieIdRepository.UpdateFied(itemfieid);
                    }
                    else
                    {

                    }
                    foreach (var itemoption in itemfieid.QuestOptionList)
                    {
                        var option = options.Where(w => w.Id == itemoption.Id).FirstOrDefault();
                        if (option != null)
                        {
                            var foru = await _pubQuestOptionRepository.UpdateOption(itemoption);
                        }
                        else
                        {

                        }
                    }
                }
            }
            return 1;
        }

        public async Task<int> InsertCate(QuestInfo questInfo)
        {
            foreach (var item in questInfo.QuestCategorie)
            {
                item.InfoId = questInfo.PubQuestInfo.Id;
                await CreateQuestCategory(item);
            }
            return 1;
        }

        public async Task<int> InsertOption(QuestInfo questInfo)
        {
            var item = questInfo.QuestCategorie[0];
            var itemfild = item.QuestFieId[0];
            var itemoption = itemfild.QuestOptionList;
            var fild = await _pubQuestFieIdRepository.GetByNameAsync("您伴有以下症状吗？");
            foreach (var item1 in itemoption)
            {
                item1.FieldId = fild.Id;
                await CreateQuestOption(item1);
            }
            return 1;
        }

        public async Task<int> ChangeCateSort(int infoid)
        {
            var releaseInfo = await _pubQuestReleaseRepository.GetByIdAsync(infoid, 7);
            var res = JsonConvert.DeserializeObject<QuestInfo>(releaseInfo.Content);
            var ischangesort = false;
            foreach (var item in res.QuestCategorie)
            {
                if (ischangesort)
                {
                    item.Sort = item.Sort + 1;
                }
                if (item.Name == "过敏史")
                {
                    ischangesort = true;
                    var aa = res.QuestCategorie.Where(w => w.Name == "预防接种情况").FirstOrDefault();
                    aa.Sort = item.Sort;

                    item.Sort = item.Sort + 1;
                }
            }
            res.QuestCategorie = res.QuestCategorie.OrderBy(o => o.Sort).ToList();

            foreach (var item in res.QuestCategorie)
            {
                await _pubQuestCategoryRepository.UpdateSort(item.Id, item.Sort);
            }

            var bb = JsonConvert.SerializeObject(res);

            return 1;
        }

    }
}
