using System;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.MS.Domain.Entities.WB;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
using System.Collections.Generic;
using APT.BaseData.Domain.Enums;
using System.Linq;
using APT.BaseData.Domain.Entities;
using APT.MS.Domain.Enums;

namespace APT.SC.WebApi.Controllers.Api.WB
{
    [Route("api/WB/WBProjectInput")]
    public class WBProjectController : AuthorizeApiController<T_WB_PROJECT_INPUT>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public WBProjectController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_WB_PROJECT_INPUT entity)
        {
            return SafeExecute(() =>
            {
                if (!entity.DEPARTMENT_ID.HasValue)
                {
                    throw new Exception("请选择外包单位！");
                }
                var isRepeat = GetEntity<T_WB_PROJECT_INPUT>(t => t.NAME == entity.NAME && t.ID != entity.ID && !t.IS_DELETED);
                if (isRepeat != null)
                {
                    throw new Exception("已存在项目名【" + entity.NAME + "】，请更换！");
                }
                if (string.IsNullOrEmpty(entity.MineType))
                {
                    throw new Exception("请选择生产单元！");
                }
                T_FM_PERSON newPerson = null;
                T_FM_USER newUser = null;
                T_FM_USER_BELONG_ROLE belongRole1 = null;
                T_FM_USER_BELONG_ROLE belongRole2 = null;
                T_WB_REGISTER newRegister = null;
                T_WB_REGISTER_2 newRegisterSafe = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                T_FM_USER_PRODUCTION_UNIT unit = null;
                List<T_FM_USER_PRODUCTION_UNIT> productionUnit = null;
                entity.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                entity.LAUNCH_USER_ID = (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.USER_ID == entity.SCENE_USER_ID)
                    {
                        throw new Exception("建设项目负责人和建设项目现场负责人不能是同一个人");
                    }
                    if (!entity.USER_ID_SAFE.HasValue)
                    {
                        //}
                        //var isrepeat = GetEntity<T_FM_USER>(t => t.CODE == entity.WB_USER_CODE);
                        //if (isrepeat == null)
                        //{
                        newUser = new T_FM_USER();
                        newPerson = new T_FM_PERSON();
                        newPerson.ID = Guid.NewGuid();
                        newPerson.CODE = entity.WB_USER_CODE;
                        newPerson.NAME = entity.WB_USER_NAME;
                        newPerson.SEX = 0;
                        newPerson.TEL = entity.WB_USER_PHONE;
                        newPerson.ORG_ID = entity.ORG_ID;
                        newUser.ID = Guid.NewGuid();
                        newUser.CODE = entity.WB_USER_CODE;
                        newUser.NAME = entity.WB_USER_NAME;
                        newUser.SEX = 0;
                        newUser.PHONE = entity.WB_USER_PHONE;
                        newUser.ENTRYTIME = DateTime.Now;
                        newUser.PERSON_ID = newPerson.ID;
                        newUser.PROJECT_ID = entity.ID;//当人员有多个项目时 不一定准确 但是可以根据外包单位  DEPARTMENT_ID 去查找
                        newUser.MineType = entity.MineType;
                        newUser.DEPARTMENT_ID = entity.DEPARTMENT_ID;//人员部门绑定 外包单位
                        entity.USER_ID_SAFE = newUser.ID;

                        var mineTypeList = entity.MineType.Split("_");
                        unit = new T_FM_USER_PRODUCTION_UNIT();
                        productionUnit = new List<T_FM_USER_PRODUCTION_UNIT>();
                        foreach (var mineTypeItem in mineTypeList)
                        {
                            if (mineTypeItem != "")
                            {
                                var enumList = this.GetEntity<T_FM_ENUMS>(t => t.CODE == "BSMineTypeEnum" && t.VALUE == int.Parse(mineTypeItem));
                                unit.ORG_ID = entity.ORG_ID;
                                unit.USER_ID = newUser.ID;
                                unit.ENUMS_ID = enumList?.ID;
                                unit.Nav_Enums = null;
                                productionUnit.Add(unit);
                            }
                        }

                        MD5 md5 = MD5.Create();
                        string NewPwd = DataHelper.MD5Encrypt32(md5, entity.WB_USER_PASSWORD);
                        newUser.PASSWORD = NewPwd;
                        newUser.ORG_ID = entity.ORG_ID;
                        var Tenant = this.Request.Headers["Tenant"];
                        using (var context = new MigrationContext(ConfigurationManager.ConnectionStrings["default"]))
                        {
                            T_OP_ALLUSER alluser = new T_OP_ALLUSER();
                            alluser.CODE = entity.WB_USER_CODE;
                            alluser.TENANT = Tenant;
                            alluser.ORG_ID = entity.ORG_ID;
                            alluser.PHONE = entity.WB_USER_PHONE;
                            context.AddEntity(alluser);
                            context.SaveChanges();
                        }
                    }
                    //权限 
                    if (entity.USER_ID_SAFE.HasValue)
                    {
                        var role1 = this.GetEntity<T_FM_ROLE>(t => t.NAME == "外包App用户");
                        var role2 = this.GetEntity<T_FM_ROLE>(t => t.NAME == "外包安全员");
                        var userRole = GetEntities<T_FM_USER_BELONG_ROLE>(e => e.USER_ID == entity.USER_ID_SAFE.Value && (e.BELONG_ROLE_ID == role1.ID || e.BELONG_ROLE_ID == role2.ID), null, null);
                        if (userRole == null || !userRole.Any() || userRole.Count() < 2)
                        {
                            if (role1 != null)
                            {
                                belongRole1 = new T_FM_USER_BELONG_ROLE();
                                belongRole1.USER_ID = entity.USER_ID_SAFE.Value;
                                belongRole1.BELONG_ROLE_ID = role1.ID;
                                belongRole1.ORG_ID = entity.ORG_ID;
                            }
                            if (role2 != null)
                            {
                                belongRole2 = new T_FM_USER_BELONG_ROLE();
                                belongRole2.USER_ID = entity.USER_ID_SAFE.Value;
                                belongRole2.BELONG_ROLE_ID = role2.ID;
                                belongRole2.ORG_ID = entity.ORG_ID;
                            }
                        }
                    }

                    var check = GetEntity<T_WB_REGISTER>(e => e.PROJECT_ID == entity.ID);
                    if (check == null || check.ID == Guid.Empty)
                    {
                        newRegister = new T_WB_REGISTER();
                        newRegister.ID = Guid.NewGuid();
                        newRegister.ORG_ID = entity.ORG_ID;
                        newRegister.PROJECT_ID = entity.ID;
                        newRegister.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                        newRegister.NAME = entity.NAME;
                        newRegister.UNIT_NAME = entity.UNIT_NAME;
                        newRegister.WB_USER_NAME = entity.WB_USER_NAME;
                        newRegister.WB_USER_PHONE = entity.WB_USER_PHONE;
                        newRegister.CONSTRUCTION_NAME = entity.CONSTRUCTION_NAME;
                        sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包单位信息登记表", newRegister.ID, entity.ORG_ID, entity.USER_ID_SAFE.Value, entity.WB_USER_NAME, DateTime.Now, DateTime.Now.AddMonths(1), 1, "WB004");

                        //外包安全员 也绑定信息
                        var workTypeSafe = GetEntity<T_WB_WORKTYPE>(e => e.WORKTYPE.HasValue && e.WORKTYPE.Value == WORKTYPE.安全员);
                        newRegisterSafe = new T_WB_REGISTER_2();
                        newRegisterSafe.ID = Guid.NewGuid();
                        newRegisterSafe.ORG_ID = entity.ORG_ID;
                        newRegisterSafe.PARENT_ID = newRegister.ID;
                        newRegisterSafe.NAME = entity.WB_USER_NAME;
                        newRegisterSafe.WORKTYPE = WORKTYPE.安全员;
                        newRegisterSafe.WORKTYPE_ID = (workTypeSafe == null ? null : workTypeSafe.ID);
                        newRegisterSafe.PHONE = entity.WB_USER_PHONE;
                        newRegisterSafe.IS_LOGIN = true;
                        newRegisterSafe.PROJECT_ID = entity.ID;
                        newRegisterSafe.USERID = entity.USER_ID_SAFE;
                        var us = GetEntity<T_FM_USER>(entity.USER_ID_SAFE.Value);
                        if (us != null)
                        {
                            newRegisterSafe.SEX = (FMSexEnum)us.SEX;
                        }
                    }
                    else
                    {
                        newRegister = check;
                        newRegister.NAME = entity.NAME;
                        newRegister.UNIT_NAME = entity.UNIT_NAME;
                        newRegister.WB_USER_NAME = entity.WB_USER_NAME;
                        newRegister.WB_USER_PHONE = entity.WB_USER_PHONE;
                        newRegister.CONSTRUCTION_NAME = entity.CONSTRUCTION_NAME;
                    }

                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (newUser != null)
                        AddEntityNoCommit(newUser);
                    if (newPerson != null)
                        AddEntityNoCommit(newPerson);
                    if (belongRole1 != null)
                        AddEntityNoCommit(belongRole1);
                    if (belongRole2 != null)
                        AddEntityNoCommit(belongRole2);
                    if (newRegister != null)
                        UpdateEntityNoCommit(newRegister);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (productionUnit != null && productionUnit.Any())
                        BantchSaveEntityNoCommit(productionUnit);
                    if (newRegisterSafe != null)
                        UpdateEntityNoCommit(newRegisterSafe);
                });
                return true;
            });
        }
    }
}
