package com.gyee.wisdom.dao.sql.system.entity;

import com.gyee.wisdom.common.data.DataUtil;
import com.gyee.wisdom.common.data.ToData;
import com.gyee.wisdom.common.data.system.model.Role;
import com.gyee.wisdom.common.data.system.model.User;
import com.gyee.wisdom.dao.sql.ModelConstants;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.jws.WebParam;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Data
@NoArgsConstructor
@ToString
@EqualsAndHashCode()
@Entity
@Table(name = ModelConstants.ROLE_)
public class RoleEntity implements ToData<Role> {
    /** 主键ID */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = ModelConstants.ID_)
    private String id;

    /** 角色名*/
    @Column(name=ModelConstants.NAME_)
    private String name;

    /** 描述 */
    @Column(name=ModelConstants.DESCRITION_)
    private String description;

    /** 状态 是否禁用*/
    @Column(name=ModelConstants.DISABLED_)
    private boolean disabled;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name=ModelConstants.USER_ROLE,
            joinColumns=@JoinColumn(name=ModelConstants.ROLE_ID, referencedColumnName=ModelConstants.ID_),
            inverseJoinColumns=@JoinColumn(name=ModelConstants.USER_ID, referencedColumnName=ModelConstants.ID_))
    private List<UserEntity> userEntityList;

    @ManyToMany()
    @JoinTable(
            name=ModelConstants.ROLE_MENU,
            joinColumns=@JoinColumn(name=ModelConstants.ROLE_ID, referencedColumnName=ModelConstants.ID_),
            inverseJoinColumns=@JoinColumn(name=ModelConstants.MENU_ID, referencedColumnName=ModelConstants.ID_))
    private List<MenuEntity> menuEntityList;



    public RoleEntity(Role role) {
        this.id = role.getId();
        this.name = role.getName();
        this.disabled = role.isDisabled();
        this.description = role.getDescription();

        List<UserEntity> userEntityList=new ArrayList<>();
        for (int i = 0; i < role.getMenuList().size(); i++) {
            UserEntity userEntity=new UserEntity(role.getUserList().get(i));
            userEntityList.add(userEntity);
        }
        this.userEntityList = userEntityList;


        List<MenuEntity> menuEntityList=new ArrayList<>();
        for (int i = 0; i < role.getMenuList().size(); i++) {
            MenuEntity menuEntity=new MenuEntity(role.getMenuList().get(i));
            menuEntityList.add(menuEntity);
        }
        this.menuEntityList = menuEntityList;
    }

    @Override
    public Role toData() {
        Role role = new Role();
        role.setId(id);
        role.setName(name);
        role.setDescription(description);
        role.setDisabled(disabled);
        role.setUserList(DataUtil.convertDataList(this.userEntityList));
        //role.setMenuList(DataUtil.convertDataList(this.menuEntityList));

        return role;
    }


}
