using Learun.Application.Organization;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using HttpGetAttribute = System.Web.Mvc.HttpGetAttribute;
using HttpPostAttribute = System.Web.Mvc.HttpPostAttribute;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-23 11:30
    /// 描 述：属性表
    /// </summary>
    public class ec_propertyController : MvcControllerBase
    {
        private ec_propertyIBLL ec_propertyIBLL = new ec_propertyBLL();
        private ec_objecttypepIBLL ec_objecttypepIBLL = new ec_objecttypepBLL();
        #region 视图功能

        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 表单页
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Form()
        {
            return View();
        }
        /// <summary>
        /// 属性设置页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SelectProperty()
        {
            return View();
        }
        /// <summary>
        /// 设置对象类型 - 属性 的高级联动设置
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PropertyDependent()
        {
            return View();
        }

        /// <summary>
        ///对象类型页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SelectObjectType()
        {
            return View();
        }
        #endregion

        #region 获取数据

        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <param name="engineDataID">工程数据ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string queryJson, string engineDataID = "", string caseID = "")
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            paginationobj.sidx = "OrderID ";
            paginationobj.sord = "ASC";
            var data = ec_propertyIBLL.GetList(queryJson, engineDataID, paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }


        /// <summary>
        /// 用于 对象类型 - 属性设置
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <param name="engineDataID">工程数据ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList2(string ProjectId, string ObjectTypeID, string PropertyGID)
        {
            if (string.IsNullOrEmpty(PropertyGID))
            {
                //没选择group时，不返回
                return Success(null);
            }
            var data = ec_propertyIBLL.GetObjectLinkedProps(ProjectId, ObjectTypeID, PropertyGID);

            return Success(data);
        }
        /// <summary>
        /// 获取表单数据
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue, string ProjectId)
        {
            if (keyValue == GlobalObject.fakeID)
            {
                var settingTbName = ProjectSugar.TableName<ec_projectSettingsEntity>(ProjectId);
                var existvalue = SqlSugarHelper.Db.Queryable<ec_projectSettingsEntity>().AS(settingTbName).First(x => x.SettingName == GlobalObject.projSetting_TagNumber_CADBlockAlias);

                var ec_propertyDataFake = new ec_propertyEntity()
                {
                    PropertyID = GlobalObject.fakeID,
                    PropertyGID = GlobalObject.fakeID,
                    PropertyName = GlobalObject.propName_TagNumber,
                    PropertyNameEN = GlobalObject.propName_TagNumber,
                    PropertyType = "00001",//文本
                    OrderID = 1,
                    CADBlockAlias = existvalue == null ? "" : existvalue.SettingValue, //从项目设置来好了
                    BasicGroup = 1
                };
                var jsonData2 = new
                {
                    ec_property = ec_propertyDataFake,
                };
                return Success(jsonData2);
            }
            var ec_propertyData = ec_propertyIBLL.GetEntity(keyValue, ProjectId);
            //if (ec_propertyData.PropertyType == "00003")
            //{
            //    ec_propertyData.DefaultValueEnum = ec_propertyData.DefaultValue;
            //    ec_propertyData.DefaultValue = "";
            //}
            var jsonData = new
            {
                ec_property = ec_propertyData,
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取左侧树形数据（属性的tree，根据属性组进行分组）
        /// <summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTree(string ProjectId)
        {
            var data = ec_propertyIBLL.GetTree(ProjectId);
            return Success(data);
        }

        /// <summary>
        /// 获取属性树形数据（第一级为属性组，第二级为属性）。
        /// 场合：
        /// 如，报表输出时的参数xue
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPropTreeData(string ProjectId, bool isShowCheck = false)
        {
            var data = ec_propertyIBLL.GetPropTreeData(ProjectId, isShowCheck);
            return Success(data);
        }
        /// <summary>
        /// 命名规则里用的数据，某个对象分类下拥有的属性
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="ObjectTypeId"></param>
        /// <param name="isShowCheck">前端是否会显示勾选框</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPropTreeDataByType(string ProjectId, string ObjectTypeId, bool isShowCheck = false, string exceptionProp = "")
        {
            var data = ec_propertyIBLL.GetPropTreeDataByType(ProjectId, ObjectTypeId, isShowCheck, exceptionProp);
            return Success(data);
        }

        /// <summary>
        /// 获取对象类型属性表数据
        /// <summary>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetObjectTypePById(string objectTypeID, string ProjectId)
        {
            var data = ec_objecttypepIBLL.GetObjectTypePById(objectTypeID, ProjectId);//网页端
            return Success(data);
        }

        /// <summary>
        /// 获取一个
        /// <summary>
        /// <param name="objectTypeID">对象类型ID</param>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetObjectTypeP(string objectTypeID, string propertyID, string ProjectId)
        {
            var tb = ProjectSugar.TableName<ec_objecttypepEntity>(ProjectId);
            var data = SqlSugarHelper.Db.Queryable<ec_objecttypepEntity>().AS(tb).First(x => x.ObjectTypeID == objectTypeID && x.PropertyID == propertyID);
            return Success(data);
        }
        /// <summary>
        /// 获取属性反向关联的对象类型表数据
        /// <summary>
        /// <param name="propertyID">属性ID</param>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetObjectTypeAssigned2Property(string propertyID, string ProjectId)
        {
            var data = ec_objecttypepIBLL.GetPropertyByObjectId(propertyID, ProjectId);
            return Success(data);
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string ProjectId)
        {
            ec_propertyIBLL.DeleteEntity(keyValue, ProjectId);
            return Success("删除成功！");
        }
        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string strEntity, string ProjectId)
        {
            ec_propertyEntity entity = strEntity.ToObject<ec_propertyEntity>();
            //if (entity.PropertyType == "00003")
            //{
            //    entity.DefaultValue = entity.DefaultValueEnum;
            //}
            //属性名称不允许重复
            if (keyValue == GlobalObject.fakeID)
            {
                var settringData = new ec_projectSettingsEntity();
                settringData.SettingName = GlobalObject.projSetting_TagNumber_CADBlockAlias;
                settringData.SettingValue = entity.CADBlockAlias;
                //只是为了保存位号的CAD
                var settingTbName = ProjectSugar.TableName<ec_projectSettingsEntity>(ProjectId);
                var existvalue = SqlSugarHelper.Db.Queryable<ec_projectSettingsEntity>().AS(settingTbName).First(x => x.SettingName == GlobalObject.projSetting_TagNumber_CADBlockAlias);
                if (existvalue == null)
                {
                    settringData.SettingID =  Guid.NewGuid().ToString();
                   
                    SqlSugarHelper.Db.Insertable<ec_projectSettingsEntity>(settringData).AS(settingTbName).ExecuteCommand();
                }
                else
                {
                    settringData.SettingID = existvalue.SettingID;
                    SqlSugarHelper.Db.Updateable<ec_projectSettingsEntity>(settringData).AS(settingTbName).ExecuteCommand();
                }
                return Success("保存成功！");
            }
            var data = ec_propertyIBLL.GetList("{ProjectId:\"" + ProjectId + "\"}").ToList();
            data = data.FindAll(x => x.PropertyName == entity.PropertyName);
            if (data != null && data.Count > 0)
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    data = data.FindAll(x => x.PropertyID != keyValue);
                    if (data != null && data.Count > 0)
                    {
                        return Fail("属性名称不允许重复！");
                    }
                }
                else
                {
                    return Fail("属性名称不允许重复！");
                }
            }
            ec_propertyIBLL.SaveEntity(keyValue, entity, ProjectId);
            return Success("保存成功！");
        }


        /// <summary>
        /// 保存对象类型属性表数据（新增）
        /// <param name="objectTypeID">对象类型ID</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult SaveObjectTypeP(string objectTypeID, string ProjectId, [FromBody] List<ec_objecttypepEntity> entityList)
        {
            //var asyncContent = Request.Content.ReadAsStringAsync().Result;
            //List<ec_enginedataEntity> entitys = asyncContent.ToObject<List<ec_enginedataEntity>>();

            //List<ec_objecttypepEntity> entityList = strEntity.ToList<ec_objecttypepEntity>();
            if (entityList == null)
            {
                return Success("");
            }
            ec_objecttypepIBLL.SaveEntityByObjectType(objectTypeID, entityList, ProjectId);
            return Success("保存成功！");
        }

        /// <summary>
        /// 网页上，属性界面去配置需要关联到哪些对象类型
        /// <param name="propertyID">属性ID</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult SavePropertyO(string propertyID, string objectTypeIDs, string ProjectId)
        {
            ec_objecttypepIBLL.SaveEntityByProperty(propertyID, objectTypeIDs, ProjectId);
            return Success("保存成功！");
        }

        #endregion
         
    }
}
