using Mall.Model.Extend.TradePavilion;
using Mall.Repository.TradePavilion;
using System.Collections.Generic;
using VT.FW.AOP.CustomerAttribute;
using Mall.Common.Enum;
using VT.FW.DB;
using Newtonsoft.Json.Linq;
using Mall.Common.Plugin;
using System.Linq;

namespace Mall.Module.TradePavilion
{
    /// <summary>
    /// 自定义表单处理类
    /// </summary>
    public class CustomFormModule
    {
        /// <summary>
        /// 自定义表单仓储层对象
        /// </summary>
        private readonly RB_Custom_FormRepository custom_FormRepository = new RB_Custom_FormRepository();

        /// <summary>
        /// 获取自定义表单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Custom_Form_Extend> GetCustomFormPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Custom_Form_Extend query)
        {
            return custom_FormRepository.GetCustomFormPageRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 获取自定义表单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Custom_Form_Extend> GetCustomFormListModule(RB_Custom_Form_Extend query)
        {
            return custom_FormRepository.GetCustomFormListRepository(query);
        }

        /// <summary>
        /// 小程序获取榜单表单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public object AppGetCustomFormModule(RB_Custom_Form_Extend query)
        {
            object result = new object();
            var model = GetCustomFormListModule(query)?.FirstOrDefault();
            if (model != null)
            {
                var dataList = AnalyzeFormComponent(model.FormData, isGetAnswer: false);
                result = new
                {
                    model.Id,
                    model.FormName,
                    model.FormType,
                    model.FormTypeStr,
                    FormData = dataList
                };
            }
            return result;
        }

        /// <summary>
        /// 检查表单是否存在
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CheckExistsCustomFormModule(RB_Custom_Form_Extend model)
        {
            IList<WhereHelper> list = new List<WhereHelper>
            {
                new WhereHelper(nameof(RB_Custom_Form_Extend.FormType), model.FormType),
                new WhereHelper(nameof(RB_Custom_Form_Extend.Status), (int)DateStateEnum.Normal),
                new WhereHelper(nameof(RB_Custom_Form_Extend.TenantId), model.TenantId)
            };
            if (model.Id > 0)
            {
                list.Add(new WhereHelper(nameof(RB_Custom_Form_Extend.Id), model.Id, OperatorEnum.NotEqual));
            }
            return custom_FormRepository.Exists(list);
        }

        /// <summary>
        /// 新增修改自定义表单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetCustomFormModule(RB_Custom_Form_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Custom_Form_Extend.FormName),model.FormName.Trim()},
                    { nameof(RB_Custom_Form_Extend.FormType),model.FormType},
                    { nameof(RB_Custom_Form_Extend.FormData),model.FormData},
                    { nameof(RB_Custom_Form_Extend.UpdateBy),model.UpdateBy},
                    { nameof(RB_Custom_Form_Extend.UpdateDate),model.UpdateDate},
                };
                flag= custom_FormRepository.Update(fileds, new WhereHelper(nameof(RB_Custom_Form_Extend.Id), model.Id));
            }
            else
            {
                var newId = custom_FormRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取自定义表单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Custom_Form_Extend GetCustomFormModule(object Id)
        {
            var extModel = custom_FormRepository.GetEntity<RB_Custom_Form_Extend>(Id);
            if (extModel != null)
            {
                extModel.FormDataList = AnalyzeFormComponent(extModel.FormData, isGetAnswer: true);
            }
            return extModel;
        }

        /// <summary>
        /// 解析表单组件
        /// </summary>
        /// <param name="formData"></param>
        /// <param name="isGetAnswer"></param>
        /// <returns></returns>
        public List<FormDataItem> AnalyzeFormComponent(string formData,bool isGetAnswer=false)
        {
            List<FormDataItem> dataList = new List<FormDataItem>();
            if (!string.IsNullOrEmpty(formData))
            {
                JArray jArray = JArray.Parse(formData);
                if (jArray != null && jArray.Count > 0)
                {
                    foreach (var jItem in jArray)
                    {
                        JObject jObj = JObject.Parse(jItem.ToString());
                        FormDataItem dataItem = new FormDataItem()
                        {
                            CompKey = jObj.GetStringValue("CompKey"),
                            CompData = new object(),
                            isCked=false,
                        };
                        if (!string.IsNullOrEmpty(dataItem.CompKey))
                        {
                            string compData = jObj.GetStringValue("CompData");
                            switch (dataItem.CompKey)
                            {
                                //单行文本
                                case "SingleLineText":
                                    TextItem txtItem = GetTextItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        txtItem.TextValue = "";
                                    }
                                    dataItem.CompData = txtItem;
                                    break;
                                //多行文本
                                case "MultiLineText":
                                    TextItem multiItem = GetTextItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        multiItem.TextValue = "";
                                    }
                                    dataItem.CompData = multiItem;
                                    break;
                                //下拉框
                                case "DorpDownList":
                                    SelectItem selectItem = GetSelectItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        selectItem.OptionValue = "";
                                    }
                                    dataItem.CompData = selectItem;
                                    break;
                                //图片上传组件
                                case "ImageUploadComp":
                                    UploadItem imgItem = GetUploadItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        imgItem.FileList = new List<string>();
                                    }
                                    dataItem.CompData = imgItem;
                                    break;
                                //视频上传组件
                                case "VideoUploadComp":
                                    UploadItem videoItem = GetUploadItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        videoItem.FileList = new List<string>();
                                    }
                                    dataItem.CompData = videoItem;
                                    break;
                            }
                            dataList.Add(dataItem);
                        }
                    }
                }
            }
            return dataList;
        }

        /// <summary>
        /// 获取文本框信息
        /// </summary>
        /// <param name="CompData"></param>
        /// <returns></returns>
        private TextItem GetTextItem(string CompData)
        {
            JObject textObj = JObject.Parse(CompData);
            TextItem txtItem = new TextItem()
            {
                Name = textObj.GetStringValue("Name"),
                WordsLength = textObj.GetInt("WordsLength"),
                IsRequire = textObj.GetBoolValue("IsRequire"),
                Remark = textObj.GetStringValue("Remark"),
                TextValue = textObj.GetStringValue("TextValue"),
            };
            return txtItem;
        }

        /// <summary>
        /// 获取下拉框信息
        /// </summary>
        /// <param name="CompData"></param>
        /// <returns></returns>
        private SelectItem GetSelectItem(string CompData)
        {
            JObject dropdownObj = JObject.Parse(CompData);
            SelectItem selectItem = new SelectItem()
            {
                Name = dropdownObj.GetStringValue("Name"),
                IsMultiple = dropdownObj.GetBoolValue("IsMultiple"),
                IsRequire = dropdownObj.GetBoolValue("IsRequire"),
                OptionList = new List<SelectOption>(),
                Remark = dropdownObj.GetStringValue("Remark"),
            };
            if (selectItem.IsMultiple)
            {
                List<string> valueList = JsonHelper.DeserializeObject<List<string>>(dropdownObj.GetStringValue("OptionValue"));
                if (valueList != null && valueList.Count > 0)
                {
                    selectItem.OptionValue = string.Join(",", valueList);
                }
            }
            else
            {
                selectItem.OptionValue = dropdownObj.GetStringValue("OptionValue");
            }
            var optionList = JArray.Parse(dropdownObj.GetStringValue("OptionList"));
            if (optionList != null && optionList.Count > 0)
            {
                foreach (var oItem in optionList)
                {
                    JObject optionObj = JObject.Parse(oItem.ToString());
                    SelectOption option = new SelectOption()
                    {
                        Id = optionObj.GetInt("Id"),
                        Name = optionObj.GetStringValue("Name"),
                    };
                    selectItem.OptionList.Add(option);
                }
            }
            return selectItem;
        }

        /// <summary>
        /// 获取上传配置信息
        /// </summary>
        /// <param name="CompData"></param>
        /// <returns></returns>
        private UploadItem GetUploadItem(string CompData)
        {
            JObject uploadObj = JObject.Parse(CompData);
            UploadItem uploadItem = new UploadItem()
            {
                Name = uploadObj.GetStringValue("Name"),
                FileCount = uploadObj.GetInt("FileCount"),
                FileSizeLimit = uploadObj.GetInt("FileSizeLimit"),
                Remark = uploadObj.GetStringValue("Remark"),
                FileList = new List<string>(),
            };
            if (!string.IsNullOrEmpty(uploadObj.GetStringValue("FileList")))
            {
                try
                {
                    uploadItem.FileList =JsonHelper.DeserializeObject<List<string>>(uploadObj.GetStringValue("FileList"));
                }
                catch
                {

                }
            }
            return uploadItem;
        }


        /// <summary>
        /// 根据编号删除自定义表单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveCustomFormModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Custom_Form_Extend.Status),(int)DateStateEnum.Delete}
            };
            return custom_FormRepository.Update(fileds, new WhereHelper(nameof(RB_Custom_Form_Extend.Id),Id));
        }
    }
}
