package flow

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hz_crm_api/models/system"
	"strings"
	"time"
)

// 获取审批工作流（基础）
func GetApprovalFlow(flowId int) (approvalFlow *system.ApprovalFlowItem, err error) {
	approvalFlow, err = system.GetByFlowItemId(flowId)
	if err != nil {
		err = errors.New("查询审批流程失败：Err:" + err.Error())
		return
	}
	flowNodeList := make([]*system.ApprovalFlowNodeList, 0)
	approvalFlowNodeList, err := system.GetListByFlowId(approvalFlow.FlowId, approvalFlow.CurrVersion)
	if err != nil {
		err = errors.New("查询审批节点失败：Err:" + err.Error())
		return
	}
	for _, approvalFlowNode := range approvalFlowNodeList {
		userList, tmpErr := getAdminListByUser(approvalFlowNode.User, approvalFlow.ProductId)
		if tmpErr != nil {
			err = errors.New("获取审批人失败：Err:" + tmpErr.Error())
			return
		}
		for _, user := range userList {
			userInfo := system.User{
				AdminId:      user.AdminId,
				RoleId:       user.RoleId,
				Name:         user.RealName,
				RoleName:     user.RoleName,
				RoleTypeCode: user.RoleTypeCode,
				Mobile:       user.Mobile,
			}
			approvalFlowNode.UserList = append(approvalFlowNode.UserList, userInfo)
		}
		if len(approvalFlowNode.UserList) > 0 {
			flowNodeList = append(flowNodeList, approvalFlowNode)
		}
	}
	approvalFlow.NodeList = flowNodeList

	return
}

// 节点用户
type NodeUser struct {
	UserType string `json:"user_type";description:"用户类型，枚举值，user：指定人，manager：主管，role：角色"`
	User     string `json:"user";description:"所属用户，多个用英文,隔开；用户类型为user代表指定人id，manager代表几级主管，role代表角色id"`
}

// 获取审批人信息
func getAdminListByUser(userStrList string, productId int) (adminList []*system.Admin, err error) {
	nodeUserList := make([]NodeUser, 0)
	err = json.Unmarshal([]byte(userStrList), &nodeUserList)
	if err != nil {
		return
	}
	firstAdminList := make([]*system.Admin, 0)
	for _, userInfo := range nodeUserList {
		userType := userInfo.UserType
		user := userInfo.User
		tmpAdminList := make([]*system.Admin, 0)
		switch userType {
		case "user":
			tmpAdminList, err = system.GetAdminListByIds(user)
		case "manager":
			roleTypeCode := ``
			if productId == 1 {
				roleTypeCode = `ficc_admin`
			} else if productId == 1 {
				roleTypeCode = `rai_admin`
			}
			if roleTypeCode == `` {
				err = errors.New("找不到对应的主管")
				return
			}
			tmpAdminList, err = system.GetAdminListByRoleCode(roleTypeCode)
		case "role": //角色类型
			roleSlice := strings.Split(user, ",")
			for _, roleId := range roleSlice {
				list, tmpErr := system.GetAdminListByRoleId(roleId)
				if tmpErr != nil {
					err = tmpErr
					return
				}
				tmpAdminList = append(tmpAdminList, list...)
			}
		}
		firstAdminList = append(firstAdminList, tmpAdminList...)
	}

	userMap := make(map[int]*system.Admin)
	for _, adminInfo := range firstAdminList {
		fmt.Println(userMap)
		//如果不在，那么就插入用户列表，避免同一个节点重复添加用户
		if _, ok := userMap[adminInfo.AdminId]; !ok {
			adminList = append(adminList, adminInfo)
			userMap[adminInfo.AdminId] = adminInfo
		}
	}

	return
}

// 获取审批工作流（基础）
func GetApprovalFlowDetail(flowId int) (approvalFlow *system.ApprovalFlowItem, err error) {
	approvalFlow, err = system.GetByFlowItemId(flowId)
	if err != nil {
		err = errors.New("查询审批流程失败：Err:" + err.Error())
		return
	}
	flowNodeList := make([]*system.ApprovalFlowNodeList, 0)
	approvalFlowNodeList, err := system.GetListByFlowId(approvalFlow.FlowId, approvalFlow.CurrVersion)
	if err != nil {
		err = errors.New("查询审批节点失败：Err:" + err.Error())
		return
	}
	for _, approvalFlowNode := range approvalFlowNodeList {
		userList, tmpErr := getAdminListByUser(approvalFlowNode.User, approvalFlow.ProductId)
		if tmpErr != nil {
			err = errors.New("获取审批人失败：Err:" + tmpErr.Error())
			return
		}
		for _, user := range userList {
			userInfo := system.User{
				AdminId:      user.AdminId,
				RoleId:       user.RoleId,
				Name:         user.RealName,
				RoleName:     user.RoleName,
				RoleTypeCode: user.RoleTypeCode,
				Mobile:       user.Mobile,
			}
			approvalFlowNode.UserList = append(approvalFlowNode.UserList, userInfo)
		}

		var userArr []system.NodeUser
		tmpErr = json.Unmarshal([]byte(approvalFlowNode.User), &userArr)
		if tmpErr != nil {
			err = errors.New("获取审批人失败：Err:" + tmpErr.Error())
			return
		}
		approvalFlowNode.UserArr = userArr

		if len(approvalFlowNode.UserList) > 0 {
			flowNodeList = append(flowNodeList, approvalFlowNode)
		}
	}
	approvalFlow.NodeList = flowNodeList

	return
}

// 节点配置
func EditFlow(editFlowReq system.EditFlowReq) (err error) {
	flowId := editFlowReq.FlowId
	//获取流程配置详情
	approvalFlow, err := system.GetByFlowItemId(flowId)
	if err != nil {
		return
	}
	if approvalFlow == nil {
		err = errors.New("找不到该审批单")
		return
	}

	nodeList := editFlowReq.NodeList

	flowNodeList := make([]*system.ApprovalFlowNode, 0)
	//newVer := approvalFlow.CurrVersion + 1

	for _, node := range nodeList {
		if len(node.User) <= 0 {
			err = errors.New("审批/抄送节点用户不能为空")
			return
		}
		for _, nodeUser := range node.User {
			if nodeUser.User == "" {
				err = errors.New("数据异常")
				return
			}
		}
		userByte, tmpErr := json.Marshal(node.User)
		if tmpErr != nil {
			err = errors.New("格式化用户失败,Err:" + tmpErr.Error())
			return
		}
		nodeName := ""
		if node.NodeType == "check" {
			nodeName = `审批人`
		} else {
			nodeName = `抄送人`
		}
		flowNode := &system.ApprovalFlowNode{
			//NodeId     :1,
			FlowId:     flowId,
			NodeName:   nodeName,         // 流程节点名称
			PrevNodeId: 0,                //上级节点id，为0代表是开始节点
			NextNodeId: 0,                //下级节点id，为0代表是结束节点
			NodeType:   node.NodeType,    //节点类型，审批人：check；抄送人：cc（Carbon Copy），默认是：check
			AuditType:  1,                //多人审批时，1：或签（一名审批人同意即可），2：会签（需所有审批人同意）
			User:       string(userByte), //所属用户，多个用英文,隔开；用户类型为user代表指定人id，manager代表几级主管，role代表角色类型
			//Version:    newVer,           // 所属流程版本
			CreateTime: time.Now(), // 创建时间
		}
		flowNodeList = append(flowNodeList, flowNode)
	}

	err = system.UpdateFlow(flowId, flowNodeList)
	return
}
