class Organizations::ClasController < Organizations::BaseController
    before_action :load_organization
    before_action :load_cla, only: [:show, :update, :destroy]
    before_action :check_user_can_edit_org, only: [:create, :update, :destroy]

    def index
        @cla = @organization.cla
    end

    def show 
        @is_admin = can_edit_org?
        @is_member = @organization.is_member?(current_user.id)
        @is_sign = @organization.is_sign?(current_user.id)
        @cla_sign_email = if @is_sign 
            @organization.cla_sign_email(current_user.id)
        end
    end

    def create
        tip_exception("您的组织还未拥有创建CLA权限，请联系管理员") if @organization.enabling_cla == false
        ActiveRecord::Base.transaction do
            if @organization.cla.present?
                return tip_exception("组织已存在CLA！") 
            else 
                Organizations::CreateClaForm.new(cla_params).validate!
                @cla = Cla.build(cla_params,@organization.id)
            end
        end
        rescue Exception => e
            uid_logger_error(e.message)
            tip_exception(e.message)
    end

    def update
        ActiveRecord::Base.transaction do
            Organizations::CreateClaForm.new(cla_params).validate!
            @cla.update(cla_params)
        end
        rescue Exception => e
            uid_logger_error(e.message)
            tip_exception(e.message)
    end

    def destroy
        tip_exception("组织CLA已被签署，无法删除") if @cla.user_clas.size > 0
        ActiveRecord::Base.transaction do
            @cla.destroy!
        end
        render_ok
        rescue Exception => e
            uid_logger_error(e.message)
            tip_exception(e.message)
    end


    private
    def cla_params
        params.permit(:name, :key, :content, :pr_need)
    end

    def load_organization
        @organization = Organization.find_by(login: params[:organization_id]) || Organization.find_by(id: params[:organization_id])
        return render_not_found("组织不存在") if @organization.nil?
    end

    def load_cla
        @cla = Cla.find_by!(organization:@organization, key: params[:id])
    end

end
